@kuafucloud/data 0.0.0-stage → 0.1.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/admin/admin/extension.zip +0 -0
  2. package/dist/admin/index.d.ts +2 -0
  3. package/dist/admin/index.js +2 -0
  4. package/dist/admin/meta/admin.json +74 -0
  5. package/dist/admin/meta/extension-manifest.json +298 -0
  6. package/dist/facade/index.d.ts +272 -0
  7. package/dist/facade/index.js +11 -0
  8. package/dist/public/index.js +78 -0
  9. package/dist/public/runtime-services/core/index.js +334 -0
  10. package/dist/runtime-services/app/index.js +341 -0
  11. package/dist/runtime-services/app/service-module.config.json +16 -0
  12. package/dist/runtime-services/app-simulator/index.js +341 -0
  13. package/dist/runtime-services/app-simulator/service-module.config.json +12 -0
  14. package/dist/runtime-services/mini-program/index.js +341 -0
  15. package/dist/runtime-services/mini-program/service-module.config.json +12 -0
  16. package/dist/runtime-services/mini-program-simulator/index.js +341 -0
  17. package/dist/runtime-services/mini-program-simulator/service-module.config.json +12 -0
  18. package/dist/runtime-services/site/index.js +341 -0
  19. package/dist/runtime-services/site/service-module.config.json +12 -0
  20. package/dist/simulation/artifact/meta/database.json +72 -0
  21. package/dist/simulation/artifact/meta/manifest.json +286 -0
  22. package/dist/simulation/artifact/meta/permissions.json +86 -0
  23. package/dist/simulation/artifact/meta/runtime-meta.json +29 -0
  24. package/dist/simulation/artifact/meta/schema.json +70 -0
  25. package/dist/simulation/artifact/server/worker/index.js +39 -0
  26. package/dist/simulation/artifact/server/worker/monitoring-contract.json +7 -0
  27. package/dist/simulation/index.d.ts +1 -0
  28. package/dist/simulation/index.js +1 -0
  29. package/dist/types/client/index.d.ts +87 -0
  30. package/dist/types/runtime-services/app/index.d.ts +2 -0
  31. package/dist/types/runtime-services/app-simulator/index.d.ts +2 -0
  32. package/dist/types/runtime-services/core/index.d.ts +73 -0
  33. package/dist/types/runtime-services/mini-program/index.d.ts +2 -0
  34. package/dist/types/runtime-services/mini-program-simulator/index.d.ts +2 -0
  35. package/dist/types/runtime-services/site/index.d.ts +2 -0
  36. package/extension-manifest.json +265 -0
  37. package/package.json +99 -4
  38. package/README.md +0 -3
@@ -0,0 +1,39 @@
1
+ var yp=Object.defineProperty;var Rc=(t,e)=>{for(var r in e)yp(t,r,{get:e[r],enumerable:!0})};import{AsyncLocalStorage as Pp}from"node:async_hooks";import{createHash as jp}from"node:crypto";function Ac(t){return Object.freeze({kind:"service",id:bp(t.id)})}function bp(t){let e=t.trim();if(!e||e!==t)throw new TypeError("Client Key id \u5FC5\u987B\u662F\u975E\u7A7A\u4E14\u65E0\u9996\u5C3E\u7A7A\u767D\u7684\u7A33\u5B9A\u5B57\u7B26\u4E32\u3002");return e}var _y=Ac({id:"system.account"});function or(t,e=""){let r=e.startsWith("/")?e:`/${e}`,n=typeof t.projectEnvKey=="string"&&/^[a-z0-9][a-z0-9_-]{0,62}$/u.test(t.projectEnvKey.trim().toLowerCase())?t.projectEnvKey.trim().toLowerCase():"prod";return`/api/project/${String(t.projectId)}/env/${encodeURIComponent(n)}/ext/${t.extensionId}${r}`}var Ty=4320*6e4,Ry=256*1024;var Uo="global",wp=Object.freeze({homeRegion:"global",splitRegions:!1});function Dt(t=wp){if(typeof t=="string")try{t=JSON.parse(t)}catch{throw new Error("region.project_policy_invalid")}if(!t||typeof t!="object"||Array.isArray(t))throw new Error("region.project_policy_invalid");let e=t;if(Object.keys(e).some(r=>r!=="homeRegion"&&r!=="splitRegions")||!Pe(e.homeRegion)||typeof e.splitRegions!="boolean")throw new Error("region.project_policy_invalid");return Object.freeze({homeRegion:e.homeRegion,splitRegions:e.splitRegions})}function Pe(t){return t==="cn"||t==="global"}function ws(t){let e={status:"unknown",region:null,countryCode:null,source:"unavailable"},{policy:r}=t;if(!Pe(r.homeRegion)||typeof r.splitRegions!="boolean")throw new Error("region.project_policy_invalid");if(!r.splitRegions)return Object.freeze({region:r.homeRegion,source:"project-fixed",detection:e});if(t.accountRegion!=null){if(!Pe(t.accountRegion))throw new Error("region.account_region_invalid");return Object.freeze({region:t.accountRegion,source:"account",detection:e})}if(t.anonymousRegion!=null){if(!Pe(t.anonymousRegion))throw new Error("region.anonymous_region_invalid");return Object.freeze({region:t.anonymousRegion,source:"anonymous",detection:e})}let n=[t.ipDetection,t.deviceDetection].find(s=>s?.status==="known");if(n){if(!Pe(n.region)||n.source!=="trusted-ip"&&n.source!=="device")throw new Error("region.detection_invalid");return Object.freeze({region:n.region,source:n.source,detection:Object.freeze({...n})})}return Object.freeze({region:r.homeRegion,source:"project-default",detection:e})}function Oc(t){return typeof t=="string"?ir(t):Array.isArray(t)&&t.length>0&&t.length<=1e3&&t.every(ir)&&new Set(t).size===t.length}function ir(t){return typeof t=="string"&&t.length>0&&!/[\\\u0000-\u001f\u007f]/u.test(t)&&!t.split("/").some(e=>!e||e==="."||e==="..")&&new TextEncoder().encode(t).length<=1023}function Ko(t){return!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).some(([e,r])=>!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/u.test(e)||typeof r!="string"||/[\r\n]/u.test(r))?!1:new TextEncoder().encode(JSON.stringify(t)).length<=2048}function Ue(t,e){if(!Number.isSafeInteger(e)||e<1||e>16384)throw new TypeError("\u76D1\u63A7\u6587\u672C\u5BB9\u91CF\u65E0\u6548\u3002");return t.slice(0,e).replace(/Bearer\s+[a-zA-Z0-9._~+\/-]+/giu,"Bearer [redacted]").replace(/\b((?:proxy[-_]?)?authorization|(?:set[-_]?)?cookie)["']?\s*[:=]\s*[^\r\n]*/giu,"$1=[redacted]").replace(/\b(password|(?:access[_-]?|refresh[_-]?)?token|secret|api[_-]?key)["']?\s*[:=]\s*(?:"(?:\\.|[^"\\\r\n])*(?:"|$)|'(?:\\.|[^'\\\r\n])*(?:'|$)|[^\r\n,;]*)/giu,"$1=[redacted]").replace(/https?:\/\/[^\s)]+/giu,r=>{try{let n=new URL(r);return`${n.origin}${n.pathname}`}catch{return"[url]"}}).replace(/(^|[^a-zA-Z0-9._%+-])[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/gu,"$1[email]").slice(0,e)}function Pc(t){if(!t)return[];let e=[];for(let r of t.slice(0,16384).split(/\r?\n/u).slice(0,64)){let n=/^(?:\s*at\s+(?:(.*?)\s+\()?|\s*(.*?)@)(.+?):(\d+):(\d+)\)?\s*$/u.exec(r);if(!n)continue;let s=n[3].replace(/\\/gu,"/");if(/node:|\/(?:node_modules|runtime-core|runtime-shell)\/|@kuafucloud\/(?:extension-kit|product-runtime)/u.test(s))continue;s=s.replace(/^https?:\/\/[^/]+/u,"").replace(/[?#].*$/u,"");let o=(n[1]??n[2]??"").trim();if(e.push(Ue(`${o}@${s}:${n[4]}:${n[5]}`,1024)),e.length===8)break}return Object.freeze(e)}function ar(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(t))throw new Error("\u5DE5\u4F5C\u533A\u8EAB\u4EFD\u4E0D\u662F\u6709\u6548\u7684 UUID\u3002");return t}function Bo(t){if(typeof t!="string"||!/^[A-Za-z0-9._-]{1,160}$/u.test(t)||t==="."||t==="..")throw new Error("\u5DE5\u4F5C\u533A\u4ED3\u5E93\u8EAB\u4EFD\u65E0\u6548\u3002");return t}function vs(t){if(t===".")return t;if(!t||t!==t.trim()||t.includes("\\")||t.split("/").some(e=>!e||e==="."||e===".."||/[:\u0000-\u001f\u007f]/u.test(e)))throw new Error("\u5DE5\u7A0B\u8DEF\u5F84\u5FC5\u987B\u662F\u5DE5\u4F5C\u533A\u5185\u7684\u89C4\u8303\u76F8\u5BF9\u8DEF\u5F84\u3002");return t}function vp(t){if(t.pathname!=="/codebases"&&!t.pathname.startsWith("/codebases/"))return null;let e=/^\/codebases\/~([^/]+)(\/.*)?$/u.exec(t.pathname);if(!e)throw new Error("\u5DE5\u7A0B\u9884\u89C8\u5730\u5740\u65E0\u6548\u3002");let r=vs(decodeURIComponent(e[1])),n=e[2]??"/";if(/^\/g(?:\/|$)/u.test(n))throw new Error("\u516C\u5F00\u9884\u89C8\u5730\u5740\u4E0D\u63A5\u53D7\u8FD0\u884C\u4EE3\u9645\u3002");return{relativePath:r,runtimePath:`${n}${t.search}`}}function Fo(t){let e=t.pathname.match(/^\/api\/project\/([1-9]\d*)\/env\/prod\/ext\/developer\/runtime\/developer\/preview\/([A-Za-z0-9_-]{1,160})\/target\/([^/]+)\/([^/]+)\/(browser|native-ios|native-android)(\/local\/.*)$/u),r=t.pathname.match(/^\/api\/project\/([1-9]\d*)\/env\/prod\/ext\/developer\/runtime\/developer\/preview\/([A-Za-z0-9_-]{1,160})\/([0-9a-f-]{36})(\/local\/.*)$/u),n=(e?.[6]??r?.[4]??t.pathname).match(/^\/local\/project\/([^/]+)\/env\/([^/]+)\/workspace\/([^/]+)(?:\/(.*))?$/u);if(!n)return null;try{let s=wn(n[1]),o=wn(n[2]),i=ar(wn(n[3])),a=r?{hostDeviceId:r[2],sessionId:ar(r[3])}:void 0,c=e?xp({hostDeviceId:e[2],kind:e[3],productId:wn(e[4]),surface:e[5]==="browser"?"browser":"native",...e[5]==="browser"?{}:{platform:e[5].slice(7)}}):void 0;if(r&&(r[1]!==s||o!=="prod")||e&&(e[1]!==s||o!=="prod"))return null;let l=n[4]?`/${n[4]}`:"/",u=/^\/repo\/([^/]+)(\/codebases\/.*)$/u.exec(l);if(!u&&/^\/(?:repo|codebases)(?:\/|$)/u.test(l))return null;let d=u?vp({pathname:u[2],search:t.search}):null,p=u?Bo(wn(u[1])):void 0;return{projectId:s,envKey:o,workspaceId:i,runtimePath:d?.runtimePath??`${l}${t.search}`,...a?{remotePreview:a}:{},...c?{remoteProduct:c}:{},...d?{codebaseRuntime:{repositoryId:p,relativePath:d.relativePath}}:{}}}catch{return null}}function xp(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("\u8FDC\u7AEF\u4EA7\u54C1\u76EE\u6807\u65E0\u6548\u3002");let e=t;if(Object.keys(e).some(r=>!["hostDeviceId","kind","productId","surface","platform"].includes(r))||typeof e.hostDeviceId!="string"||!/^[A-Za-z0-9_-]{1,160}$/u.test(e.hostDeviceId)||typeof e.productId!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(e.productId)||!["app","site","mini-program","extension","desktop"].includes(String(e.kind))||(e.surface==="native"?e.kind!=="app"||!["ios","android"].includes(String(e.platform)):e.surface!=="browser"||e.platform!==void 0))throw new Error("\u8FDC\u7AEF\u4EA7\u54C1\u76EE\u6807\u65E0\u6548\u3002");return{hostDeviceId:e.hostDeviceId,kind:e.kind,productId:e.productId,surface:e.surface,...e.platform?{platform:e.platform}:{}}}function wn(t,e=!0){let r=e?decodeURIComponent(t):t;if(!r||r.trim()!==r||r==="."||r===".."||/[\u0000-\u001f\u007f\\/]/u.test(r))throw new Error("\u5DE5\u4F5C\u533A\u516C\u5F00\u8303\u56F4\u65E0\u6548\u3002");return r}var Zy=8*1024*1024;var W=class extends Error{code;status;constructor(e,r){super(e),this.code=e,this.status=r,this.name="StorageProxyError"}};function Nc(t){let{allocationId:e,extensionId:r,credential:n,service:s}=t;if(t.namespace!==void 0&&t.namespace!=="tenant"&&t.namespace!=="platform")throw yt();let o=t.namespace==="platform"?"/__gateway/storage":"/__storage";if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u.test(e)||!/^[a-z][a-z0-9-]{0,62}$/u.test(r)||!/^[a-f0-9]{64}$/u.test(n))throw yt();let i={authorization:`Bearer ${n}`,"x-kuafu-storage-allocation":e,"x-kuafu-storage-extension":r},a=async(c,l={})=>{let u=l.sign?"/sign":l.list?"/list":l.bulkDelete?"/delete":`/object?key=${encodeURIComponent(Sp(l.key))}`,d;try{d=await s.fetch(new Request(`https://storage.internal${o}${u}`,{method:c,headers:{...i,...l.headers},body:l.body,signal:l.signal,redirect:"manual",...l.body instanceof ReadableStream?{duplex:"half"}:{}}))}catch{throw new W("storage.transport_unconfirmed")}if(d.headers.get("x-kuafu-storage-protocol")!==String(2)||d.status>=300&&d.status<400)throw await d.body?.cancel(),nt();return d};return{async sign(c,l){let u=await a("POST",{sign:!0,headers:{"content-type":"application/json"},body:JSON.stringify({requests:c,expiresAt:l})});if(u.status!==200)throw await kr(u);return(await u.json()).requests},async head(c){let l=await a("HEAD",{key:c});if(l.status===404)return await l.body?.cancel(),null;if(l.status!==200)throw await kr(l);return await l.body?.cancel(),Qo(l,c)},async get(c,l){let u;if(l?.range){let{offset:p,length:g}=l.range;if(!Number.isSafeInteger(p)||p<0||!Number.isSafeInteger(g)||g<1||!Number.isSafeInteger(p+g))throw yt();u={range:`bytes=${p}-${p+g-1}`}}let d=await a("GET",{key:c,headers:u,signal:l?.signal});if(d.status===404)return await d.body?.cancel(),null;if(d.status!==(l?.range?206:200)||!d.body)throw await kr(d);try{return{object:Qo(d,c),body:d.body}}catch(p){throw await d.body.cancel(),p}},async put(c){if(!Number.isSafeInteger(c.size)||c.size<0||!c.contentType||!Ko(c.metadata??{})||typeof c.body=="string"&&new TextEncoder().encode(c.body).length!==c.size||c.body instanceof Uint8Array&&c.body.byteLength!==c.size)throw yt();let l={"content-type":c.contentType,"x-kuafu-object-size":String(c.size),"x-kuafu-object-metadata":encodeURIComponent(JSON.stringify(c.metadata??{}))};if(c.condition.kind==="if-absent")l["if-none-match"]="*";else if(c.condition.kind==="if-match"&&c.condition.etag)l["if-match"]=c.condition.etag;else if(c.condition.kind==="replace")l["x-kuafu-write-mode"]="replace";else throw yt();let u=await a("PUT",{key:c.key,headers:l,body:c.body,signal:c.signal});if(u.status===412)return await u.body?.cancel(),{status:"condition-failed"};if(u.status!==201)throw await kr(u);await u.body?.cancel();let d=Qo(u,c.key);if(d.size!==c.size)throw nt();return{status:"written",object:d}},async list(c={}){if(c.prefix&&!ir(c.prefix.endsWith("/")?c.prefix.slice(0,-1):c.prefix)||c.limit!==void 0&&(!Number.isSafeInteger(c.limit)||c.limit<1||c.limit>1e3)||c.includeMetadata!==void 0&&typeof c.includeMetadata!="boolean")throw yt();let l=await a("POST",{list:!0,headers:{"content-type":"application/json"},body:JSON.stringify(c)});if(l.status!==200)throw await kr(l);let u;try{u=await l.json()}catch{throw nt()}let d=xs(u);if(!Array.isArray(d.objects)||d.objects.length>(c.limit??100)||d.cursor!==null&&typeof d.cursor!="string")throw nt();let p=d.objects.map(g=>Cc(g));if(p.some(g=>!g.key.startsWith(c.prefix??""))||new Set(p.map(g=>g.key)).size!==p.length)throw nt();return{objects:p,cursor:d.cursor}},async delete(c){if(!Oc(c))throw yt();let l=typeof c=="string"?await a("DELETE",{key:c}):await a("POST",{bulkDelete:!0,headers:{"content-type":"application/json"},body:JSON.stringify({keys:c})});if(l.status!==204)throw await kr(l);await l.body?.cancel()}}}function Qo(t,e){let r;try{r=JSON.parse(decodeURIComponent(t.headers.get("x-kuafu-object")??""))}catch{throw nt()}let n=Cc(r);if(n.key!==e)throw nt();return n}function Cc(t){let e=xs(t);if(!ir(e.key)||!Number.isSafeInteger(e.size)||Number(e.size)<0||typeof e.etag!="string"||!e.etag||e.contentType!==null&&typeof e.contentType!="string"||!Ko(e.metadata)||e.lastModified!==void 0&&(!Number.isSafeInteger(e.lastModified)||Number(e.lastModified)<0))throw nt();let r;if(e.checksum!==void 0){let n=xs(e.checksum);if(n.algorithm!=="sha256"||typeof n.value!="string"||!/^[a-f0-9]{64}$/u.test(n.value))throw nt();r={algorithm:"sha256",value:n.value}}return{key:e.key,size:e.size,etag:e.etag,contentType:e.contentType,metadata:{...e.metadata},...e.lastModified===void 0?{}:{lastModified:Number(e.lastModified)},...r?{checksum:r}:{}}}async function kr(t){let e={};try{e=xs(await t.json())}catch{}let r=typeof e.code=="string"&&/^storage\.[a-z0-9_]+$/u.test(e.code)?e.code:`storage.http_${t.status}`;return new W(r,t.status)}function xs(t){if(!t||typeof t!="object"||Array.isArray(t))throw nt();return t}function Sp(t){if(!ir(t))throw yt();return t}function yt(){return new W("storage.request_invalid")}function nt(){return new W("storage.response_invalid")}var kc="PLATFORM_OBJECT_STORAGE_RUNTIME",Ep=["objects","data-raw","monitor-raw","lake"];function Dc(t,e){if(typeof t=="string")try{t=JSON.parse(t)}catch{bt()}let r=_s(t,["schemaVersion","projectId","projectEnvKey","extensionId","regions"]);(r.schemaVersion!==1||r.projectId!==e.projectId||r.projectEnvKey!==e.projectEnvKey||r.extensionId!==e.extensionId||!/^[1-9][0-9]{0,15}$/u.test(e.projectId)||!/^[a-z0-9][a-z0-9_-]{0,62}$/u.test(e.projectEnvKey)||!/^[a-z][a-z0-9-]{0,62}$/u.test(e.extensionId))&&bt();let n=_s(r.regions,["cn","global"]),s={};Object.keys(n).length||bt();for(let[o,i]of Object.entries(n)){Pe(o)||bt();let a=_s(i,Ep),c={};for(let[l,u]of Object.entries(a)){l!=="objects"&&(o!==Uo||!(e.extensionId==="data"&&(l==="data-raw"||l==="lake")||e.extensionId==="developer"&&(l==="monitor-raw"||l==="lake")))&&bt();let d=_s(u,["allocationId","credential"]);(typeof d.allocationId!="string"||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u.test(d.allocationId)||typeof d.credential!="string"||!/^[a-f0-9]{64}$/u.test(d.credential))&&bt(),c[l]=Object.freeze({allocationId:d.allocationId,credential:d.credential})}Object.keys(c).length||bt(),s[o]=Object.freeze(c)}return Object.values(s).some(o=>o.objects)||bt(),Object.freeze({schemaVersion:1,projectId:e.projectId,projectEnvKey:e.projectEnvKey,extensionId:e.extensionId,regions:Object.freeze(s)})}function _s(t,e){return(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(r=>!e.includes(r)))&&bt(),t}function bt(){throw new W("storage.runtime_configuration_invalid")}var $c="(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-alpha\\.(?:0|[1-9]\\d*))?",yb=new RegExp(`^[a-z][a-z0-9]*(?:-[a-z0-9]+)*/v${$c}(?:/extension)?$`,"u"),bb=new RegExp(`^extensions/center/v${$c}(?:/extension)?$`,"u");function Ip(t){if(!t||typeof t!="object")return"cloudflare";let e=t.KUAFUCLOUD_RUNTIME_PLACEMENT;return e==="local-platform"?e:"cloudflare"}function $t(t){return Ip(t)==="local-platform"}var Tp=8e3,Rp=4e3,Lc=1024,Vo=new TextEncoder;function Ho(){let t=Tp-Lc,e,r=0,n=0,s=0,o=!1,i=(c,l)=>{let u=Mc(c);return!u||!/^monitor-[0-9a-f]{64}$/u.test(l)||e&&(e.sourceGrantId!==l||["projectId","projectEnvKey","productId","productRelease","runtime"].some(d=>e.source[d]!==u[d]))?!1:(e??={source:{...u,userId:null,routeTemplate:null},sourceGrantId:l},!0)},a=Rp;return{recordDroppedError(c,l){!o&&i(c,l)&&r++},recordOutputFailure(c,l){!o&&i(c,l)&&s++},finishDiagnostic(){if(o||(o=!0,!e||!(r||n||s)))return null;let c=JSON.stringify({event:"runtime.monitor",schemaVersion:1,kind:"diagnostic",...e,occurredAt:new Date().toISOString(),truncated:!1,droppedErrors:r,droppedTraces:n,outputFailures:s});return Vo.encode(c).byteLength<=Lc?c:null},encode(c,l){if(!/^monitor-[0-9a-f]{64}$/u.test(l))return null;let u=Mc(c.source);if(!u||c.schemaVersion!==1)return null;let d=c.kind==="error"?Ap(c,u):c.kind==="trace"?Op(c,u):null;if(!d||o||!i(u,l))return null;let p=()=>(d.kind==="error"?r++:n++,null),g=d.kind==="trace"?Math.min(t,a):t,w={...d,sourceGrantId:l},b=JSON.stringify(w);for(;Vo.encode(b).byteLength>g;){if(d.kind==="error")if(Object.keys(d.context.tags).length>0)d.context.tags={};else if(d.error.stack&&d.error.stack.split(`
2
+ `).length>2){let S=d.error.stack.split(`
3
+ `);d.droppedFrames+=1,d.error.stack=S.slice(0,-1).join(`
4
+ `)}else if(d.error.message.length>64)d.error.message=d.error.message.slice(0,Math.max(64,Math.floor(d.error.message.length/2)));else return p();else if(d.spans.length>0)d.spans.pop(),d.droppedSpans+=1;else return p();d.truncated=!0,b=JSON.stringify({...d,sourceGrantId:l})}let E=Vo.encode(b).byteLength;return t-=E,d.kind==="trace"&&(a-=E),b}}}function Mc(t){if(!t||!st(t.projectId,32)||!st(t.projectEnvKey,128)||!st(t.productId,128)||!st(t.productRelease,128)||!st(t.requestId,128)||t.runtime!=="server")return null;let e=t.routeTemplate;return e!==null&&(typeof e!="string"||e.length>512||!e.startsWith("/")&&e!=="queue"&&e!=="scheduled"||/[?\s\u0000-\u001f]/u.test(e))?null:{projectId:t.projectId,projectEnvKey:t.projectEnvKey,productId:t.productId,productRelease:t.productRelease,runtime:"server",requestId:t.requestId,routeTemplate:e,userId:t.userId===null?null:st(t.userId,128)?t.userId:null}}function Ap(t,e){if(!st(t.eventId,128)||!Uc(t.occurredAt)||!["handled","unhandled"].includes(t.mechanism)||!t.error||!t.context||!Wo(t.traceId)||!Wo(t.spanId))return null;let r=typeof t.error.stack=="string"?t.error.stack:"",n=Pc(r),s=n.length?`sha256:${jp("sha256").update(JSON.stringify(n)).digest("hex")}`:void 0,o=r.split(`
5
+ `),i=o.slice(0,12).map(u=>vn(u,256)),a=vn(t.error.message,1024),c=Kc(t.context.tags),l={code:zc(t.context.code),groupingKey:zc(t.context.groupingKey),tags:c.values};return{event:"runtime.monitor",schemaVersion:1,kind:"error",eventId:t.eventId,occurredAt:t.occurredAt,source:e,mechanism:t.mechanism,error:{name:vn(t.error.name,128),message:a,stack:r?i.join(`
6
+ `):null,...s?{stackDigest:s}:{}},context:l,traceId:t.traceId,spanId:t.spanId,truncated:c.dropped>0||r.length>i.join(`
7
+ `).length||typeof t.error.message=="string"&&t.error.message.length>1024,droppedFrames:Math.max(0,o.length-i.length)}}function Op(t,e){if(!st(t.traceId,128)||!Array.isArray(t.spans)||!Number.isSafeInteger(t.droppedSpans)||t.droppedSpans<0)return null;let r=t.sampling;if(!r||r.unit!=="trace"||(r.rule==="head-random"?!Number.isFinite(r.probability)||r.probability<0||r.probability>1||r.ruleVersion!==1:!["inherited","unknown"].includes(r.rule)||r.probability!==null||r.ruleVersion!==null))return null;let n=[];for(let s of t.spans.slice(0,100)){if(!st(s.spanId,128)||!Wo(s.parentSpanId)||!Uc(s.startedAt)||!["http","business","sql","rpc"].includes(s.kind)||!["running","finished"].includes(s.state)||!["ok","error"].includes(s.status)||s.durationMs!==null&&(!Number.isFinite(s.durationMs)||s.durationMs<0))return null;let o=Kc(s.attributes);n.push({spanId:s.spanId,parentSpanId:s.parentSpanId,name:vn(s.name,128),kind:s.kind,startedAt:s.startedAt,durationMs:s.durationMs,state:s.state,status:s.status,attributes:o.values,droppedAttributes:(Number.isSafeInteger(s.droppedAttributes)&&s.droppedAttributes>=0?s.droppedAttributes:0)+o.dropped})}return{event:"runtime.monitor",schemaVersion:1,kind:"trace",traceId:t.traceId,source:e,sampling:{unit:r.unit,rule:r.rule,probability:r.probability,ruleVersion:r.ruleVersion},spans:n,truncated:t.spans.length>n.length,droppedSpans:t.droppedSpans+t.spans.length-n.length}}function vn(t,e){return typeof t=="string"?Ue(t,e):""}function zc(t){return typeof t=="string"&&/^[A-Za-z0-9_.:/-]{1,128}$/u.test(t)?t:void 0}function st(t,e){return typeof t=="string"&&t.length<=e&&/^[A-Za-z0-9_.:+/-]+$/u.test(t)}function Wo(t){return t===null||st(t,128)}function Uc(t){return typeof t=="string"&&t.length<=32&&Number.isFinite(Date.parse(t))}function Kc(t){let e={};if(!t||typeof t!="object"||Array.isArray(t))return{values:e,dropped:0};let r=Object.entries(t);for(let[n,s]of r.slice(0,16))!/^[A-Za-z][A-Za-z0-9_.-]{0,47}$/u.test(n)||/token|password|secret|authorization|cookie|headers|body|sql|params/iu.test(n)||(typeof s=="string"?e[n]=vn(s,128):(typeof s=="boolean"||typeof s=="number"&&Number.isFinite(s))&&(e[n]=s));return{values:e,dropped:r.length-Object.keys(e).length}}var Dr,Ss=new Pp,Np=["log","info","debug","warn","error","assert","dir","dirxml","table","trace","count","countReset","time","timeLog","timeEnd","group","groupCollapsed","groupEnd","clear","profile","profileEnd","timeStamp"];function Bc(){if(Dr)return;let t=globalThis.console;Dr=t.info.bind(t);let e=()=>{};for(let r of Np)Object.defineProperty(t,r,{configurable:!0,writable:!0,value:e})}function Fc(t){let e=Ho(),r=()=>Ss.getStore()?.encoder??e;return Object.assign(n=>{if(!Dr)return!1;let s=r(),o=s.encode(n,t);if(o===null)return!1;try{return Dr(o),!0}catch{return s.recordOutputFailure(n.source,t),!1}},{recordDroppedError:n=>r().recordDroppedError(n,t)})}async function Qc(t,e){if(Ss.getStore())return t();let r={encoder:Ho(),tasks:new Set};return Ss.run(r,async()=>{try{return await t()}finally{let n=(async()=>{for(;r.tasks.size;)await Promise.allSettled([...r.tasks]);let s=r.encoder.finishDiagnostic();if(s&&Dr)try{Dr(s)}catch{}})();e?e(n):await n}})}function Vc(t){let e=Ss.getStore();return e?(e.tasks.add(t),t.then(()=>{e.tasks.delete(t)},()=>{e.tasks.delete(t)}),!0):!1}Bc();var m=Symbol.for("drizzle:entityKind"),Lw=Symbol.for("drizzle:hasOwnEntityKind");function h(t,e){if(!t||typeof t!="object")return!1;if(t instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,m))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(t).constructor;if(r)for(;r;){if(m in r&&r[m]===e[m])return!0;r=Object.getPrototypeOf(r)}return!1}var z=class{constructor(e,r){this.table=e,this.config=r,this.name=r.name,this.keyAsName=r.keyAsName,this.notNull=r.notNull,this.default=r.default,this.defaultFn=r.defaultFn,this.onUpdateFn=r.onUpdateFn,this.hasDefault=r.hasDefault,this.primary=r.primaryKey,this.isUnique=r.isUnique,this.uniqueName=r.uniqueName,this.uniqueType=r.uniqueType,this.dataType=r.dataType,this.columnType=r.columnType,this.generated=r.generated,this.generatedIdentity=r.generatedIdentity}static[m]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}};var $r=class{static[m]="ColumnBuilder";config;constructor(e,r,n){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:r,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){this.config.name===""&&(this.config.name=e)}};var Re=Symbol.for("drizzle:Name");var Es=class{static[m]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,r){this.reference=()=>{let{name:n,columns:s,foreignColumns:o}=e();return{name:n,columns:s,foreignTable:o[0].table,foreignColumns:o}},r&&(this._onUpdate=r.onUpdate,this._onDelete=r.onDelete)}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new Jo(e,this)}},Jo=class{constructor(e,r){this.table=e,this.reference=r.reference,this.onUpdate=r._onUpdate,this.onDelete=r._onDelete}static[m]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:r,foreignColumns:n}=this.reference(),s=r.map(a=>a.name),o=n.map(a=>a.name),i=[this.table[Re],...s,n[0].table[Re],...o];return e??`${i.join("_")}_fk`}};function Is(t,...e){return t(...e)}function Yo(t,e){return`${t[Re]}_${e.join("_")}_unique`}var Zo=class{constructor(e,r){this.name=r,this.columns=e}static[m]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new Go(e,this.columns,this.nullsNotDistinctConfig,this.name)}},Wc=class{static[m]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new Zo(e,this.name)}},Go=class{constructor(e,r,n,s){this.table=e,this.columns=r,this.name=s??Yo(this.table,this.columns.map(o=>o.name)),this.nullsNotDistinct=n}static[m]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}};function Hc(t,e,r){for(let n=e;n<t.length;n++){let s=t[n];if(s==="\\"){n++;continue}if(s==='"')return[t.slice(e,n).replace(/\\/g,""),n+1];if(!r&&(s===","||s==="}"))return[t.slice(e,n).replace(/\\/g,""),n]}return[t.slice(e).replace(/\\/g,""),t.length]}function Jc(t,e=0){let r=[],n=e,s=!1;for(;n<t.length;){let o=t[n];if(o===","){(s||n===e)&&r.push(""),s=!0,n++;continue}if(s=!1,o==="\\"){n+=2;continue}if(o==='"'){let[c,l]=Hc(t,n+1,!0);r.push(c),n=l;continue}if(o==="}")return[r,n+1];if(o==="{"){let[c,l]=Jc(t,n+1);r.push(c),n=l;continue}let[i,a]=Hc(t,n,!1);r.push(i),n=a}return[r,n]}function Zc(t){let[e]=Jc(t,1);return e}function Xo(t){return`{${t.map(e=>Array.isArray(e)?Xo(e):typeof e=="string"?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${e}`).join(",")}}`}var ve=class extends $r{foreignKeyConfigs=[];static[m]="PgColumnBuilder";array(e){return new ti(this.config.name,this,e)}references(e,r={}){return this.foreignKeyConfigs.push({ref:e,actions:r}),this}unique(e,r){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=r?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,r){return this.foreignKeyConfigs.map(({ref:n,actions:s})=>Is((o,i)=>{let a=new Es(()=>{let c=o();return{columns:[e],foreignColumns:[c]}});return i.onUpdate&&a.onUpdate(i.onUpdate),i.onDelete&&a.onDelete(i.onDelete),a.build(r)},n,s))}buildExtraConfigColumn(e){return new ei(e,this.config)}},G=class extends z{constructor(e,r){r.uniqueName||(r.uniqueName=Yo(e,[r.name])),super(e,r),this.table=e}static[m]="PgColumn"},ei=class extends G{static[m]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}},Gc=class{static[m]="IndexedColumn";constructor(e,r,n,s){this.name=e,this.keyAsName=r,this.type=n,this.indexConfig=s}name;keyAsName;type;indexConfig},ti=class extends ve{static[m]="PgArrayBuilder";constructor(e,r,n){super(e,"array","PgArray"),this.config.baseBuilder=r,this.config.size=n}build(e){let r=this.config.baseBuilder.build(e);return new ri(e,this.config,r)}},ri=class t extends G{constructor(e,r,n,s){super(e,r),this.baseColumn=n,this.range=s,this.size=r.size}size;static[m]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size=="number"?this.size:""}]`}mapFromDriverValue(e){return typeof e=="string"&&(e=Zc(e)),e.map(r=>this.baseColumn.mapFromDriverValue(r))}mapToDriverValue(e,r=!1){let n=e.map(s=>s===null?null:h(this.baseColumn,t)?this.baseColumn.mapToDriverValue(s,!0):this.baseColumn.mapToDriverValue(s));return r?n:Xo(n)}};var Yc=class extends ve{static[m]="PgEnumObjectColumnBuilder";constructor(e,r){super(e,"string","PgEnumObjectColumn"),this.config.enum=r}build(e){return new ni(e,this.config)}},ni=class extends G{static[m]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,r){super(e,r),this.enum=r.enum}getSQLType(){return this.enum.enumName}},Xc=Symbol.for("drizzle:isPgEnum");function tl(t){return!!t&&typeof t=="function"&&Xc in t&&t[Xc]===!0}var el=class extends ve{static[m]="PgEnumColumnBuilder";constructor(e,r){super(e,"string","PgEnumColumn"),this.config.enum=r}build(e){return new si(e,this.config)}},si=class extends G{static[m]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,r){super(e,r),this.enum=r.enum}getSQLType(){return this.enum.enumName}};var Q=class{static[m]="Subquery";constructor(e,r,n,s=!1,o=[]){this._={brand:"Subquery",sql:e,selectedFields:r,alias:n,isWith:s,usedTables:o}}},ot=class extends Q{static[m]="WithSubquery"};var rl="0.45.2";var oi,ii,ne={startActiveSpan(t,e){return oi?(ii||(ii=oi.trace.getTracer("drizzle-orm",rl)),Is((r,n)=>n.startActiveSpan(t,s=>{try{return e(s)}catch(o){throw s.setStatus({code:r.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),o}finally{s.end()}}),oi,ii)):e()}};var H=Symbol.for("drizzle:ViewBaseConfig");var cr=Symbol.for("drizzle:Schema"),qr=Symbol.for("drizzle:Columns"),nl=Symbol.for("drizzle:ExtraConfigColumns"),ai=Symbol.for("drizzle:OriginalName"),ci=Symbol.for("drizzle:BaseName"),xn=Symbol.for("drizzle:IsAlias"),sl=Symbol.for("drizzle:ExtraConfigBuilder"),Cp=Symbol.for("drizzle:IsDrizzleTable"),v=class{static[m]="Table";static Symbol={Name:Re,Schema:cr,OriginalName:ai,Columns:qr,ExtraConfigColumns:nl,BaseName:ci,IsAlias:xn,ExtraConfigBuilder:sl};[Re];[ai];[cr];[qr];[nl];[ci];[xn]=!1;[Cp]=!0;[sl]=void 0;constructor(e,r,n){this[Re]=this[ai]=e,this[cr]=r,this[ci]=n}};function me(t){return t[Re]}function wt(t){return`${t[cr]??"public"}.${t[Re]}`}var ol=class{static[m]="FakePrimitiveParam"};function li(t){return t!=null&&typeof t.getSQL=="function"}function kp(t){let e={sql:"",params:[]};for(let r of t)e.sql+=r.sql,e.params.push(...r.params),r.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...r.typings));return e}var fe=class{static[m]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new _([this])}},_=class t{constructor(e){this.queryChunks=e;for(let r of e)if(h(r,v)){let n=r[v.Symbol.Schema];this.usedTables.push(n===void 0?r[v.Symbol.Name]:n+"."+r[v.Symbol.Name])}}static[m]="SQL";decoder=al;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return ne.startActiveSpan("drizzle.buildSQL",r=>{let n=this.buildQueryFromSourceParams(this.queryChunks,e);return r?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,r){let n=Object.assign({},r,{inlineParams:r.inlineParams||this.shouldInlineParams,paramStartIndex:r.paramStartIndex||{value:0}}),{casing:s,escapeName:o,escapeParam:i,prepareTyping:a,inlineParams:c,paramStartIndex:l}=n;return kp(e.map(u=>{if(h(u,fe))return{sql:u.value.join(""),params:[]};if(h(u,_n))return{sql:o(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new fe("(")];for(let[p,g]of u.entries())d.push(g),p<u.length-1&&d.push(new fe(", "));return d.push(new fe(")")),this.buildQueryFromSourceParams(d,n)}if(h(u,t))return this.buildQueryFromSourceParams(u.queryChunks,{...n,inlineParams:c||u.shouldInlineParams});if(h(u,v)){let d=u[v.Symbol.Schema],p=u[v.Symbol.Name];return{sql:d===void 0||u[xn]?o(p):o(d)+"."+o(p),params:[]}}if(h(u,z)){let d=s.getColumnCasing(u);if(r.invokeSource==="indexes")return{sql:o(d),params:[]};let p=u.table[v.Symbol.Schema];return{sql:u.table[xn]||p===void 0?o(u.table[v.Symbol.Name])+"."+o(d):o(p)+"."+o(u.table[v.Symbol.Name])+"."+o(d),params:[]}}if(h(u,he)){let d=u[H].schema,p=u[H].name;return{sql:d===void 0||u[H].isAlias?o(p):o(d)+"."+o(p),params:[]}}if(h(u,xe)){if(h(u.value,vt))return{sql:i(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(h(d,t))return this.buildQueryFromSourceParams([d],n);if(c)return{sql:this.mapInlineParam(d,n),params:[]};let p=["none"];return a&&(p=[a(u.encoder)]),{sql:i(l.value++,d),params:[d],typings:p}}return h(u,vt)?{sql:i(l.value++,u),params:[u],typings:["none"]}:h(u,t.Aliased)&&u.fieldAlias!==void 0?{sql:o(u.fieldAlias),params:[]}:h(u,Q)?u._.isWith?{sql:o(u._.alias),params:[]}:this.buildQueryFromSourceParams([new fe("("),u._.sql,new fe(") "),new _n(u._.alias)],n):tl(u)?u.schema?{sql:o(u.schema)+"."+o(u.enumName),params:[]}:{sql:o(u.enumName),params:[]}:li(u)?u.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([u.getSQL()],n):this.buildQueryFromSourceParams([new fe("("),u.getSQL(),new fe(")")],n):c?{sql:this.mapInlineParam(u,n),params:[]}:{sql:i(l.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:r}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return r(e);if(typeof e=="object"){let n=e.toString();return r(n==="[object Object]"?JSON.stringify(e):n)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new t.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},_n=class{constructor(e){this.value=e}static[m]="Name";brand;getSQL(){return new _([this])}};function il(t){return typeof t=="object"&&t!==null&&"mapToDriverValue"in t&&typeof t.mapToDriverValue=="function"}var al={mapFromDriverValue:t=>t},cl={mapToDriverValue:t=>t},Tv={...al,...cl},xe=class{constructor(e,r=cl){this.value=e,this.encoder=r}static[m]="Param";brand;getSQL(){return new _([this])}};function f(t,...e){let r=[];(e.length>0||t.length>0&&t[0]!=="")&&r.push(new fe(t[0]));for(let[n,s]of e.entries())r.push(s,new fe(t[n+1]));return new _(r)}(t=>{function e(){return new _([])}t.empty=e;function r(c){return new _(c)}t.fromList=r;function n(c){return new _([new fe(c)])}t.raw=n;function s(c,l){let u=[];for(let[d,p]of c.entries())d>0&&l!==void 0&&u.push(l),u.push(p);return new _(u)}t.join=s;function o(c){return new _n(c)}t.identifier=o;function i(c){return new vt(c)}t.placeholder=i;function a(c,l){return new xe(c,l)}t.param=a})(f||(f={}));(t=>{class e{constructor(n,s){this.sql=n,this.fieldAlias=s}static[m]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}t.Aliased=e})(_||(_={}));var vt=class{constructor(e){this.name=e}static[m]="Placeholder";getSQL(){return new _([this])}};function lr(t,e){return t.map(r=>{if(h(r,vt)){if(!(r.name in e))throw new Error(`No value for placeholder "${r.name}" was provided`);return e[r.name]}if(h(r,xe)&&h(r.value,vt)){if(!(r.value.name in e))throw new Error(`No value for placeholder "${r.value.name}" was provided`);return r.encoder.mapToDriverValue(e[r.value.name])}return r})}var Dp=Symbol.for("drizzle:IsDrizzleView"),he=class{static[m]="View";[H];[Dp]=!0;constructor({name:e,schema:r,selectedFields:n,query:s}){this[H]={name:e,originalName:e,schema:r,selectedFields:n,query:s,isExisting:!s,isAlias:!1}}getSQL(){return new _([this])}};z.prototype.getSQL=function(){return new _([this])};v.prototype.getSQL=function(){return new _([this])};Q.prototype.getSQL=function(){return new _([this])};var ur=class{constructor(e){this.table=e}static[m]="ColumnAliasProxyHandler";get(e,r){return r==="table"?this.table:e[r]}},Lr=class{constructor(e,r){this.alias=e,this.replaceOriginalName=r}static[m]="TableAliasProxyHandler";get(e,r){if(r===v.Symbol.IsAlias)return!0;if(r===v.Symbol.Name)return this.alias;if(this.replaceOriginalName&&r===v.Symbol.OriginalName)return this.alias;if(r===H)return{...e[H],name:this.alias,isAlias:!0};if(r===v.Symbol.Columns){let s=e[v.Symbol.Columns];if(!s)return s;let o={};return Object.keys(s).map(i=>{o[i]=new Proxy(s[i],new ur(new Proxy(e,this)))}),o}let n=e[r];return h(n,z)?new Proxy(n,new ur(new Proxy(e,this))):n}},ll=class{constructor(e){this.alias=e}static[m]="RelationTableAliasProxyHandler";get(e,r){return r==="sourceTable"?xt(e.sourceTable,this.alias):e[r]}};function xt(t,e){return new Proxy(t,new Lr(e,!1))}function ge(t,e){return new Proxy(t,new ur(new Proxy(t.table,new Lr(e,!1))))}function Sn(t,e){return new _.Aliased(qt(t.sql,e),t.fieldAlias)}function qt(t,e){return f.join(t.queryChunks.map(r=>h(r,z)?ge(r,e):h(r,_)?qt(r,e):h(r,_.Aliased)?Sn(r,e):r))}function En(t,e,r){let n={},s=t.reduce((o,{path:i,field:a},c)=>{let l;h(a,z)?l=a:h(a,_)?l=a.decoder:h(a,Q)?l=a._.sql.decoder:l=a.sql.decoder;let u=o;for(let[d,p]of i.entries())if(d<i.length-1)p in u||(u[p]={}),u=u[p];else{let g=e[c],w=u[p]=g===null?null:l.mapFromDriverValue(g);if(r&&h(a,z)&&i.length===2){let b=i[0];b in n?typeof n[b]=="string"&&n[b]!==me(a.table)&&(n[b]=!1):n[b]=w===null?me(a.table):!1}}return o},{});if(r&&Object.keys(n).length>0)for(let[o,i]of Object.entries(n))typeof i=="string"&&!r[i]&&(s[o]=null);return s}function ce(t,e){return Object.entries(t).reduce((r,[n,s])=>{if(typeof n!="string")return r;let o=e?[...e,n]:[n];return h(s,z)||h(s,_)||h(s,_.Aliased)||h(s,Q)?r.push({path:o,field:s}):h(s,v)?r.push(...ce(s[v.Symbol.Columns],o)):r.push(...ce(s,o)),r},[])}function it(t,e){let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let[s,o]of r.entries())if(o!==n[s])return!1;return!0}function Lt(t,e){let r=Object.entries(e).filter(([,n])=>n!==void 0).map(([n,s])=>h(s,_)||h(s,z)?[n,s]:[n,new xe(s,t[v.Symbol.Columns][n])]);if(r.length===0)throw new Error("No values to set");return Object.fromEntries(r)}function js(t,e){for(let r of e)for(let n of Object.getOwnPropertyNames(r.prototype))n!=="constructor"&&Object.defineProperty(t.prototype,n,Object.getOwnPropertyDescriptor(r.prototype,n)||Object.create(null))}function Ts(t){return t[v.Symbol.Columns]}function De(t){return h(t,Q)?t._.alias:h(t,he)?t[H].name:h(t,_)?void 0:t[v.Symbol.IsAlias]?t[v.Symbol.Name]:t[v.Symbol.BaseName]}function at(t,e){return{name:typeof t=="string"&&t.length>0?t:"",config:typeof t=="object"?t:e}}var ui=typeof TextDecoder>"u"?null:new TextDecoder;var Rs=class{static[m]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,r){this.reference=()=>{let{name:n,columns:s,foreignColumns:o}=e();return{name:n,columns:s,foreignTable:o[0].table,foreignColumns:o}},r&&(this._onUpdate=r.onUpdate,this._onDelete=r.onDelete)}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new di(e,this)}},di=class{constructor(e,r){this.table=e,this.reference=r.reference,this.onUpdate=r._onUpdate,this.onDelete=r._onDelete}static[m]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:r,foreignColumns:n}=this.reference(),s=r.map(a=>a.name),o=n.map(a=>a.name),i=[this.table[Re],...s,n[0].table[Re],...o];return e??`${i.join("_")}_fk`}};function mi(t,e){return`${t[Re]}_${e.join("_")}_unique`}var fi=class{constructor(e,r){this.name=r,this.columns=e}static[m]="SQLiteUniqueConstraintBuilder";columns;build(e){return new pi(e,this.columns,this.name)}},ul=class{static[m]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new fi(e,this.name)}},pi=class{constructor(e,r,n){this.table=e,this.columns=r,this.name=n??mi(this.table,this.columns.map(s=>s.name))}static[m]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}};var ye=class extends $r{static[m]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,r={}){return this.foreignKeyConfigs.push({ref:e,actions:r}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,r){return this.config.generated={as:e,type:"always",mode:r?.mode??"virtual"},this}buildForeignKeys(e,r){return this.foreignKeyConfigs.map(({ref:n,actions:s})=>((o,i)=>{let a=new Rs(()=>{let c=o();return{columns:[e],foreignColumns:[c]}});return i.onUpdate&&a.onUpdate(i.onUpdate),i.onDelete&&a.onDelete(i.onDelete),a.build(r)})(n,s))}},ie=class extends z{constructor(e,r){r.uniqueName||(r.uniqueName=mi(e,[r.name])),super(e,r),this.table=e}static[m]="SQLiteColumn"};var hi=class extends ye{static[m]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new gi(e,this.config)}},gi=class extends ie{static[m]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let r=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(r.toString("utf8"))}return BigInt(ui.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}},yi=class extends ye{static[m]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new bi(e,this.config)}},bi=class extends ie{static[m]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let r=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(r.toString("utf8"))}return JSON.parse(ui.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}},wi=class extends ye{static[m]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new vi(e,this.config)}},vi=class extends ie{static[m]="SQLiteBlobBuffer";mapFromDriverValue(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}getSQLType(){return"blob"}};function As(t,e){let{name:r,config:n}=at(t,e);return n?.mode==="json"?new yi(r):n?.mode==="bigint"?new hi(r):new wi(r)}var xi=class extends ye{static[m]="SQLiteCustomColumnBuilder";constructor(e,r,n){super(e,"custom","SQLiteCustomColumn"),this.config.fieldConfig=r,this.config.customTypeParams=n}build(e){return new _i(e,this.config)}},_i=class extends ie{static[m]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,r){super(e,r),this.sqlName=r.customTypeParams.dataType(r.fieldConfig),this.mapTo=r.customTypeParams.toDriver,this.mapFrom=r.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom=="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo=="function"?this.mapTo(e):e}};function dl(t){return(e,r)=>{let{name:n,config:s}=at(e,r);return new xi(n,s,t)}}var In=class extends ye{static[m]="SQLiteBaseIntegerBuilder";constructor(e,r,n){super(e,r,n),this.config.autoIncrement=!1}primaryKey(e){return e?.autoIncrement&&(this.config.autoIncrement=!0),this.config.hasDefault=!0,super.primaryKey()}},jn=class extends ie{static[m]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}},Si=class extends In{static[m]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new Ei(e,this.config)}},Ei=class extends jn{static[m]="SQLiteInteger"},Ii=class extends In{static[m]="SQLiteTimestampBuilder";constructor(e,r){super(e,"date","SQLiteTimestamp"),this.config.mode=r}defaultNow(){return this.default(f`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new ji(e,this.config)}},ji=class extends jn{static[m]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){return this.config.mode==="timestamp"?new Date(e*1e3):new Date(e)}mapToDriverValue(e){let r=e.getTime();return this.config.mode==="timestamp"?Math.floor(r/1e3):r}},Ti=class extends In{static[m]="SQLiteBooleanBuilder";constructor(e,r){super(e,"boolean","SQLiteBoolean"),this.config.mode=r}build(e){return new Ri(e,this.config)}},Ri=class extends jn{static[m]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}};function Tn(t,e){let{name:r,config:n}=at(t,e);return n?.mode==="timestamp"||n?.mode==="timestamp_ms"?new Ii(r,n.mode):n?.mode==="boolean"?new Ti(r,n.mode):new Si(r)}var Ai=class extends ye{static[m]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new Oi(e,this.config)}},Oi=class extends ie{static[m]="SQLiteNumeric";mapFromDriverValue(e){return typeof e=="string"?e:String(e)}getSQLType(){return"numeric"}},Pi=class extends ye{static[m]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new Ni(e,this.config)}},Ni=class extends ie{static[m]="SQLiteNumericNumber";mapFromDriverValue(e){return typeof e=="number"?e:Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}},Ci=class extends ye{static[m]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new ki(e,this.config)}},ki=class extends ie{static[m]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}};function fl(t,e){let{name:r,config:n}=at(t,e),s=n?.mode;return s==="number"?new Pi(r):s==="bigint"?new Ci(r):new Ai(r)}var Di=class extends ye{static[m]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new $i(e,this.config)}},$i=class extends ie{static[m]="SQLiteReal";getSQLType(){return"real"}};function Os(t){return new Di(t??"")}var qi=class extends ye{static[m]="SQLiteTextBuilder";constructor(e,r){super(e,"string","SQLiteText"),this.config.enumValues=r.enum,this.config.length=r.length}build(e){return new Li(e,this.config)}},Li=class extends ie{static[m]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,r){super(e,r)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}},Mi=class extends ye{static[m]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new zi(e,this.config)}},zi=class extends ie{static[m]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}};function Rn(t,e={}){let{name:r,config:n}=at(t,e);return n.mode==="json"?new Mi(r):new qi(r,n)}var U=class t{static[m]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,r){if(r==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(r===H)return{...e[H],selectedFields:new Proxy(e[H].selectedFields,this)};if(typeof r=="symbol")return e[r];let s=(h(e,Q)?e._.selectedFields:h(e,he)?e[H].selectedFields:e)[r];if(h(s,_.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!s.isSelectionField)return s.sql;let o=s.clone();return o.isSelectionField=!0,o}if(h(s,_)){if(this.config.sqlBehavior==="sql")return s;throw new Error(`You tried to reference "${r}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return h(s,z)?this.config.alias?new Proxy(s,new ur(new Proxy(s.table,new Lr(this.config.alias,this.config.replaceOriginalName??!1)))):s:typeof s!="object"||s===null?s:new Proxy(s,new t(this.config))}};var Z=class{static[m]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(r=>(e?.(),r),r=>{throw e?.(),r})}then(e,r){return this.execute().then(e,r)}};function pl(){return{blob:As,customType:dl,integer:Tn,numeric:fl,real:Os,text:Rn}}var Ui=Symbol.for("drizzle:SQLiteInlineForeignKeys"),de=class extends v{static[m]="SQLiteTable";static Symbol=Object.assign({},v.Symbol,{InlineForeignKeys:Ui});[v.Symbol.Columns];[Ui]=[];[v.Symbol.ExtraConfigBuilder]=void 0};function $p(t,e,r,n,s=t){let o=new de(t,n,s),i=typeof e=="function"?e(pl()):e,a=Object.fromEntries(Object.entries(i).map(([l,u])=>{let d=u;d.setName(l);let p=d.build(o);return o[Ui].push(...d.buildForeignKeys(p,o)),[l,p]})),c=Object.assign(o,a);return c[v.Symbol.Columns]=a,c[v.Symbol.ExtraConfigColumns]=a,r&&(c[de.Symbol.ExtraConfigBuilder]=r),c}var ml=(t,e,r)=>$p(t,e,r);var Ps=class{constructor(e,r){this.name=e,this.unique=r}static[m]="SQLiteIndexBuilderOn";on(...e){return new Ki(this.name,e,this.unique)}},Ki=class{static[m]="SQLiteIndexBuilder";config;constructor(e,r,n){this.config={name:e,columns:r,unique:n,where:void 0}}where(e){return this.config.where=e,this}build(e){return new Bi(this.config,e)}},Bi=class{static[m]="SQLiteIndex";config;constructor(e,r){this.config={...e,table:r}}};function hl(t){return new Ps(t,!1)}function gl(t){return new Ps(t,!0)}function yl(...t){return t[0].columns?new Ns(t[0].columns,t[0].name):new Ns(t)}var Ns=class{static[m]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,r){this.columns=e,this.name=r}build(e){return new Fi(e,this.columns,this.name)}},Fi=class{constructor(e,r,n){this.table=e,this.columns=r,this.name=n}static[m]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[de.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}};function He(t){return h(t,de)?[`${t[v.Symbol.BaseName]}`]:h(t,Q)?t._.usedTables??[]:h(t,_)?t.usedTables??[]:[]}var An=class extends Z{constructor(e,r,n,s){super(),this.table=e,this.session=r,this.dialect=n,this.config={table:e,withList:s}}static[m]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]=="function"){let r=e[0](new Proxy(this.config.table[v.Symbol.Columns],new U({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(r)?r:[r];this.config.orderBy=n}else{let r=e;this.config.orderBy=r}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[de.Symbol.Columns]){return this.config.returning=ce(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...r}=this.dialect.sqlToQuery(this.getSQL());return r}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:He(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}};function qp(t){return(t.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(r=>r.toLowerCase()).join("_")}function Lp(t){return(t.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,n,s)=>{let o=s===0?n.toLowerCase():`${n[0].toUpperCase()}${n.slice(1)}`;return r+o},"")}function Mp(t){return t}var Mr=class{static[m]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?qp:e==="camelCase"?Lp:Mp}getColumnCasing(e){if(!e.keyAsName)return e.name;let r=e.table[v.Symbol.Schema]??"public",n=e.table[v.Symbol.OriginalName],s=`${r}.${n}.${e.name}`;return this.cache[s]||this.cacheTable(e.table),this.cache[s]}cacheTable(e){let r=e[v.Symbol.Schema]??"public",n=e[v.Symbol.OriginalName],s=`${r}.${n}`;if(!this.cachedTables[s]){for(let o of Object.values(e[v.Symbol.Columns])){let i=`${s}.${o.name}`;this.cache[i]=this.convert(o.name)}this.cachedTables[s]=!0}}clearCache(){this.cache={},this.cachedTables={}}};var _t=class extends Error{static[m]="DrizzleError";constructor({message:e,cause:r}){super(e),this.name="DrizzleError",this.cause=r}},Ae=class t extends Error{constructor(e,r,n){super(`Failed query: ${e}
8
+ params: ${r}`),this.query=e,this.params=r,this.cause=n,Error.captureStackTrace(this,t),n&&(this.cause=n)}},zr=class extends _t{static[m]="TransactionRollbackError";constructor(){super({message:"Rollback"})}};var ct=class extends ve{static[m]="PgDateColumnBaseBuilder";defaultNow(){return this.default(f`now()`)}};var bl=class extends ct{static[m]="PgDateBuilder";constructor(e){super(e,"date","PgDate")}build(e){return new On(e,this.config)}},On=class extends G{static[m]="PgDate";getSQLType(){return"date"}mapFromDriverValue(e){return typeof e=="string"?new Date(e):e}mapToDriverValue(e){return e.toISOString()}},wl=class extends ct{static[m]="PgDateStringBuilder";constructor(e){super(e,"string","PgDateString")}build(e){return new Pn(e,this.config)}},Pn=class extends G{static[m]="PgDateString";getSQLType(){return"date"}mapFromDriverValue(e){return typeof e=="string"?e:e.toISOString().slice(0,-14)}};var vl=class extends ve{static[m]="PgJsonBuilder";constructor(e){super(e,"json","PgJson")}build(e){return new Nn(e,this.config)}},Nn=class extends G{static[m]="PgJson";constructor(e,r){super(e,r)}getSQLType(){return"json"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}};var xl=class extends ve{static[m]="PgJsonbBuilder";constructor(e){super(e,"json","PgJsonb")}build(e){return new Cn(e,this.config)}},Cn=class extends G{static[m]="PgJsonb";constructor(e,r){super(e,r)}getSQLType(){return"jsonb"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}};var _l=class extends ve{static[m]="PgNumericBuilder";constructor(e,r,n){super(e,"string","PgNumeric"),this.config.precision=r,this.config.scale=n}build(e){return new kn(e,this.config)}},kn=class extends G{static[m]="PgNumeric";precision;scale;constructor(e,r){super(e,r),this.precision=r.precision,this.scale=r.scale}mapFromDriverValue(e){return typeof e=="string"?e:String(e)}getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}},Sl=class extends ve{static[m]="PgNumericNumberBuilder";constructor(e,r,n){super(e,"number","PgNumericNumber"),this.config.precision=r,this.config.scale=n}build(e){return new Qi(e,this.config)}},Qi=class extends G{static[m]="PgNumericNumber";precision;scale;constructor(e,r){super(e,r),this.precision=r.precision,this.scale=r.scale}mapFromDriverValue(e){return typeof e=="number"?e:Number(e)}mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}},El=class extends ve{static[m]="PgNumericBigIntBuilder";constructor(e,r,n){super(e,"bigint","PgNumericBigInt"),this.config.precision=r,this.config.scale=n}build(e){return new Vi(e,this.config)}},Vi=class extends G{static[m]="PgNumericBigInt";precision;scale;constructor(e,r){super(e,r),this.precision=r.precision,this.scale=r.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}};var Il=class extends ct{constructor(e,r,n){super(e,"string","PgTime"),this.withTimezone=r,this.precision=n,this.config.withTimezone=r,this.config.precision=n}static[m]="PgTimeBuilder";build(e){return new Dn(e,this.config)}},Dn=class extends G{static[m]="PgTime";withTimezone;precision;constructor(e,r){super(e,r),this.withTimezone=r.withTimezone,this.precision=r.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}};var jl=class extends ct{static[m]="PgTimestampBuilder";constructor(e,r,n){super(e,"date","PgTimestamp"),this.config.withTimezone=r,this.config.precision=n}build(e){return new $n(e,this.config)}},$n=class extends G{static[m]="PgTimestamp";withTimezone;precision;constructor(e,r){super(e,r),this.withTimezone=r.withTimezone,this.precision=r.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(e){return typeof e=="string"?new Date(this.withTimezone?e:e+"+0000"):e}mapToDriverValue=e=>e.toISOString()},Tl=class extends ct{static[m]="PgTimestampStringBuilder";constructor(e,r,n){super(e,"string","PgTimestampString"),this.config.withTimezone=r,this.config.precision=n}build(e){return new qn(e,this.config)}},qn=class extends G{static[m]="PgTimestampString";withTimezone;precision;constructor(e,r){super(e,r),this.withTimezone=r.withTimezone,this.precision=r.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(e){if(typeof e=="string")return e;let r=e.toISOString().slice(0,-1).replace("T"," ");if(this.withTimezone){let n=e.getTimezoneOffset(),s=n<=0?"+":"-";return`${r}${s}${Math.floor(Math.abs(n)/60).toString().padStart(2,"0")}`}return r}};var Rl=class extends ve{static[m]="PgUUIDBuilder";constructor(e){super(e,"string","PgUUID")}defaultRandom(){return this.default(f`gen_random_uuid()`)}build(e){return new Ln(e,this.config)}},Ln=class extends G{static[m]="PgUUID";getSQLType(){return"uuid"}};var Al=Symbol.for("drizzle:PgInlineForeignKeys"),Ol=Symbol.for("drizzle:EnableRLS"),Se=class extends v{static[m]="PgTable";static Symbol=Object.assign({},v.Symbol,{InlineForeignKeys:Al,EnableRLS:Ol});[Al]=[];[Ol]=!1;[v.Symbol.ExtraConfigBuilder]=void 0;[v.Symbol.ExtraConfigColumns]={}};var Cs=class{static[m]="PgPrimaryKeyBuilder";columns;name;constructor(e,r){this.columns=e,this.name=r}build(e){return new Wi(e,this.columns,this.name)}},Wi=class{constructor(e,r,n){this.table=e,this.columns=r,this.name=n}static[m]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Se.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}};function $e(t,e){return il(e)&&!li(t)&&!h(t,xe)&&!h(t,vt)&&!h(t,z)&&!h(t,v)&&!h(t,he)?new xe(t,e):t}var Ke=(t,e)=>f`${t} = ${$e(e,t)}`,Pl=(t,e)=>f`${t} <> ${$e(e,t)}`;function Je(...t){let e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?new _(e):new _([new fe("("),f.join(e,new fe(" and ")),new fe(")")])}function Hi(...t){let e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?new _(e):new _([new fe("("),f.join(e,new fe(" or ")),new fe(")")])}function Nl(t){return f`not ${t}`}var Cl=(t,e)=>f`${t} > ${$e(e,t)}`,kl=(t,e)=>f`${t} >= ${$e(e,t)}`,Dl=(t,e)=>f`${t} < ${$e(e,t)}`,$l=(t,e)=>f`${t} <= ${$e(e,t)}`;function Ji(t,e){return Array.isArray(e)?e.length===0?f`false`:f`${t} in ${e.map(r=>$e(r,t))}`:f`${t} in ${$e(e,t)}`}function ql(t,e){return Array.isArray(e)?e.length===0?f`true`:f`${t} not in ${e.map(r=>$e(r,t))}`:f`${t} not in ${$e(e,t)}`}function Ll(t){return f`${t} is null`}function Ml(t){return f`${t} is not null`}function zl(t){return f`exists ${t}`}function Ul(t){return f`not exists ${t}`}function Kl(t,e,r){return f`${t} between ${$e(e,t)} and ${$e(r,t)}`}function Bl(t,e,r){return f`${t} not between ${$e(e,t)} and ${$e(r,t)}`}function Fl(t,e){return f`${t} like ${e}`}function Ql(t,e){return f`${t} not like ${e}`}function Vl(t,e){return f`${t} ilike ${e}`}function Wl(t,e){return f`${t} not ilike ${e}`}function Hl(t){return f`${t} asc`}function Zi(t){return f`${t} desc`}var ks=class{constructor(e,r,n){this.sourceTable=e,this.referencedTable=r,this.relationName=n,this.referencedTableName=r[v.Symbol.Name]}static[m]="Relation";referencedTableName;fieldName},Gi=class{constructor(e,r){this.table=e,this.config=r}static[m]="Relations"},lt=class t extends ks{constructor(e,r,n,s){super(e,r,n?.relationName),this.config=n,this.isNullable=s}static[m]="One";withFieldName(e){let r=new t(this.sourceTable,this.referencedTable,this.config,this.isNullable);return r.fieldName=e,r}},dr=class t extends ks{constructor(e,r,n){super(e,r,n?.relationName),this.config=n}static[m]="Many";withFieldName(e){let r=new t(this.sourceTable,this.referencedTable,this.config);return r.fieldName=e,r}};function Ds(){return{and:Je,between:Kl,eq:Ke,exists:zl,gt:Cl,gte:kl,ilike:Vl,inArray:Ji,isNull:Ll,isNotNull:Ml,like:Fl,lt:Dl,lte:$l,ne:Pl,not:Nl,notBetween:Bl,notExists:Ul,notLike:Ql,notIlike:Wl,notInArray:ql,or:Hi,sql:f}}function $s(){return{sql:f,asc:Hl,desc:Zi}}function qs(t,e){Object.keys(t).length===1&&"default"in t&&!h(t.default,v)&&(t=t.default);let r={},n={},s={};for(let[o,i]of Object.entries(t))if(h(i,v)){let a=wt(i),c=n[a];r[a]=o,s[o]={tsName:o,dbName:i[v.Symbol.Name],schema:i[v.Symbol.Schema],columns:i[v.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let u of Object.values(i[v.Symbol.Columns]))u.primary&&s[o].primaryKey.push(u);let l=i[v.Symbol.ExtraConfigBuilder]?.(i[v.Symbol.ExtraConfigColumns]);if(l)for(let u of Object.values(l))h(u,Cs)&&s[o].primaryKey.push(...u.columns)}else if(h(i,Gi)){let a=wt(i.table),c=r[a],l=i.config(e(i.table)),u;for(let[d,p]of Object.entries(l))if(c){let g=s[c];g.relations[d]=p,u&&g.primaryKey.push(...u)}else a in n||(n[a]={relations:{},primaryKey:u}),n[a].relations[d]=p}return{tables:s,tableNamesMap:r}}function zp(t){return function(r,n){return new lt(t,r,n,n?.fields.reduce((s,o)=>s&&o.notNull,!0)??!1)}}function Up(t){return function(r,n){return new dr(t,r,n)}}function Ls(t,e,r){if(h(r,lt)&&r.config)return{fields:r.config.fields,references:r.config.references};let n=e[wt(r.referencedTable)];if(!n)throw new Error(`Table "${r.referencedTable[v.Symbol.Name]}" not found in schema`);let s=t[n];if(!s)throw new Error(`Table "${n}" not found in schema`);let o=r.sourceTable,i=e[wt(o)];if(!i)throw new Error(`Table "${o[v.Symbol.Name]}" not found in schema`);let a=[];for(let c of Object.values(s.relations))(r.relationName&&r!==c&&c.relationName===r.relationName||!r.relationName&&c.referencedTable===r.sourceTable)&&a.push(c);if(a.length>1)throw r.relationName?new Error(`There are multiple relations with name "${r.relationName}" in table "${n}"`):new Error(`There are multiple relations between "${n}" and "${r.sourceTable[v.Symbol.Name]}". Please specify relation name`);if(a[0]&&h(a[0],lt)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw new Error(`There is not enough information to infer relation "${i}.${r.fieldName}"`)}function Ms(t){return{one:zp(t),many:Up(t)}}function Ur(t,e,r,n,s=o=>o){let o={};for(let[i,a]of n.entries())if(a.isJson){let c=e.relations[a.tsKey],l=r[i],u=typeof l=="string"?JSON.parse(l):l;o[a.tsKey]=h(c,lt)?u&&Ur(t,t[a.relationTableTsKey],u,a.selection,s):u.map(d=>Ur(t,t[a.relationTableTsKey],d,a.selection,s))}else{let c=s(r[i]),l=a.field,u;h(l,z)?u=l:h(l,_)?u=l.decoder:u=l.sql.decoder,o[a.tsKey]=c===null?null:u.mapFromDriverValue(c)}return o}var Mt=class extends he{static[m]="SQLiteViewBase"};var fr=class{static[m]="SQLiteDialect";casing;constructor(e){this.casing=new Mr(e?.casing)}escapeName(e){return`"${e.replace(/"/g,'""')}"`}escapeParam(e){return"?"}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let r=[f`with `];for(let[n,s]of e.entries())r.push(f`${f.identifier(s._.alias)} as (${s._.sql})`),n<e.length-1&&r.push(f`, `);return r.push(f` `),f.join(r)}buildDeleteQuery({table:e,where:r,returning:n,withList:s,limit:o,orderBy:i}){let a=this.buildWithCTE(s),c=n?f` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,l=r?f` where ${r}`:void 0,u=this.buildOrderBy(i),d=this.buildLimit(o);return f`${a}delete from ${e}${l}${c}${u}${d}`}buildUpdateSet(e,r){let n=e[v.Symbol.Columns],s=Object.keys(n).filter(i=>r[i]!==void 0||n[i]?.onUpdateFn!==void 0),o=s.length;return f.join(s.flatMap((i,a)=>{let c=n[i],l=c.onUpdateFn?.(),u=r[i]??(h(l,_)?l:f.param(l,c)),d=f`${f.identifier(this.casing.getColumnCasing(c))} = ${u}`;return a<o-1?[d,f.raw(", ")]:[d]}))}buildUpdateQuery({table:e,set:r,where:n,returning:s,withList:o,joins:i,from:a,limit:c,orderBy:l}){let u=this.buildWithCTE(o),d=this.buildUpdateSet(e,r),p=a&&f.join([f.raw(" from "),this.buildFromTable(a)]),g=this.buildJoins(i),w=s?f` returning ${this.buildSelection(s,{isSingleTable:!0})}`:void 0,b=n?f` where ${n}`:void 0,E=this.buildOrderBy(l),S=this.buildLimit(c);return f`${u}update ${e} set ${d}${p}${g}${b}${w}${E}${S}`}buildSelection(e,{isSingleTable:r=!1}={}){let n=e.length,s=e.flatMap(({field:o},i)=>{let a=[];if(h(o,_.Aliased)&&o.isSelectionField)a.push(f.identifier(o.fieldAlias));else if(h(o,_.Aliased)||h(o,_)){let c=h(o,_.Aliased)?o.sql:o;r?a.push(new _(c.queryChunks.map(l=>h(l,z)?f.identifier(this.casing.getColumnCasing(l)):l))):a.push(c),h(o,_.Aliased)&&a.push(f` as ${f.identifier(o.fieldAlias)}`)}else if(h(o,z)){let c=o.table[v.Symbol.Name];o.columnType==="SQLiteNumericBigInt"?r?a.push(f`cast(${f.identifier(this.casing.getColumnCasing(o))} as text)`):a.push(f`cast(${f.identifier(c)}.${f.identifier(this.casing.getColumnCasing(o))} as text)`):r?a.push(f.identifier(this.casing.getColumnCasing(o))):a.push(f`${f.identifier(c)}.${f.identifier(this.casing.getColumnCasing(o))}`)}else if(h(o,Q)){let c=Object.entries(o._.selectedFields);if(c.length===1){let l=c[0][1],u=h(l,_)?l.decoder:h(l,z)?{mapFromDriverValue:d=>l.mapFromDriverValue(d)}:l.sql.decoder;u&&(o._.sql.decoder=u)}a.push(o)}return i<n-1&&a.push(f`, `),a});return f.join(s)}buildJoins(e){if(!e||e.length===0)return;let r=[];if(e)for(let[n,s]of e.entries()){n===0&&r.push(f` `);let o=s.table,i=s.on?f` on ${s.on}`:void 0;if(h(o,de)){let a=o[de.Symbol.Name],c=o[de.Symbol.Schema],l=o[de.Symbol.OriginalName],u=a===l?void 0:s.alias;r.push(f`${f.raw(s.joinType)} join ${c?f`${f.identifier(c)}.`:void 0}${f.identifier(l)}${u&&f` ${f.identifier(u)}`}${i}`)}else r.push(f`${f.raw(s.joinType)} join ${o}${i}`);n<e.length-1&&r.push(f` `)}return f.join(r)}buildLimit(e){return typeof e=="object"||typeof e=="number"&&e>=0?f` limit ${e}`:void 0}buildOrderBy(e){let r=[];if(e)for(let[n,s]of e.entries())r.push(s),n<e.length-1&&r.push(f`, `);return r.length>0?f` order by ${f.join(r)}`:void 0}buildFromTable(e){return h(e,v)&&e[v.Symbol.IsAlias]?f`${f`${f.identifier(e[v.Symbol.Schema]??"")}.`.if(e[v.Symbol.Schema])}${f.identifier(e[v.Symbol.OriginalName])} ${f.identifier(e[v.Symbol.Name])}`:e}buildSelectQuery({withList:e,fields:r,fieldsFlat:n,where:s,having:o,table:i,joins:a,orderBy:c,groupBy:l,limit:u,offset:d,distinct:p,setOperators:g}){let w=n??ce(r);for(let re of w)if(h(re.field,z)&&me(re.field.table)!==(h(i,Q)?i._.alias:h(i,Mt)?i[H].name:h(i,_)?void 0:me(i))&&!(J=>a?.some(({alias:ke})=>ke===(J[v.Symbol.IsAlias]?me(J):J[v.Symbol.BaseName])))(re.field.table)){let J=me(re.field.table);throw new Error(`Your "${re.path.join("->")}" field references a column "${J}"."${re.field.name}", but the table "${J}" is not part of the query! Did you forget to join it?`)}let b=!a||a.length===0,E=this.buildWithCTE(e),S=p?f` distinct`:void 0,k=this.buildSelection(w,{isSingleTable:b}),q=this.buildFromTable(i),P=this.buildJoins(a),X=s?f` where ${s}`:void 0,L=o?f` having ${o}`:void 0,I=[];if(l)for(let[re,J]of l.entries())I.push(J),re<l.length-1&&I.push(f`, `);let A=I.length>0?f` group by ${f.join(I)}`:void 0,V=this.buildOrderBy(c),oe=this.buildLimit(u),we=d?f` offset ${d}`:void 0,ue=f`${E}select${S} ${k} from ${q}${P}${X}${A}${L}${V}${oe}${we}`;return g.length>0?this.buildSetOperations(ue,g):ue}buildSetOperations(e,r){let[n,...s]=r;if(!n)throw new Error("Cannot pass undefined values to any set operator");return s.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:n}),s)}buildSetOperationQuery({leftSelect:e,setOperator:{type:r,isAll:n,rightSelect:s,limit:o,orderBy:i,offset:a}}){let c=f`${e.getSQL()} `,l=f`${s.getSQL()}`,u;if(i&&i.length>0){let w=[];for(let b of i)if(h(b,ie))w.push(f.identifier(b.name));else if(h(b,_)){for(let E=0;E<b.queryChunks.length;E++){let S=b.queryChunks[E];h(S,ie)&&(b.queryChunks[E]=f.identifier(this.casing.getColumnCasing(S)))}w.push(f`${b}`)}else w.push(f`${b}`);u=f` order by ${f.join(w,f`, `)}`}let d=typeof o=="object"||typeof o=="number"&&o>=0?f` limit ${o}`:void 0,p=f.raw(`${r} ${n?"all ":""}`),g=a?f` offset ${a}`:void 0;return f`${c}${p}${l}${u}${d}${g}`}buildInsertQuery({table:e,values:r,onConflict:n,returning:s,withList:o,select:i}){let a=[],c=e[v.Symbol.Columns],l=Object.entries(c).filter(([b,E])=>!E.shouldDisableInsert()),u=l.map(([,b])=>f.identifier(this.casing.getColumnCasing(b)));if(i){let b=r;h(b,_)?a.push(b):a.push(b.getSQL())}else{let b=r;a.push(f.raw("values "));for(let[E,S]of b.entries()){let k=[];for(let[q,P]of l){let X=S[q];if(X===void 0||h(X,xe)&&X.value===void 0){let L;if(P.default!==null&&P.default!==void 0)L=h(P.default,_)?P.default:f.param(P.default,P);else if(P.defaultFn!==void 0){let I=P.defaultFn();L=h(I,_)?I:f.param(I,P)}else if(!P.default&&P.onUpdateFn!==void 0){let I=P.onUpdateFn();L=h(I,_)?I:f.param(I,P)}else L=f`null`;k.push(L)}else k.push(X)}a.push(k),E<b.length-1&&a.push(f`, `)}}let d=this.buildWithCTE(o),p=f.join(a),g=s?f` returning ${this.buildSelection(s,{isSingleTable:!0})}`:void 0,w=n?.length?f.join(n):void 0;return f`${d}insert into ${e} ${u} ${p}${w}${g}`}sqlToQuery(e,r){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:r})}buildRelationalQuery({fullSchema:e,schema:r,tableNamesMap:n,table:s,tableConfig:o,queryConfig:i,tableAlias:a,nestedQueryRelation:c,joinOn:l}){let u=[],d,p,g=[],w,b=[];if(i===!0)u=Object.entries(o.columns).map(([k,q])=>({dbKey:q.name,tsKey:k,field:ge(q,a),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let S=Object.fromEntries(Object.entries(o.columns).map(([I,A])=>[I,ge(A,a)]));if(i.where){let I=typeof i.where=="function"?i.where(S,Ds()):i.where;w=I&&qt(I,a)}let k=[],q=[];if(i.columns){let I=!1;for(let[A,V]of Object.entries(i.columns))V!==void 0&&A in o.columns&&(!I&&V===!0&&(I=!0),q.push(A));q.length>0&&(q=I?q.filter(A=>i.columns?.[A]===!0):Object.keys(o.columns).filter(A=>!q.includes(A)))}else q=Object.keys(o.columns);for(let I of q){let A=o.columns[I];k.push({tsKey:I,value:A})}let P=[];i.with&&(P=Object.entries(i.with).filter(I=>!!I[1]).map(([I,A])=>({tsKey:I,queryConfig:A,relation:o.relations[I]})));let X;if(i.extras){X=typeof i.extras=="function"?i.extras(S,{sql:f}):i.extras;for(let[I,A]of Object.entries(X))k.push({tsKey:I,value:Sn(A,a)})}for(let{tsKey:I,value:A}of k)u.push({dbKey:h(A,_.Aliased)?A.fieldAlias:o.columns[I].name,tsKey:I,field:h(A,z)?ge(A,a):A,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof i.orderBy=="function"?i.orderBy(S,$s()):i.orderBy??[];Array.isArray(L)||(L=[L]),g=L.map(I=>h(I,z)?ge(I,a):qt(I,a)),d=i.limit,p=i.offset;for(let{tsKey:I,queryConfig:A,relation:V}of P){let oe=Ls(r,n,V),we=wt(V.referencedTable),ue=n[we],re=`${a}_${I}`,J=Je(...oe.fields.map((Mo,zo)=>Ke(ge(oe.references[zo],re),ge(Mo,a)))),ke=this.buildRelationalQuery({fullSchema:e,schema:r,tableNamesMap:n,table:e[ue],tableConfig:r[ue],queryConfig:h(V,lt)?A===!0?{limit:1}:{...A,limit:1}:A,tableAlias:re,joinOn:J,nestedQueryRelation:V}),bn=f`(${ke.sql})`.as(I);u.push({dbKey:I,tsKey:I,field:bn,relationTableTsKey:ue,isJson:!0,selection:ke.selection})}}if(u.length===0)throw new _t({message:`No fields selected for table "${o.tsName}" ("${a}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let E;if(w=Je(l,w),c){let S=f`json_array(${f.join(u.map(({field:P})=>h(P,ie)?f.identifier(this.casing.getColumnCasing(P)):h(P,_.Aliased)?P.sql:P),f`, `)})`;h(c,dr)&&(S=f`coalesce(json_group_array(${S}), json_array())`);let k=[{dbKey:"data",tsKey:"data",field:S.as("data"),isJson:!0,relationTableTsKey:o.tsName,selection:u}];d!==void 0||p!==void 0||g.length>0?(E=this.buildSelectQuery({table:xt(s,a),fields:{},fieldsFlat:[{path:[],field:f.raw("*")}],where:w,limit:d,offset:p,orderBy:g,setOperators:[]}),w=void 0,d=void 0,p=void 0,g=void 0):E=xt(s,a),E=this.buildSelectQuery({table:h(E,de)?E:new Q(E,{},a),fields:{},fieldsFlat:k.map(({field:P})=>({path:[],field:h(P,z)?ge(P,a):P})),joins:b,where:w,limit:d,offset:p,orderBy:g,setOperators:[]})}else E=this.buildSelectQuery({table:xt(s,a),fields:{},fieldsFlat:u.map(({field:S})=>({path:[],field:h(S,z)?ge(S,a):S})),joins:b,where:w,limit:d,offset:p,orderBy:g,setOperators:[]});return{tableTsKey:o.tsName,sql:E,selection:u}}},zs=class extends fr{static[m]="SQLiteSyncDialect";migrate(e,r,n){let s=n===void 0||typeof n=="string"?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",o=f`
9
+ CREATE TABLE IF NOT EXISTS ${f.identifier(s)} (
10
+ id SERIAL PRIMARY KEY,
11
+ hash text NOT NULL,
12
+ created_at numeric
13
+ )
14
+ `;r.run(o);let a=r.values(f`SELECT id, hash, created_at FROM ${f.identifier(s)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;r.run(f`BEGIN`);try{for(let c of e)if(!a||Number(a[2])<c.folderMillis){for(let l of c.sql)r.run(f.raw(l));r.run(f`INSERT INTO ${f.identifier(s)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}r.run(f`COMMIT`)}catch(c){throw r.run(f`ROLLBACK`),c}}},Us=class extends fr{static[m]="SQLiteAsyncDialect";async migrate(e,r,n){let s=n===void 0||typeof n=="string"?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",o=f`
15
+ CREATE TABLE IF NOT EXISTS ${f.identifier(s)} (
16
+ id SERIAL PRIMARY KEY,
17
+ hash text NOT NULL,
18
+ created_at numeric
19
+ )
20
+ `;await r.run(o);let a=(await r.values(f`SELECT id, hash, created_at FROM ${f.identifier(s)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await r.transaction(async c=>{for(let l of e)if(!a||Number(a[2])<l.folderMillis){for(let u of l.sql)await c.run(f.raw(u));await c.run(f`INSERT INTO ${f.identifier(s)} ("hash", "created_at") VALUES(${l.hash}, ${l.folderMillis})`)}})}};var Kr=class{static[m]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}};var Be=class{static[m]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let r=!!this.fields,n;return this.fields?n=this.fields:h(e,Q)?n=Object.fromEntries(Object.keys(e._.selectedFields).map(s=>[s,e[s]])):h(e,Mt)?n=e[H].selectedFields:h(e,_)?n={}:n=Ts(e),new Ks({table:e,fields:n,isPartialSelect:r,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}},Yi=class extends Kr{static[m]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:r,isPartialSelect:n,session:s,dialect:o,withList:i,distinct:a}){super(),this.config={withList:i,table:e,fields:{...r},distinct:a,setOperators:[]},this.isPartialSelect=n,this.session=s,this.dialect=o,this._={selectedFields:r,config:this.config},this.tableName=De(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{};for(let c of He(e))this.usedTables.add(c)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(r,n)=>{let s=this.tableName,o=De(r);for(let i of He(r))this.usedTables.add(i);if(typeof o=="string"&&this.config.joins?.some(i=>i.alias===o))throw new Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof s=="string"&&(this.config.fields={[s]:this.config.fields}),typeof o=="string"&&!h(r,_))){let i=h(r,Q)?r._.selectedFields:h(r,he)?r[H].selectedFields:r[v.Symbol.Columns];this.config.fields[o]=i}if(typeof n=="function"&&(n=n(new Proxy(this.config.fields,new U({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:n,table:r,joinType:e,alias:o}),typeof o=="string")switch(e){case"left":{this.joinsNotNullableMap[o]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[o]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[o]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[o]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,r){return n=>{let s=typeof n=="function"?n(Kp()):n;if(!it(this.getSelectedFields(),s.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:r,rightSelect:s}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new U({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new U({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){let r=e[0](new Proxy(this.config.fields,new U({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(r)?r:[r]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){let r=e[0](new Proxy(this.config.fields,new U({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(r)?r:[r];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{let r=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=r:this.config.orderBy=r}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...r}=this.dialect.sqlToQuery(this.getSQL());return r}as(e){let r=[];if(r.push(...He(this.config.table)),this.config.joins)for(let n of this.config.joins)r.push(...He(n.table));return new Proxy(new Q(this.getSQL(),this.config.fields,e,!1,[...new Set(r)]),new U({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new U({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}},Ks=class extends Yi{static[m]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let r=ce(this.config.fields),n=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),r,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return n.joinsNotNullableMap=this.joinsNotNullableMap,n}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(){return this.all()}};js(Ks,[Z]);function Bs(t,e){return(r,n,...s)=>{let o=[n,...s].map(i=>({type:t,isAll:e,rightSelect:i}));for(let i of o)if(!it(r.getSelectedFields(),i.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(o)}}var Kp=()=>({union:Bp,unionAll:Fp,intersect:Qp,except:Vp}),Bp=Bs("union",!1),Fp=Bs("union",!0),Qp=Bs("intersect",!1),Vp=Bs("except",!1);var Br=class{static[m]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=h(e,fr)?e:void 0,this.dialectConfig=h(e,fr)?void 0:e}$with=(e,r)=>{let n=this;return{as:o=>(typeof o=="function"&&(o=o(n)),new Proxy(new ot(o.getSQL(),r??("getSelectedFields"in o?o.getSelectedFields()??{}:{}),e,!0),new U({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...e){let r=this;function n(o){return new Be({fields:o??void 0,session:void 0,dialect:r.getDialect(),withList:e})}function s(o){return new Be({fields:o??void 0,session:void 0,dialect:r.getDialect(),withList:e,distinct:!0})}return{select:n,selectDistinct:s}}select(e){return new Be({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Be({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||(this.dialect=new zs(this.dialectConfig)),this.dialect}};var Mn=class{constructor(e,r,n,s){this.table=e,this.session=r,this.dialect=n,this.withList=s}static[m]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw new Error("values() must be called with at least one value");let r=e.map(n=>{let s={},o=this.table[v.Symbol.Columns];for(let i of Object.keys(n)){let a=n[i];s[i]=h(a,_)?a:new xe(a,o[i])}return s});return new Fs(this.table,r,this.session,this.dialect,this.withList)}select(e){let r=typeof e=="function"?e(new Br):e;if(!h(r,_)&&!it(this.table[qr],r._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new Fs(this.table,r,this.session,this.dialect,this.withList,!0)}},Fs=class extends Z{constructor(e,r,n,s,o,i){super(),this.session=n,this.dialect=s,this.config={table:e,values:r,withList:o,select:i}}static[m]="SQLiteInsert";config;returning(e=this.config.table[de.Symbol.Columns]){return this.config.returning=ce(e),this}onConflictDoNothing(e={}){if(this.config.onConflict||(this.config.onConflict=[]),e.target===void 0)this.config.onConflict.push(f` on conflict do nothing`);else{let r=Array.isArray(e.target)?f`${e.target}`:f`${[e.target]}`,n=e.where?f` where ${e.where}`:f``;this.config.onConflict.push(f` on conflict ${r} do nothing${n}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');this.config.onConflict||(this.config.onConflict=[]);let r=e.where?f` where ${e.where}`:void 0,n=e.targetWhere?f` where ${e.targetWhere}`:void 0,s=e.setWhere?f` where ${e.setWhere}`:void 0,o=Array.isArray(e.target)?f`${e.target}`:f`${[e.target]}`,i=this.dialect.buildUpdateSet(this.config.table,Lt(this.config.table,e.set));return this.config.onConflict.push(f` on conflict ${o}${n} do update set ${i}${r}${s}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...r}=this.dialect.sqlToQuery(this.getSQL());return r}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:He(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}};var zn=class{constructor(e,r,n,s){this.table=e,this.session=r,this.dialect=n,this.withList=s}static[m]="SQLiteUpdateBuilder";set(e){return new Xi(this.table,Lt(this.table,e),this.session,this.dialect,this.withList)}},Xi=class extends Z{constructor(e,r,n,s,o){super(),this.session=n,this.dialect=s,this.config={set:r,table:e,withList:o,joins:[]}}static[m]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(r,n)=>{let s=De(r);if(typeof s=="string"&&this.config.joins.some(o=>o.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(typeof n=="function"){let o=this.config.from?h(r,de)?r[v.Symbol.Columns]:h(r,Q)?r._.selectedFields:h(r,Mt)?r[H].selectedFields:void 0:void 0;n=n(new Proxy(this.config.table[v.Symbol.Columns],new U({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),o&&new Proxy(o,new U({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:n,table:r,joinType:e,alias:s}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]=="function"){let r=e[0](new Proxy(this.config.table[v.Symbol.Columns],new U({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(r)?r:[r];this.config.orderBy=n}else{let r=e;this.config.orderBy=r}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[de.Symbol.Columns]){return this.config.returning=ce(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...r}=this.dialect.sqlToQuery(this.getSQL());return r}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:He(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}};var Qs=class t extends _{constructor(e){super(t.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.session=e.session,this.sql=t.buildCount(e.source,e.filters)}sql;static[m]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,r){return f`(select count(*) from ${e}${f.raw(" where ").if(r)}${r})`}static buildCount(e,r){return f`select count(*) from ${e}${f.raw(" where ").if(r)}${r}`}then(e,r){return Promise.resolve(this.session.count(this.sql)).then(e,r)}catch(e){return this.then(void 0,e)}finally(e){return this.then(r=>(e?.(),r),r=>{throw e?.(),r})}};var Vs=class{constructor(e,r,n,s,o,i,a,c){this.mode=e,this.fullSchema=r,this.schema=n,this.tableNamesMap=s,this.table=o,this.tableConfig=i,this.dialect=a,this.session=c}static[m]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new Ws(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many"):new Un(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many")}findFirst(e){return this.mode==="sync"?new Ws(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Un(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}},Un=class extends Z{constructor(e,r,n,s,o,i,a,c,l){super(),this.fullSchema=e,this.schema=r,this.tableNamesMap=n,this.table=s,this.tableConfig=o,this.dialect=i,this.session=a,this.config=c,this.mode=l}static[m]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:r,builtQuery:n}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](n,void 0,this.mode==="first"?"get":"all",!0,(s,o)=>{let i=s.map(a=>Ur(this.schema,this.tableConfig,a,r.selection,o));return this.mode==="first"?i[0]:i})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),r=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:r}}toSQL(){return this._toSQL().builtQuery}executeRaw(){return this.mode==="first"?this._prepare(!1).get():this._prepare(!1).all()}async execute(){return this.executeRaw()}},Ws=class extends Un{static[m]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}};var pr=class extends Z{constructor(e,r,n,s,o){super(),this.execute=e,this.getSQL=r,this.dialect=s,this.mapBatchResult=o,this.config={action:n}}static[m]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,r){return r?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}};var Fr=class{constructor(e,r,n,s){this.resultKind=e,this.dialect=r,this.session=n,this._=s?{schema:s.schema,fullSchema:s.fullSchema,tableNamesMap:s.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let o=this.query;if(this._.schema)for(let[i,a]of Object.entries(this._.schema))o[i]=new Vs(e,s.fullSchema,this._.schema,this._.tableNamesMap,s.fullSchema[i],a,r,n);this.$cache={invalidate:async i=>{}}}static[m]="BaseSQLiteDatabase";query;$with=(e,r)=>{let n=this;return{as:o=>(typeof o=="function"&&(o=o(new Br(n.dialect))),new Proxy(new ot(o.getSQL(),r??("getSelectedFields"in o?o.getSelectedFields()??{}:{}),e,!0),new U({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(e,r){return new Qs({source:e,filters:r,session:this.session})}with(...e){let r=this;function n(c){return new Be({fields:c??void 0,session:r.session,dialect:r.dialect,withList:e})}function s(c){return new Be({fields:c??void 0,session:r.session,dialect:r.dialect,withList:e,distinct:!0})}function o(c){return new zn(c,r.session,r.dialect,e)}function i(c){return new Mn(c,r.session,r.dialect,e)}function a(c){return new An(c,r.session,r.dialect,e)}return{select:n,selectDistinct:s,update:o,insert:i,delete:a}}select(e){return new Be({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Be({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new zn(e,this.session,this.dialect)}$cache;insert(e){return new Mn(e,this.session,this.dialect)}delete(e){return new An(e,this.session,this.dialect)}run(e){let r=typeof e=="string"?f.raw(e):e.getSQL();return this.resultKind==="async"?new pr(async()=>this.session.run(r),()=>r,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session)):this.session.run(r)}all(e){let r=typeof e=="string"?f.raw(e):e.getSQL();return this.resultKind==="async"?new pr(async()=>this.session.all(r),()=>r,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session)):this.session.all(r)}get(e){let r=typeof e=="string"?f.raw(e):e.getSQL();return this.resultKind==="async"?new pr(async()=>this.session.get(r),()=>r,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session)):this.session.get(r)}values(e){let r=typeof e=="string"?f.raw(e):e.getSQL();return this.resultKind==="async"?new pr(async()=>this.session.values(r),()=>r,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session)):this.session.values(r)}transaction(e,r){return this.session.transaction(e,r)}};var ea=class{static[m]="Cache"},ut=class extends ea{strategy(){return"all"}static[m]="NoopCache";async get(e){}async put(e,r,n,s){}async onMutate(e){}};async function Qr(t,e){let r=`${t}-${JSON.stringify(e)}`,s=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",s);return[...new Uint8Array(o)].map(c=>c.toString(16).padStart(2,"0")).join("")}var ta=class extends Z{constructor(e){super(),this.resultCb=e}static[m]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}},Hs=class{constructor(e,r,n,s,o,i){this.mode=e,this.executeMethod=r,this.query=n,this.cache=s,this.queryMetadata=o,this.cacheConfig=i,s&&s.strategy()==="all"&&i===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}static[m]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,r,n){if(this.cache===void 0||h(this.cache,ut)||this.queryMetadata===void 0)try{return await n()}catch(s){throw new Ae(e,r,s)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await n()}catch(s){throw new Ae(e,r,s)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[s]=await Promise.all([n(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return s}catch(s){throw new Ae(e,r,s)}if(!this.cacheConfig)try{return await n()}catch(s){throw new Ae(e,r,s)}if(this.queryMetadata.type==="select"){let s=await this.cache.get(this.cacheConfig.tag??await Qr(e,r),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(s===void 0){let o;try{o=await n()}catch(i){throw new Ae(e,r,i)}return await this.cache.put(this.cacheConfig.tag??await Qr(e,r),o,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),o}return s}try{return await n()}catch(s){throw new Ae(e,r,s)}}getQuery(){return this.query}mapRunResult(e,r){return e}mapAllResult(e,r){throw new Error("Not implemented")}mapGetResult(e,r){throw new Error("Not implemented")}execute(e){return this.mode==="async"?this[this.executeMethod](e):new ta(()=>this[this.executeMethod](e))}mapResult(e,r){switch(this.executeMethod){case"run":return this.mapRunResult(e,r);case"all":return this.mapAllResult(e,r);case"get":return this.mapGetResult(e,r)}}},Js=class{constructor(e){this.dialect=e}static[m]="SQLiteSession";prepareOneTimeQuery(e,r,n,s,o,i,a){return this.prepareQuery(e,r,n,s,o,i,a)}run(e){let r=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(r,void 0,"run",!1).run()}catch(n){throw new _t({cause:n,message:`Failed to run the query '${r.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw new Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw new Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw new Error("Not implemented")}},Zs=class extends Fr{constructor(e,r,n,s,o=0){super(e,r,n,s),this.schema=s,this.nestedIndex=o}static[m]="SQLiteTransaction";rollback(){throw new zr}};var ra=class{static[m]="ConsoleLogWriter";write(e){console.log(e)}},Vr=class{static[m]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new ra}logQuery(e,r){let n=r.map(o=>{try{return JSON.stringify(o)}catch{return String(o)}}),s=n.length?` -- params: [${n.join(", ")}]`:"";this.writer.write(`Query: ${e}${s}`)}},Wr=class{static[m]="NoopLogger";logQuery(){}};var na=class t{config;constructor(e){this.config=e}name(e){return this.clone({name:e})}nullable(){return this.clone({nullable:!0})}notNull(){return this.clone({nullable:!1})}primaryKey(){return this.clone({primaryKey:!0,nullable:!1})}autoIncrement(){return this.clone({autoIncrement:!0})}unique(){return this.clone({unique:!0})}default(e){return this.clone({default:{kind:"literal",value:e}})}defaultNow(){return this.clone({default:{kind:"now"}})}defaultEmptyJson(){return this.clone({default:{kind:"emptyJson"}})}clone(e){return new t({...this.config,...e})}},sa=class{index(e){return new Gs("index",e)}unique(e){return new Gs("unique",e)}},Gs=class{kind;name;constructor(e,r){this.kind=e,this.name=r}on(...e){return{kind:this.kind,name:this.name,columns:e}}},Et={id:t=>St("id",t).notNull(),int:t=>St("int",t),bigint:t=>St("bigint",t),text:t=>St("text",t),boolean:t=>St("boolean",t),real:t=>St("real",t),blob:t=>St("blob",t),json:t=>St("json",t),timestampMs:t=>St("timestampMs",t),table:em},Q0=Et.timestampMs("created_at").notNull().defaultNow(),V0=Et.timestampMs("updated_at").notNull().defaultNow();function Jl(t){let e=Zl(t.databaseName),r=Object.fromEntries(Object.entries(t.tables).map(([s,o])=>[s,{logicalName:o.logicalName,physicalName:Gl({extensionId:t.extensionId,databaseName:e,tableName:o.logicalName}),columns:o.columns,indexes:o.indexes,primaryKey:o.primaryKey}])),n={extensionId:t.extensionId,databaseName:e,tables:r};return Object.assign(n,Jp(r))}function Zl(t){let e=t.trim();if(!/^[A-Za-z][A-Za-z0-9_]*$/u.test(e))throw new Error(`Invalid databaseName "${t}".`);return e}function Wp(t){return`${t.extensionId}_${Zl(t.databaseName)}`}function Gl(t){return`${Wp(t)}_${t.tableName}`}function oa(t){return t.config}function ia(t,e){return e.config.name??Hp(t)}function Hp(t){return t.replace(/([a-z0-9])([A-Z])/gu,"$1_$2").replace(/[-\s]+/gu,"_").toLowerCase()}function St(t,e){return new na({kind:t,name:e,nullable:!0,primaryKey:!1,autoIncrement:!1,unique:!1})}function Jp(t){return Object.fromEntries(Object.entries(t).map(([e,r])=>[e,Zp(r)]))}function Zp(t){let e=Object.fromEntries(Object.entries(t.columns).map(([r,n])=>[r,Gp(r,n)]));return ml(t.physicalName,e,r=>{let n=t.primaryKey?.map(o=>r[o]),s=t.indexes.map(o=>{let i=o.columns.map(c=>r[c]);return(o.kind==="unique"?gl(o.name):hl(o.name)).on(i[0],...i.slice(1))});return n?.length?[yl({columns:[n[0],...n.slice(1)]}),...s]:s})}function Gp(t,e){let r=oa(e),n=ia(t,e),s=Yp(n,r);return r.primaryKey?s=r.autoIncrement?s.primaryKey({autoIncrement:!0}):s.primaryKey():r.nullable||(s=s.notNull()),r.unique&&(s=s.unique()),r.default&&(s=s.default(Xp(r.default))),s}function Yp(t,e){switch(e.kind){case"id":case"int":case"bigint":case"timestampMs":return Tn(t,{mode:"number"});case"boolean":return Tn(t,{mode:"boolean"});case"real":return Os(t);case"blob":return As(t,{mode:"buffer"});case"json":return Rn(t,{mode:"json"});case"text":return Rn(t)}}function Xp(t){return t.kind==="now"?f`(cast(strftime('%s','now') as integer) * 1000)`:t.kind==="emptyJson"?{}:t.value}function em(t,e,r){let n=r?.(new sa),s=n?.primaryKey;if(s&&(s.length===0||new Set(s).size!==s.length||Object.values(e).some(o=>o.config.primaryKey)||s.some(o=>!e[o]||e[o].config.nullable||e[o].config.autoIncrement)))throw new Error(`Invalid composite primary key for ${t}: declare distinct NOT NULL columns without another primary key.`);return{logicalName:t,columns:e,indexes:n?.indexes??[],primaryKey:s}}var Ys=class extends Js{constructor(e,r,n,s,o={}){super(r),this.client=e,this.schema=n,this.batchCLient=s,this.logger=o.logger??new Wr,this.cache=o.cache??new ut}static[m]="SQLiteRemoteSession";logger;cache;prepareQuery(e,r,n,s,o,i,a){return new ca(this.client,e,this.logger,this.cache,i,a,r,n,s,o)}async batch(e){let r=[],n=[];for(let o of e){let i=o._prepare(),a=i.getQuery();r.push(i),n.push({sql:a.sql,params:a.params,method:a.method})}return(await this.batchCLient(n)).map((o,i)=>r[i].mapResult(o,!0))}async transaction(e,r){let n=new aa("async",this.dialect,this,this.schema);await this.run(f.raw(`begin${r?.behavior?" "+r.behavior:""}`));try{let s=await e(n);return await this.run(f`commit`),s}catch(s){throw await this.run(f`rollback`),s}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}},aa=class t extends Zs{static[m]="SQLiteProxyTransaction";async transaction(e){let r=`sp${this.nestedIndex}`,n=new t("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(f.raw(`savepoint ${r}`));try{let s=await e(n);return await this.session.run(f.raw(`release savepoint ${r}`)),s}catch(s){throw await this.session.run(f.raw(`rollback to savepoint ${r}`)),s}}},ca=class extends Hs{constructor(e,r,n,s,o,i,a,c,l,u){super("async",c,r,s,o,i),this.client=e,this.logger=n,this.fields=a,this._isResponseInArrayMode=l,this.customResultMapper=u,this.customResultMapper=u,this.method=c}static[m]="SQLiteProxyPreparedQuery";method;getQuery(){return{...this.query,method:this.method}}async run(e){let r=lr(this.query.params,e??{});return this.logger.logQuery(this.query.sql,r),await this.queryWithCache(this.query.sql,r,async()=>await this.client(this.query.sql,r,"run"))}mapAllResult(e,r){return r&&(e=e.rows),!this.fields&&!this.customResultMapper?e:this.customResultMapper?this.customResultMapper(e):e.map(n=>En(this.fields,n,this.joinsNotNullableMap))}async all(e){let{query:r,logger:n,client:s}=this,o=lr(r.params,e??{});n.logQuery(r.sql,o);let{rows:i}=await this.queryWithCache(r.sql,o,async()=>await s(r.sql,o,"all"));return this.mapAllResult(i)}async get(e){let{query:r,logger:n,client:s}=this,o=lr(r.params,e??{});n.logQuery(r.sql,o);let i=await this.queryWithCache(r.sql,o,async()=>await s(r.sql,o,"get"));return this.mapGetResult(i.rows)}mapGetResult(e,r){r&&(e=e.rows);let n=e;if(!this.fields&&!this.customResultMapper)return n;if(n)return this.customResultMapper?this.customResultMapper([e]):En(this.fields,n,this.joinsNotNullableMap)}async values(e){let r=lr(this.query.params,e??{});return this.logger.logQuery(this.query.sql,r),(await this.queryWithCache(this.query.sql,r,async()=>await this.client(this.query.sql,r,"values"))).rows}isResponseInArrayMode(){return this._isResponseInArrayMode}};var la=class extends Fr{static[m]="SqliteRemoteDatabase";async batch(e){return this.session.batch(e)}};function Yl(t,e,r){let n=new Us({casing:r?.casing}),s,o,i,a={};e&&(typeof e=="function"?(i=e,a=r??{}):(i=void 0,a=e),a.logger===!0?s=new Vr:a.logger!==!1&&(s=a.logger,o=a.cache));let c;if(a.schema){let d=qs(a.schema,Ms);c={fullSchema:a.schema,schema:d.tables,tableNamesMap:d.tableNamesMap}}let l=new Ys(t,n,c,i,{logger:s,cache:o}),u=new la("async",n,l,c);return u.$cache=o,u.$cache&&(u.$cache.invalidate=o?.onMutate),u}function Xl(t,e){return Yl(async(r,n,s)=>{let o=s==="run"?"run":"values",a=(await t.execute({type:"query",statement:{sql:r,params:n,method:o}})).rows;return{rows:s==="get"?a[0]:a}},async r=>(await t.execute({type:"transactionBatch",statements:r.map(s=>({sql:s.sql,params:s.params,method:s.method==="run"?"run":"values"}))})).results.map((s,o)=>({rows:r[o]?.method==="get"?s.rows[0]:s.rows})),e)}var Kn=Object.freeze({bytes:16*1024*1024,entries:256,rows:5e4,fieldBytes:1024*1024,depth:64}),tu=new TextEncoder;function tm(t){let e=new Set,r=0,n=o=>{if(r+=tu.encode(o).byteLength,r>Kn.bytes)throw new Error("Dataset \u8D85\u51FA\u6587\u4EF6\u5927\u5C0F\u9650\u5236\u3002");return o};function s(o,i){if(i>Kn.depth)throw new Error("Dataset \u5D4C\u5957\u8FC7\u6DF1\u3002");if(o===null||typeof o=="boolean"||typeof o=="string"||typeof o=="number"&&Number.isFinite(o))return n(JSON.stringify(o));if(!o||typeof o!="object")throw new Error("Dataset \u53EA\u80FD\u5305\u542B\u7EAF JSON \u503C\u3002");if(e.has(o))throw new Error("Dataset \u4E0D\u5141\u8BB8\u5FAA\u73AF\u5F15\u7528\u3002");if(!Array.isArray(o)&&Object.getPrototypeOf(o)!==Object.prototype&&Object.getPrototypeOf(o)!==null)throw new Error("Dataset \u4E0D\u5141\u8BB8 class\u3001Date \u6216\u5176\u5B83\u5B9E\u4F8B\u3002");let a=Object.getOwnPropertyDescriptors(o);if(Object.getOwnPropertySymbols(o).length||Object.entries(a).some(([c,l])=>(!Array.isArray(o)||c!=="length")&&(!l.enumerable||!("value"in l))))throw new Error("Dataset \u4E0D\u5141\u8BB8 Symbol\u3001\u8BBF\u95EE\u5668\u6216\u4E0D\u53EF\u679A\u4E3E\u5B57\u6BB5\u3002");e.add(o);try{if(Array.isArray(o)){if(Object.keys(o).length!==o.length||Object.keys(o).some((l,u)=>l!==String(u)))throw new Error("Dataset \u4E0D\u5141\u8BB8\u7A00\u758F\u6570\u7EC4\u6216\u989D\u5916\u6570\u7EC4\u5C5E\u6027\u3002");return n("[]"+",".repeat(Math.max(0,o.length-1))),`[${Array.from({length:o.length},(l,u)=>s(a[String(u)].value,i+1)).join(",")}]`}let c=Object.keys(a).sort();return n("{}"+",".repeat(Math.max(0,c.length-1))),`{${c.map(l=>`${n(JSON.stringify(l)+":")}${s(a[l].value,i+1)}`).join(",")}}`}finally{e.delete(o)}}return s(t,0)}function ru(t,e){let r=ua(JSON.parse(tm(t)),"Dataset");if(eu(r,["schemaVersion","extensionId","entries"]),r.schemaVersion!==1||r.extensionId!==e.extensionId||!e.extensionId)throw new Error("Dataset \u7248\u672C\u6216 Extension \u8EAB\u4EFD\u4E0D\u5339\u914D\u3002");if(!Array.isArray(r.entries)||r.entries.length>Kn.entries)throw new Error("Dataset entries \u65E0\u6548\u6216\u8D85\u9650\u3002");let n=new Map(Object.values(e.metadata.tables??{}).map(o=>[o.tableName,o])),s=0;for(let o of r.entries){let i=ua(o,"Dataset entry");eu(i,["tableName","rows"]);let a=typeof i.tableName=="string"?n.get(i.tableName):void 0;if(!a?.columns)throw new Error("Dataset \u5F15\u7528\u4E86\u672A\u77E5\u8868\u3002");if(!Array.isArray(i.rows)||(s+=i.rows.length)>Kn.rows)throw new Error("Dataset rows \u65E0\u6548\u6216\u8D85\u9650\u3002");let c=a.columns,l=a.primaryKey?.length?a.primaryKey:Object.values(c).filter(d=>d.primary||d.primaryKey).map(d=>d.name),u=l.map(d=>Object.keys(c).find(p=>c[p].name===d));if(l.some(d=>typeof d!="string"||!d)||!u.length||u.some(d=>!d)||new Set(u).size!==u.length)throw new Error("Dataset \u8868\u7F3A\u5C11\u6709\u6548\u7A33\u5B9A\u4E3B\u952E\u3002");for(let d of i.rows){let p=ua(d,"Dataset row");for(let g of Object.keys(p)){if(!Object.hasOwn(c,g))throw new Error(`Dataset \u672A\u77E5\u5B57\u6BB5\uFF1A${g}`);if(tu.encode(JSON.stringify(p[g])).byteLength>Kn.fieldBytes)throw new Error(`Dataset \u5B57\u6BB5\u8D85\u9650\uFF1A${g}`);rm(p[g],c[g],g)}for(let[g,w]of Object.entries(c)){if(u.includes(g)&&(!Object.hasOwn(p,g)||p[g]===null))throw new Error(`Dataset \u7F3A\u5931\u7A33\u5B9A\u4E3B\u952E\uFF1A${g}`);if(!Object.hasOwn(p,g)&&w.notNull&&w.default===void 0)throw new Error(`Dataset \u7F3A\u5931\u5FC5\u586B\u5B57\u6BB5\uFF1A${g}`)}}}return r}function rm(t,e,r){if(t===null){if(e.notNull||e.primary||e.primaryKey)throw new Error(`Dataset \u5B57\u6BB5\u4E0D\u80FD\u4E3A null\uFF1A${r}`);return}let n=e.dataType;if(n!=="json"&&!(n==="string"&&typeof t=="string")&&!(n==="boolean"&&typeof t=="boolean")){if(n==="number"&&typeof t=="number"){if(/integer|bigint|timestamp/iu.test(e.columnType??"")&&!Number.isSafeInteger(t))throw new Error(`Dataset \u6574\u6570\u5B57\u6BB5\u65E0\u6548\uFF1A${r}`);return}throw new Error(`Dataset \u5B57\u6BB5\u7C7B\u578B\u4E0D\u5339\u914D\u6216\u4E0D\u652F\u6301\uFF1A${r}`)}}function ua(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} \u5FC5\u987B\u662F\u5BF9\u8C61\u3002`);return t}function eu(t,e){if(Object.keys(t).length!==e.length||e.some(r=>!Object.hasOwn(t,r)))throw new Error("Dataset \u7ED3\u6784\u5B57\u6BB5\u65E0\u6548\u3002")}async function su(t,e,r={}){let n=ou(e),s=0;for(let a of n.values()){let c=sm(a);c&&(await t.execute({type:"query",statement:{sql:c,method:"run"}}),await im(t,a),await am(t,a),s+=1)}for(let a of e.sqliteMigrations??[])await t.execute({type:"applyMigration",migrationId:a.id,statements:a.statements});let o=await um(t,nm(e),n),i=r.dataset?await hm(t,e,r.dataset):0;return{tablesEnsured:s,bootstrapRows:o,datasetRows:i}}function ou(t){let e=new Map;for(let r of Object.values(t.tables??{})){let n=dt(r?.tableName);n&&e.set(n,r)}return e}function nm(t){return Array.isArray(t.bootstrap)?t.bootstrap:Array.isArray(t.install)?t.install:[]}function sm(t){let e=dt(t.tableName);if(!e||!t.columns||typeof t.columns!="object")return"";let r=Object.values(t.columns).map(n=>iu(n)).filter(Boolean);return r.length===0?"":(om(r,t),`CREATE TABLE IF NOT EXISTS "${Ze(e)}" (${r.join(", ")});`)}function om(t,e){if(!e.primaryKey?.length)return;let r=Object.values(e.columns??{});if(new Set(e.primaryKey).size!==e.primaryKey.length||r.some(n=>n.primary||n.primaryKey)||e.primaryKey.some(n=>!r.some(s=>s.name===n&&s.notNull)))throw new Error(`Invalid composite primary key for ${e.tableName}.`);t.push(`PRIMARY KEY (${e.primaryKey.map(n=>`"${Ze(n)}"`).join(", ")})`)}async function im(t,e){let r=dt(e.tableName);if(!r||!e.columns||typeof e.columns!="object")return;let n=await t.execute({type:"query",statement:{sql:`PRAGMA table_info("${Ze(r)}")`,method:"all"}}),s=new Set((Array.isArray(n.rows)?n.rows:[]).flatMap(o=>Array.isArray(o)?typeof o[1]=="string"?[o[1]]:[]:o&&typeof o=="object"&&"name"in o&&typeof o.name=="string"?[o.name]:[]));for(let o of Object.values(e.columns)){let i=dt(o.name);if(!i||s.has(i))continue;if(o.primary||o.primaryKey||o.autoIncrement||o.unique)throw new Error(`Cannot safely add constrained SQLite column ${r}.${i} from metadata; use an explicit migration.`);if(o.notNull&&!au(o))throw new Error(`Cannot safely add NOT NULL SQLite column ${r}.${i} without a default; use an explicit migration.`);let a=iu(o);a&&await t.execute({type:"query",statement:{sql:`ALTER TABLE "${Ze(r)}" ADD COLUMN ${a};`,method:"run"}})}}async function am(t,e){let r=dt(e.tableName);if(r)for(let n of e.indexes??[]){let s=cm(r,n);s&&await t.execute({type:"query",statement:{sql:s,method:"run"}})}}function cm(t,e){let r=dt(e.name),n=lm(e.columns);return!r||n.length===0?"":["CREATE",e.unique===!0?"UNIQUE INDEX IF NOT EXISTS":"INDEX IF NOT EXISTS",`"${Ze(r)}"`,"ON",`"${Ze(t)}"`,`(${n.map(s=>`"${Ze(s)}"`).join(", ")});`].join(" ")}function lm(t){return Array.isArray(t)?t.map(e=>dt(e)).filter(e=>!!e):[]}function iu(t){let e=dt(t.name);if(!e)return"";let r=pm(t.columnType),n=!!(t.primary||t.primaryKey),s=[`"${Ze(e)}"`,r];t.notNull&&!n&&s.push("NOT NULL"),n&&s.push(t.autoIncrement&&r==="INTEGER"?"PRIMARY KEY AUTOINCREMENT":"PRIMARY KEY"),t.unique&&!n&&s.push("UNIQUE");let o=au(t);return o&&s.push(o),s.join(" ")}function au(t){let e=t.default;return e===void 0?"":e&&typeof e=="object"&&"kind"in e&&e.kind==="now"?"DEFAULT (cast(strftime('%s','now') as integer) * 1000)":e&&typeof e=="object"&&"kind"in e&&e.kind==="emptyJson"?"DEFAULT '{}'":e&&typeof e=="object"&&"kind"in e&&e.kind==="literal"?`DEFAULT ${nu(e.value)}`:`DEFAULT ${nu(e)}`}function nu(t){if(t==null)return"NULL";if(typeof t=="number")return Number.isFinite(t)?String(t):"NULL";if(typeof t=="boolean")return t?"1":"0";let e=typeof t=="string"?t:JSON.stringify(t);return`'${String(e).replaceAll("'","''")}'`}async function um(t,e,r){let n=0;for(let s of e){let o=dt(s.tableName),i=Array.isArray(s.rows)?s.rows:[];if(!o||i.length===0)continue;let a=r.get(o);if(a)for(let c of i)n+=await dm(t,o,a,c)}return n}async function dm(t,e,r,n){let s=fm(r),o=Object.keys(n).map(a=>{let c=s.get(a)??s.get(`@name:${a}`);return c?{columnName:c,value:mm(n[a])}:null}).filter(a=>a!==null);if(o.length===0)return 0;await t.execute({type:"query",statement:{sql:[`INSERT OR IGNORE INTO "${Ze(e)}"`,`(${o.map(a=>`"${Ze(a.columnName)}"`).join(", ")})`,`VALUES (${o.map(()=>"?").join(", ")});`].join(" "),params:o.map(a=>a.value),method:"run"}});let i=await t.execute({type:"query",statement:{sql:"SELECT changes() AS changes",method:"get"}});return Number(i.rows&&i.rows.changes)||0}function fm(t){let e=new Map;for(let[r,n]of Object.entries(t.columns??{})){let s=dt(n.name);s&&(e.set(r,s),e.set(`@name:${s}`,s))}return e}function pm(t){return t==="SQLiteInteger"||t==="SQLiteBoolean"||t==="SQLiteTimestamp"?"INTEGER":t==="SQLiteReal"?"REAL":t==="SQLiteBlob"?"BLOB":"TEXT"}function mm(t){return t instanceof Date?t.valueOf():typeof t=="boolean"?t?1:0:t&&typeof t=="object"?JSON.stringify(t):t}function dt(t){return String(t??"").trim()}function Ze(t){return t.replaceAll('"','""')}async function hm(t,e,r){let n=gm(e,r,"sqlite");return n.length?(await t.execute({type:"transactionBatch",statements:n.map(i=>({...i,method:"all"}))})).results.reduce((i,a)=>i+(Array.isArray(a.rows)?a.rows.length:0),0):0}function gm(t,e,r){let n=ru(e.value,{extensionId:e.extensionId,metadata:t}),s=ou(t),o=i=>`"${Ze(i)}"`;return n.entries.flatMap(i=>{let a=s.get(i.tableName),c=a.columns,l=a.primaryKey?.length?a.primaryKey:Object.values(c).filter(u=>u.primary||u.primaryKey).map(u=>u.name);return i.rows.map(u=>{let d=Object.keys(u);return{sql:`INSERT INTO ${o(i.tableName)} (${d.map(p=>o(c[p].name)).join(", ")}) VALUES (${d.map((p,g)=>r==="sqlite"?"?":`$${g+1}`).join(", ")}) ON CONFLICT (${l.map(o).join(", ")}) DO NOTHING RETURNING 1;`,params:d.map(p=>{let g=u[p];return g===null?null:c[p].dataType==="json"?JSON.stringify(g):r==="sqlite"&&typeof g=="boolean"?Number(g):g})}})})}var Hr="SQL_EXECUTOR";function ym(t){return{async execute(e){return lu(t,e)}}}function Bn(t){return{async execute(e){let r=await t.fetch("https://sql-executor.local/execute",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let n=await r.text();throw new Error(`Durable Object SQL executor failed (${r.status}): ${n}`)}return await r.json()}}}var Xs=class{state;constructor(e){this.state=e}async fetch(e){let r=e.clone();try{let n=await wm(e),s=await lu(this.state,n);return Response.json(s)}catch(n){return console.error("Durable Object SQL executor request failed.",{requestType:await bm(r),error:n instanceof Error?n.message:String(n)}),Response.json({error:n instanceof Error?n.message:String(n)},{status:500})}}};async function bm(t){let e=new URL(t.url).pathname;if(e==="/apply-metadata"||e==="/bootstrap")return"applyMetadata";if(e==="/apply-migration")return"applyMigration";let r=await t.clone().json().catch(()=>null);return typeof r?.type=="string"?r.type:"unknown"}async function lu(t,e){return e.type==="query"?da(t.storage.sql,e.statement):e.type==="batch"?{results:e.statements.map(r=>da(t.storage.sql,r))}:e.type==="transactionBatch"?cu(t,()=>({results:e.statements.map(r=>da(t.storage.sql,r))})):e.type==="applyMigration"?cu(t,()=>{if(xm(t.storage.sql),_m(t.storage.sql,e.migrationId))return{rowsAffected:0};for(let r of e.statements)t.storage.sql.exec(r);return Sm(t.storage.sql,e.migrationId),{rowsAffected:0}}):e.type==="applyMetadata"?await su(ym(t),e.metadata,{dataset:e.dataset}):{statements:[]}}async function wm(t){if(t.method!=="POST")throw new Error("Durable Object SQL executor only accepts POST requests.");let e=new URL(t.url).pathname,r=await t.json();return e==="/apply-metadata"||e==="/bootstrap"?{type:"applyMetadata",metadata:r.metadata,dataset:r.dataset}:e==="/apply-migration"?{type:"applyMigration",migrationId:String(r.migrationId??"default"),statements:Array.isArray(r.statements)?r.statements.map(String):[]}:r}function cu(t,e){if(t.storage.transactionSync)return t.storage.transactionSync(e);t.storage.sql.exec("BEGIN");try{let r=e();return t.storage.sql.exec("COMMIT"),r}catch(r){throw t.storage.sql.exec("ROLLBACK"),r}}function da(t,e){let r=t.exec(e.sql,...e.params??[]),n=e.method??"run";return n==="values"?{rows:Em(r.raw?.())}:n==="get"?{rows:uu(r)}:n==="all"?{rows:r.toArray?.()??[]}:{rows:[]}}function uu(t){try{return t.one?.()}catch(e){if(vm(e))return;throw e}}function vm(t){return t instanceof Error&&t.message.toLowerCase().includes("no results")}function xm(t){t.exec(`
21
+ CREATE TABLE IF NOT EXISTS "__kuafu_sql_migrations" (
22
+ id TEXT PRIMARY KEY,
23
+ applied_at INTEGER NOT NULL
24
+ )
25
+ `)}function _m(t,e){return!!uu(t.exec('SELECT id FROM "__kuafu_sql_migrations" WHERE id = ? LIMIT 1',e))}function Sm(t,e){t.exec('INSERT OR IGNORE INTO "__kuafu_sql_migrations" (id, applied_at) VALUES (?, ?)',e,Date.now())}function Em(t){return t?Array.isArray(t)?t:"toArray"in t?t.toArray():Array.from(t):[]}var Jr=class extends he{static[m]="PgViewBase"};var zt=class{static[m]="PgDialect";casing;constructor(e){this.casing=new Mr(e?.casing)}async migrate(e,r,n){let s=typeof n=="string"?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",o=typeof n=="string"?"drizzle":n.migrationsSchema??"drizzle",i=f`
26
+ CREATE TABLE IF NOT EXISTS ${f.identifier(o)}.${f.identifier(s)} (
27
+ id SERIAL PRIMARY KEY,
28
+ hash text NOT NULL,
29
+ created_at bigint
30
+ )
31
+ `;await r.execute(f`CREATE SCHEMA IF NOT EXISTS ${f.identifier(o)}`),await r.execute(i);let c=(await r.all(f`select id, hash, created_at from ${f.identifier(o)}.${f.identifier(s)} order by created_at desc limit 1`))[0];await r.transaction(async l=>{for await(let u of e)if(!c||Number(c.created_at)<u.folderMillis){for(let d of u.sql)await l.execute(f.raw(d));await l.execute(f`insert into ${f.identifier(o)}.${f.identifier(s)} ("hash", "created_at") values(${u.hash}, ${u.folderMillis})`)}})}escapeName(e){return`"${e.replace(/"/g,'""')}"`}escapeParam(e){return`$${e+1}`}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let r=[f`with `];for(let[n,s]of e.entries())r.push(f`${f.identifier(s._.alias)} as (${s._.sql})`),n<e.length-1&&r.push(f`, `);return r.push(f` `),f.join(r)}buildDeleteQuery({table:e,where:r,returning:n,withList:s}){let o=this.buildWithCTE(s),i=n?f` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,a=r?f` where ${r}`:void 0;return f`${o}delete from ${e}${a}${i}`}buildUpdateSet(e,r){let n=e[v.Symbol.Columns],s=Object.keys(n).filter(i=>r[i]!==void 0||n[i]?.onUpdateFn!==void 0),o=s.length;return f.join(s.flatMap((i,a)=>{let c=n[i],l=c.onUpdateFn?.(),u=r[i]??(h(l,_)?l:f.param(l,c)),d=f`${f.identifier(this.casing.getColumnCasing(c))} = ${u}`;return a<o-1?[d,f.raw(", ")]:[d]}))}buildUpdateQuery({table:e,set:r,where:n,returning:s,withList:o,from:i,joins:a}){let c=this.buildWithCTE(o),l=e[Se.Symbol.Name],u=e[Se.Symbol.Schema],d=e[Se.Symbol.OriginalName],p=l===d?void 0:l,g=f`${u?f`${f.identifier(u)}.`:void 0}${f.identifier(d)}${p&&f` ${f.identifier(p)}`}`,w=this.buildUpdateSet(e,r),b=i&&f.join([f.raw(" from "),this.buildFromTable(i)]),E=this.buildJoins(a),S=s?f` returning ${this.buildSelection(s,{isSingleTable:!i})}`:void 0,k=n?f` where ${n}`:void 0;return f`${c}update ${g} set ${w}${b}${E}${k}${S}`}buildSelection(e,{isSingleTable:r=!1}={}){let n=e.length,s=e.flatMap(({field:o},i)=>{let a=[];if(h(o,_.Aliased)&&o.isSelectionField)a.push(f.identifier(o.fieldAlias));else if(h(o,_.Aliased)||h(o,_)){let c=h(o,_.Aliased)?o.sql:o;r?a.push(new _(c.queryChunks.map(l=>h(l,G)?f.identifier(this.casing.getColumnCasing(l)):l))):a.push(c),h(o,_.Aliased)&&a.push(f` as ${f.identifier(o.fieldAlias)}`)}else if(h(o,z))r?a.push(f.identifier(this.casing.getColumnCasing(o))):a.push(o);else if(h(o,Q)){let c=Object.entries(o._.selectedFields);if(c.length===1){let l=c[0][1],u=h(l,_)?l.decoder:h(l,z)?{mapFromDriverValue:d=>l.mapFromDriverValue(d)}:l.sql.decoder;u&&(o._.sql.decoder=u)}a.push(o)}return i<n-1&&a.push(f`, `),a});return f.join(s)}buildJoins(e){if(!e||e.length===0)return;let r=[];for(let[n,s]of e.entries()){n===0&&r.push(f` `);let o=s.table,i=s.lateral?f` lateral`:void 0,a=s.on?f` on ${s.on}`:void 0;if(h(o,Se)){let c=o[Se.Symbol.Name],l=o[Se.Symbol.Schema],u=o[Se.Symbol.OriginalName],d=c===u?void 0:s.alias;r.push(f`${f.raw(s.joinType)} join${i} ${l?f`${f.identifier(l)}.`:void 0}${f.identifier(u)}${d&&f` ${f.identifier(d)}`}${a}`)}else if(h(o,he)){let c=o[H].name,l=o[H].schema,u=o[H].originalName,d=c===u?void 0:s.alias;r.push(f`${f.raw(s.joinType)} join${i} ${l?f`${f.identifier(l)}.`:void 0}${f.identifier(u)}${d&&f` ${f.identifier(d)}`}${a}`)}else r.push(f`${f.raw(s.joinType)} join${i} ${o}${a}`);n<e.length-1&&r.push(f` `)}return f.join(r)}buildFromTable(e){if(h(e,v)&&e[v.Symbol.IsAlias]){let r=f`${f.identifier(e[v.Symbol.OriginalName])}`;return e[v.Symbol.Schema]&&(r=f`${f.identifier(e[v.Symbol.Schema])}.${r}`),f`${r} ${f.identifier(e[v.Symbol.Name])}`}return e}buildSelectQuery({withList:e,fields:r,fieldsFlat:n,where:s,having:o,table:i,joins:a,orderBy:c,groupBy:l,limit:u,offset:d,lockingClause:p,distinct:g,setOperators:w}){let b=n??ce(r);for(let J of b)if(h(J.field,z)&&me(J.field.table)!==(h(i,Q)?i._.alias:h(i,Jr)?i[H].name:h(i,_)?void 0:me(i))&&!(ke=>a?.some(({alias:bn})=>bn===(ke[v.Symbol.IsAlias]?me(ke):ke[v.Symbol.BaseName])))(J.field.table)){let ke=me(J.field.table);throw new Error(`Your "${J.path.join("->")}" field references a column "${ke}"."${J.field.name}", but the table "${ke}" is not part of the query! Did you forget to join it?`)}let E=!a||a.length===0,S=this.buildWithCTE(e),k;g&&(k=g===!0?f` distinct`:f` distinct on (${f.join(g.on,f`, `)})`);let q=this.buildSelection(b,{isSingleTable:E}),P=this.buildFromTable(i),X=this.buildJoins(a),L=s?f` where ${s}`:void 0,I=o?f` having ${o}`:void 0,A;c&&c.length>0&&(A=f` order by ${f.join(c,f`, `)}`);let V;l&&l.length>0&&(V=f` group by ${f.join(l,f`, `)}`);let oe=typeof u=="object"||typeof u=="number"&&u>=0?f` limit ${u}`:void 0,we=d?f` offset ${d}`:void 0,ue=f.empty();if(p){let J=f` for ${f.raw(p.strength)}`;p.config.of&&J.append(f` of ${f.join(Array.isArray(p.config.of)?p.config.of:[p.config.of],f`, `)}`),p.config.noWait?J.append(f` nowait`):p.config.skipLocked&&J.append(f` skip locked`),ue.append(J)}let re=f`${S}select${k} ${q} from ${P}${X}${L}${V}${I}${A}${oe}${we}${ue}`;return w.length>0?this.buildSetOperations(re,w):re}buildSetOperations(e,r){let[n,...s]=r;if(!n)throw new Error("Cannot pass undefined values to any set operator");return s.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:n}),s)}buildSetOperationQuery({leftSelect:e,setOperator:{type:r,isAll:n,rightSelect:s,limit:o,orderBy:i,offset:a}}){let c=f`(${e.getSQL()}) `,l=f`(${s.getSQL()})`,u;if(i&&i.length>0){let w=[];for(let b of i)if(h(b,G))w.push(f.identifier(b.name));else if(h(b,_)){for(let E=0;E<b.queryChunks.length;E++){let S=b.queryChunks[E];h(S,G)&&(b.queryChunks[E]=f.identifier(S.name))}w.push(f`${b}`)}else w.push(f`${b}`);u=f` order by ${f.join(w,f`, `)} `}let d=typeof o=="object"||typeof o=="number"&&o>=0?f` limit ${o}`:void 0,p=f.raw(`${r} ${n?"all ":""}`),g=a?f` offset ${a}`:void 0;return f`${c}${p}${l}${u}${d}${g}`}buildInsertQuery({table:e,values:r,onConflict:n,returning:s,withList:o,select:i,overridingSystemValue_:a}){let c=[],l=e[v.Symbol.Columns],u=Object.entries(l).filter(([S,k])=>!k.shouldDisableInsert()),d=u.map(([,S])=>f.identifier(this.casing.getColumnCasing(S)));if(i){let S=r;h(S,_)?c.push(S):c.push(S.getSQL())}else{let S=r;c.push(f.raw("values "));for(let[k,q]of S.entries()){let P=[];for(let[X,L]of u){let I=q[X];if(I===void 0||h(I,xe)&&I.value===void 0)if(L.defaultFn!==void 0){let A=L.defaultFn(),V=h(A,_)?A:f.param(A,L);P.push(V)}else if(!L.default&&L.onUpdateFn!==void 0){let A=L.onUpdateFn(),V=h(A,_)?A:f.param(A,L);P.push(V)}else P.push(f`default`);else P.push(I)}c.push(P),k<S.length-1&&c.push(f`, `)}}let p=this.buildWithCTE(o),g=f.join(c),w=s?f` returning ${this.buildSelection(s,{isSingleTable:!0})}`:void 0,b=n?f` on conflict ${n}`:void 0,E=a===!0?f`overriding system value `:void 0;return f`${p}insert into ${e} ${d} ${E}${g}${b}${w}`}buildRefreshMaterializedViewQuery({view:e,concurrently:r,withNoData:n}){let s=r?f` concurrently`:void 0,o=n?f` with no data`:void 0;return f`refresh materialized view${s} ${e}${o}`}prepareTyping(e){return h(e,Cn)||h(e,Nn)?"json":h(e,kn)?"decimal":h(e,Dn)?"time":h(e,$n)||h(e,qn)?"timestamp":h(e,On)||h(e,Pn)?"date":h(e,Ln)?"uuid":"none"}sqlToQuery(e,r){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:r})}buildRelationalQueryWithoutPK({fullSchema:e,schema:r,tableNamesMap:n,table:s,tableConfig:o,queryConfig:i,tableAlias:a,nestedQueryRelation:c,joinOn:l}){let u=[],d,p,g=[],w,b=[];if(i===!0)u=Object.entries(o.columns).map(([k,q])=>({dbKey:q.name,tsKey:k,field:ge(q,a),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let S=Object.fromEntries(Object.entries(o.columns).map(([I,A])=>[I,ge(A,a)]));if(i.where){let I=typeof i.where=="function"?i.where(S,Ds()):i.where;w=I&&qt(I,a)}let k=[],q=[];if(i.columns){let I=!1;for(let[A,V]of Object.entries(i.columns))V!==void 0&&A in o.columns&&(!I&&V===!0&&(I=!0),q.push(A));q.length>0&&(q=I?q.filter(A=>i.columns?.[A]===!0):Object.keys(o.columns).filter(A=>!q.includes(A)))}else q=Object.keys(o.columns);for(let I of q){let A=o.columns[I];k.push({tsKey:I,value:A})}let P=[];i.with&&(P=Object.entries(i.with).filter(I=>!!I[1]).map(([I,A])=>({tsKey:I,queryConfig:A,relation:o.relations[I]})));let X;if(i.extras){X=typeof i.extras=="function"?i.extras(S,{sql:f}):i.extras;for(let[I,A]of Object.entries(X))k.push({tsKey:I,value:Sn(A,a)})}for(let{tsKey:I,value:A}of k)u.push({dbKey:h(A,_.Aliased)?A.fieldAlias:o.columns[I].name,tsKey:I,field:h(A,z)?ge(A,a):A,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof i.orderBy=="function"?i.orderBy(S,$s()):i.orderBy??[];Array.isArray(L)||(L=[L]),g=L.map(I=>h(I,z)?ge(I,a):qt(I,a)),d=i.limit,p=i.offset;for(let{tsKey:I,queryConfig:A,relation:V}of P){let oe=Ls(r,n,V),we=wt(V.referencedTable),ue=n[we],re=`${a}_${I}`,J=Je(...oe.fields.map((Mo,zo)=>Ke(ge(oe.references[zo],re),ge(Mo,a)))),ke=this.buildRelationalQueryWithoutPK({fullSchema:e,schema:r,tableNamesMap:n,table:e[ue],tableConfig:r[ue],queryConfig:h(V,lt)?A===!0?{limit:1}:{...A,limit:1}:A,tableAlias:re,joinOn:J,nestedQueryRelation:V}),bn=f`${f.identifier(re)}.${f.identifier("data")}`.as(I);b.push({on:f`true`,table:new Q(ke.sql,{},re),alias:re,joinType:"left",lateral:!0}),u.push({dbKey:I,tsKey:I,field:bn,relationTableTsKey:ue,isJson:!0,selection:ke.selection})}}if(u.length===0)throw new _t({message:`No fields selected for table "${o.tsName}" ("${a}")`});let E;if(w=Je(l,w),c){let S=f`json_build_array(${f.join(u.map(({field:P,tsKey:X,isJson:L})=>L?f`${f.identifier(`${a}_${X}`)}.${f.identifier("data")}`:h(P,_.Aliased)?P.sql:P),f`, `)})`;h(c,dr)&&(S=f`coalesce(json_agg(${S}${g.length>0?f` order by ${f.join(g,f`, `)}`:void 0}), '[]'::json)`);let k=[{dbKey:"data",tsKey:"data",field:S.as("data"),isJson:!0,relationTableTsKey:o.tsName,selection:u}];d!==void 0||p!==void 0||g.length>0?(E=this.buildSelectQuery({table:xt(s,a),fields:{},fieldsFlat:[{path:[],field:f.raw("*")}],where:w,limit:d,offset:p,orderBy:g,setOperators:[]}),w=void 0,d=void 0,p=void 0,g=[]):E=xt(s,a),E=this.buildSelectQuery({table:h(E,Se)?E:new Q(E,{},a),fields:{},fieldsFlat:k.map(({field:P})=>({path:[],field:h(P,z)?ge(P,a):P})),joins:b,where:w,limit:d,offset:p,orderBy:g,setOperators:[]})}else E=this.buildSelectQuery({table:xt(s,a),fields:{},fieldsFlat:u.map(({field:S})=>({path:[],field:h(S,z)?ge(S,a):S})),joins:b,where:w,limit:d,offset:p,orderBy:g,setOperators:[]});return{tableTsKey:o.tsName,sql:E,selection:u}}};var Oe=class{static[m]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,e.withList&&(this.withList=e.withList),this.distinct=e.distinct}authToken;setToken(e){return this.authToken=e,this}from(e){let r=!!this.fields,n=e,s;return this.fields?s=this.fields:h(n,Q)?s=Object.fromEntries(Object.keys(n._.selectedFields).map(o=>[o,n[o]])):h(n,Jr)?s=n[H].selectedFields:h(n,_)?s={}:s=Ts(n),new eo({table:n,fields:s,isPartialSelect:r,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}},fa=class extends Kr{static[m]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:r,isPartialSelect:n,session:s,dialect:o,withList:i,distinct:a}){super(),this.config={withList:i,table:e,fields:{...r},distinct:a,setOperators:[]},this.isPartialSelect=n,this.session=s,this.dialect=o,this._={selectedFields:r,config:this.config},this.tableName=De(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{};for(let c of Ge(e))this.usedTables.add(c)}getUsedTables(){return[...this.usedTables]}createJoin(e,r){return(n,s)=>{let o=this.tableName,i=De(n);for(let a of Ge(n))this.usedTables.add(a);if(typeof i=="string"&&this.config.joins?.some(a=>a.alias===i))throw new Error(`Alias "${i}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof o=="string"&&(this.config.fields={[o]:this.config.fields}),typeof i=="string"&&!h(n,_))){let a=h(n,Q)?n._.selectedFields:h(n,he)?n[H].selectedFields:n[v.Symbol.Columns];this.config.fields[i]=a}if(typeof s=="function"&&(s=s(new Proxy(this.config.fields,new U({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:s,table:n,joinType:e,alias:i,lateral:r}),typeof i=="string")switch(e){case"left":{this.joinsNotNullableMap[i]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[i]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[i]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[i]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(e,r){return n=>{let s=typeof n=="function"?n(Im()):n;if(!it(this.getSelectedFields(),s.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:r,rightSelect:s}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new U({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new U({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){let r=e[0](new Proxy(this.config.fields,new U({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(r)?r:[r]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){let r=e[0](new Proxy(this.config.fields,new U({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(r)?r:[r];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{let r=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=r:this.config.orderBy=r}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}for(e,r={}){return this.config.lockingClause={strength:e,config:r},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...r}=this.dialect.sqlToQuery(this.getSQL());return r}as(e){let r=[];if(r.push(...Ge(this.config.table)),this.config.joins)for(let n of this.config.joins)r.push(...Ge(n.table));return new Proxy(new Q(this.getSQL(),this.config.fields,e,!1,[...new Set(r)]),new U({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new U({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}},eo=class extends fa{static[m]="PgSelect";_prepare(e){let{session:r,config:n,dialect:s,joinsNotNullableMap:o,authToken:i,cacheConfig:a,usedTables:c}=this;if(!r)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:l}=n;return ne.startActiveSpan("drizzle.prepareQuery",()=>{let u=ce(l),d=r.prepareQuery(s.sqlToQuery(this.getSQL()),u,e,!0,void 0,{type:"select",tables:[...c]},a);return d.joinsNotNullableMap=o,d.setToken(i)})}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>ne.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken))};js(eo,[Z]);function Zr(t,e){return(r,n,...s)=>{let o=[n,...s].map(i=>({type:t,isAll:e,rightSelect:i}));for(let i of o)if(!it(r.getSelectedFields(),i.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(o)}}var Im=()=>({union:jm,unionAll:Tm,intersect:Rm,intersectAll:Am,except:Om,exceptAll:Pm}),jm=Zr("union",!1),Tm=Zr("union",!0),Rm=Zr("intersect",!1),Am=Zr("intersect",!0),Om=Zr("except",!1),Pm=Zr("except",!0);var Gr=class{static[m]="PgQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=h(e,zt)?e:void 0,this.dialectConfig=h(e,zt)?void 0:e}$with=(e,r)=>{let n=this;return{as:o=>(typeof o=="function"&&(o=o(n)),new Proxy(new ot(o.getSQL(),r??("getSelectedFields"in o?o.getSelectedFields()??{}:{}),e,!0),new U({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...e){let r=this;function n(i){return new Oe({fields:i??void 0,session:void 0,dialect:r.getDialect(),withList:e})}function s(i){return new Oe({fields:i??void 0,session:void 0,dialect:r.getDialect(),distinct:!0})}function o(i,a){return new Oe({fields:a??void 0,session:void 0,dialect:r.getDialect(),distinct:{on:i}})}return{select:n,selectDistinct:s,selectDistinctOn:o}}select(e){return new Oe({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Oe({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(e,r){return new Oe({fields:r??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:e}})}getDialect(){return this.dialect||(this.dialect=new zt(this.dialectConfig)),this.dialect}};function Ge(t){return h(t,Se)?[t[cr]?`${t[cr]}.${t[v.Symbol.BaseName]}`:t[v.Symbol.BaseName]]:h(t,Q)?t._.usedTables??[]:h(t,_)?t.usedTables??[]:[]}var Fn=class extends Z{constructor(e,r,n,s){super(),this.session=r,this.dialect=n,this.config={table:e,withList:s}}static[m]="PgDelete";config;cacheConfig;where(e){return this.config.where=e,this}returning(e=this.config.table[v.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=ce(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...r}=this.dialect.sqlToQuery(this.getSQL());return r}_prepare(e){return ne.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:"delete",tables:Ge(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>ne.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new U({alias:me(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var Qn=class{constructor(e,r,n,s,o){this.table=e,this.session=r,this.dialect=n,this.withList=s,this.overridingSystemValue_=o}static[m]="PgInsertBuilder";authToken;setToken(e){return this.authToken=e,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw new Error("values() must be called with at least one value");let r=e.map(n=>{let s={},o=this.table[v.Symbol.Columns];for(let i of Object.keys(n)){let a=n[i];s[i]=h(a,_)?a:new xe(a,o[i])}return s});return new to(this.table,r,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(e){let r=typeof e=="function"?e(new Gr):e;if(!h(r,_)&&!it(this.table[qr],r._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new to(this.table,r,this.session,this.dialect,this.withList,!0)}},to=class extends Z{constructor(e,r,n,s,o,i,a){super(),this.session=n,this.dialect=s,this.config={table:e,values:r,withList:o,select:i,overridingSystemValue_:a}}static[m]="PgInsert";config;cacheConfig;returning(e=this.config.table[v.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=ce(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=f`do nothing`;else{let r="";r=Array.isArray(e.target)?e.target.map(s=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(s))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));let n=e.where?f` where ${e.where}`:void 0;this.config.onConflict=f`(${f.raw(r)})${n} do nothing`}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let r=e.where?f` where ${e.where}`:void 0,n=e.targetWhere?f` where ${e.targetWhere}`:void 0,s=e.setWhere?f` where ${e.setWhere}`:void 0,o=this.dialect.buildUpdateSet(this.config.table,Lt(this.config.table,e.set)),i="";return i=Array.isArray(e.target)?e.target.map(a=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(a))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=f`(${f.raw(i)})${n} do update set ${o}${r}${s}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...r}=this.dialect.sqlToQuery(this.getSQL());return r}_prepare(e){return ne.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:"insert",tables:Ge(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>ne.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new U({alias:me(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var ro=class extends Z{constructor(e,r,n){super(),this.session=r,this.dialect=n,this.config={view:e}}static[m]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:e,...r}=this.dialect.sqlToQuery(this.getSQL());return r}_prepare(e){return ne.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,!0))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>ne.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken))};var Vn=class{constructor(e,r,n,s){this.table=e,this.session=r,this.dialect=n,this.withList=s}static[m]="PgUpdateBuilder";authToken;setToken(e){return this.authToken=e,this}set(e){return new pa(this.table,Lt(this.table,e),this.session,this.dialect,this.withList).setToken(this.authToken)}},pa=class extends Z{constructor(e,r,n,s,o){super(),this.session=n,this.dialect=s,this.config={set:r,table:e,withList:o,joins:[]},this.tableName=De(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}static[m]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(e){let r=e,n=De(r);return typeof n=="string"&&(this.joinsNotNullableMap[n]=!0),this.config.from=r,this}getTableLikeFields(e){return h(e,Se)?e[v.Symbol.Columns]:h(e,Q)?e._.selectedFields:e[H].selectedFields}createJoin(e){return(r,n)=>{let s=De(r);if(typeof s=="string"&&this.config.joins.some(o=>o.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(typeof n=="function"){let o=this.config.from&&!h(this.config.from,_)?this.getTableLikeFields(this.config.from):void 0;n=n(new Proxy(this.config.table[v.Symbol.Columns],new U({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),o&&new Proxy(o,new U({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:n,table:r,joinType:e,alias:s}),typeof s=="string")switch(e){case"left":{this.joinsNotNullableMap[s]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!0;break}case"inner":{this.joinsNotNullableMap[s]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}returning(e){if(!e&&(e=Object.assign({},this.config.table[v.Symbol.Columns]),this.config.from)){let r=De(this.config.from);if(typeof r=="string"&&this.config.from&&!h(this.config.from,_)){let n=this.getTableLikeFields(this.config.from);e[r]=n}for(let n of this.config.joins){let s=De(n.table);if(typeof s=="string"&&!h(n.table,_)){let o=this.getTableLikeFields(n.table);e[s]=o}}}return this.config.returningFields=e,this.config.returning=ce(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...r}=this.dialect.sqlToQuery(this.getSQL());return r}_prepare(e){let r=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:"insert",tables:Ge(this.config.table)},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>this._prepare().execute(e,this.authToken);getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new U({alias:me(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var no=class t extends _{constructor(e){super(t.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.mapWith(Number),this.session=e.session,this.sql=t.buildCount(e.source,e.filters)}sql;token;static[m]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(e,r){return f`(select count(*) from ${e}${f.raw(" where ").if(r)}${r})`}static buildCount(e,r){return f`select count(*) as count from ${e}${f.raw(" where ").if(r)}${r};`}setToken(e){return this.token=e,this}then(e,r){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,r)}catch(e){return this.then(void 0,e)}finally(e){return this.then(r=>(e?.(),r),r=>{throw e?.(),r})}};var so=class{constructor(e,r,n,s,o,i,a){this.fullSchema=e,this.schema=r,this.tableNamesMap=n,this.table=s,this.tableConfig=o,this.dialect=i,this.session=a}static[m]="PgRelationalQueryBuilder";findMany(e){return new oo(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many")}findFirst(e){return new oo(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}},oo=class extends Z{constructor(e,r,n,s,o,i,a,c,l){super(),this.fullSchema=e,this.schema=r,this.tableNamesMap=n,this.table=s,this.tableConfig=o,this.dialect=i,this.session=a,this.config=c,this.mode=l}static[m]="PgRelationalQuery";_prepare(e){return ne.startActiveSpan("drizzle.prepareQuery",()=>{let{query:r,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,e,!0,(s,o)=>{let i=s.map(a=>Ur(this.schema,this.tableConfig,a,r.selection,o));return this.mode==="first"?i[0]:i})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery(),r=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:r}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return ne.startActiveSpan("drizzle.operation",()=>this._prepare().execute(void 0,this.authToken))}};var io=class extends Z{constructor(e,r,n,s){super(),this.execute=e,this.sql=r,this.query=n,this.mapBatchResult=s}static[m]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(e,r){return r?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}};var Yr=class{constructor(e,r,n){if(this.dialect=e,this.session=r,this._=n?{schema:n.schema,fullSchema:n.fullSchema,tableNamesMap:n.tableNamesMap,session:r}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:r},this.query={},this._.schema)for(let[s,o]of Object.entries(this._.schema))this.query[s]=new so(n.fullSchema,this._.schema,this._.tableNamesMap,n.fullSchema[s],o,e,r);this.$cache={invalidate:async s=>{}}}static[m]="PgDatabase";query;$with=(e,r)=>{let n=this;return{as:o=>(typeof o=="function"&&(o=o(new Gr(n.dialect))),new Proxy(new ot(o.getSQL(),r??("getSelectedFields"in o?o.getSelectedFields()??{}:{}),e,!0),new U({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(e,r){return new no({source:e,filters:r,session:this.session})}$cache;with(...e){let r=this;function n(l){return new Oe({fields:l??void 0,session:r.session,dialect:r.dialect,withList:e})}function s(l){return new Oe({fields:l??void 0,session:r.session,dialect:r.dialect,withList:e,distinct:!0})}function o(l,u){return new Oe({fields:u??void 0,session:r.session,dialect:r.dialect,withList:e,distinct:{on:l}})}function i(l){return new Vn(l,r.session,r.dialect,e)}function a(l){return new Qn(l,r.session,r.dialect,e)}function c(l){return new Fn(l,r.session,r.dialect,e)}return{select:n,selectDistinct:s,selectDistinctOn:o,update:i,insert:a,delete:c}}select(e){return new Oe({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Oe({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(e,r){return new Oe({fields:r??void 0,session:this.session,dialect:this.dialect,distinct:{on:e}})}update(e){return new Vn(e,this.session,this.dialect)}insert(e){return new Qn(e,this.session,this.dialect)}delete(e){return new Fn(e,this.session,this.dialect)}refreshMaterializedView(e){return new ro(e,this.session,this.dialect)}authToken;execute(e){let r=typeof e=="string"?f.raw(e):e.getSQL(),n=this.dialect.sqlToQuery(r),s=this.session.prepareQuery(n,void 0,void 0,!1);return new io(()=>s.execute(void 0,this.authToken),r,n,o=>s.mapResult(o,!0))}transaction(e,r){return this.session.transaction(e,r)}};var ao=class{constructor(e,r,n,s){this.query=e,this.cache=r,this.queryMetadata=n,this.cacheConfig=s,r&&r.strategy()==="all"&&s===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}authToken;getQuery(){return this.query}mapResult(e,r){return e}setToken(e){return this.authToken=e,this}static[m]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(e,r,n){if(this.cache===void 0||h(this.cache,ut)||this.queryMetadata===void 0)try{return await n()}catch(s){throw new Ae(e,r,s)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await n()}catch(s){throw new Ae(e,r,s)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[s]=await Promise.all([n(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return s}catch(s){throw new Ae(e,r,s)}if(!this.cacheConfig)try{return await n()}catch(s){throw new Ae(e,r,s)}if(this.queryMetadata.type==="select"){let s=await this.cache.get(this.cacheConfig.tag??await Qr(e,r),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(s===void 0){let o;try{o=await n()}catch(i){throw new Ae(e,r,i)}return await this.cache.put(this.cacheConfig.tag??await Qr(e,r),o,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),o}return s}try{return await n()}catch(s){throw new Ae(e,r,s)}}},co=class{constructor(e){this.dialect=e}static[m]="PgSession";execute(e,r){return ne.startActiveSpan("drizzle.operation",()=>ne.startActiveSpan("drizzle.prepareQuery",()=>this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1)).setToken(r).execute(void 0,r))}all(e){return this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1).all()}async count(e,r){let n=await this.execute(e,r);return Number(n[0].count)}},lo=class extends Yr{constructor(e,r,n,s=0){super(e,r,n),this.schema=n,this.nestedIndex=s}static[m]="PgTransaction";rollback(){throw new zr}getTransactionConfigSQL(e){let r=[];return e.isolationLevel&&r.push(`isolation level ${e.isolationLevel}`),e.accessMode&&r.push(e.accessMode),typeof e.deferrable=="boolean"&&r.push(e.deferrable?"deferrable":"not deferrable"),f.raw(r.join(" "))}setTransaction(e){return this.session.execute(f`set transaction ${this.getTransactionConfigSQL(e)}`)}};var uo=class extends co{constructor(e,r,n,s={}){super(r),this.client=e,this.schema=n,this.logger=s.logger??new Wr,this.cache=s.cache??new ut}static[m]="PgRemoteSession";logger;cache;prepareQuery(e,r,n,s,o,i,a){return new ma(this.client,e.sql,e.params,e.typings,this.logger,this.cache,i,a,r,s,o)}async transaction(e,r){throw new Error("Transactions are not supported by the Postgres Proxy driver")}},du=class extends lo{static[m]="PgProxyTransaction";async transaction(e){throw new Error("Transactions are not supported by the Postgres Proxy driver")}},ma=class extends ao{constructor(e,r,n,s,o,i,a,c,l,u,d){super({sql:r,params:n},i,a,c),this.client=e,this.queryString=r,this.params=n,this.typings=s,this.logger=o,this.fields=l,this._isResponseInArrayMode=u,this.customResultMapper=d}static[m]="PgProxyPreparedQuery";async execute(e={}){return ne.startActiveSpan("drizzle.execute",async r=>{let n=lr(this.params,e),{fields:s,client:o,queryString:i,joinsNotNullableMap:a,customResultMapper:c,logger:l,typings:u}=this;if(r?.setAttributes({"drizzle.query.text":i,"drizzle.query.params":JSON.stringify(n)}),l.logQuery(i,n),!s&&!c)return ne.startActiveSpan("drizzle.driver.execute",async()=>{let{rows:p}=await this.queryWithCache(i,n,async()=>await o(i,n,"execute",u));return p});let d=await ne.startActiveSpan("drizzle.driver.execute",async()=>{r?.setAttributes({"drizzle.query.text":i,"drizzle.query.params":JSON.stringify(n)});let{rows:p}=await this.queryWithCache(i,n,async()=>await o(i,n,"all",u));return p});return ne.startActiveSpan("drizzle.mapResponse",()=>c?c(d):d.map(p=>En(s,p,a)))})}async all(){}isResponseInArrayMode(){return this._isResponseInArrayMode}};var ha=class extends Yr{static[m]="PgRemoteDatabase"};function fu(t,e={},r=()=>new zt({casing:e.casing})){let n=r(),s;e.logger===!0?s=new Vr:e.logger!==!1&&(s=e.logger);let o;if(e.schema){let c=qs(e.schema,Ms);o={fullSchema:e.schema,schema:c.tables,tableNamesMap:c.tableNamesMap}}let i=new uo(t,n,o,{logger:s,cache:e.cache}),a=new ha(n,i,o);return a.$cache=e.cache,a.$cache&&(a.$cache.invalidate=e.cache?.onMutate),a}var ga="POSTGRES_EXECUTOR";function pu(t,e){return{async transactionBatch(r){let n=await t.fetch(new Request("https://postgres-executor.local/transaction-batch",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({...e,databaseName:e.databaseName??"default",statements:r})}));if(!n.ok)throw new Error(`PostgreSQL transaction batch failed: status=${n.status}`);let s=await n.json();if(!Array.isArray(s.results)||s.results.length!==r.length)throw new Error("PostgreSQL transaction batch returned invalid results.");return s.results},async execute(r){let n=await t.fetch(new Request("https://postgres-executor.local/execute",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({projectId:e.projectId,projectEnvKey:e.projectEnvKey,extensionId:e.extensionId,databaseName:e.databaseName??"default",statement:r})}));if(!n.ok){let s=await n.text();throw new Error(`PostgreSQL executor request failed: status=${n.status} body=${s}`)}return await n.json()}}}function mu(t,e){let r=fu(async(s,o,i,a)=>({rows:(await t.execute({sql:s,params:o,method:i,typings:a})).rows}),e);return Object.assign(r,{async executeAtomicWrites(s){if(!t.transactionBatch)throw new Error("PostgreSQL executor requires transactionBatch for atomic writes.");let o=s.map(i=>({...i.toSQL(),method:"execute"}));await t.transactionBatch(o)}})}var Nm=0xffffffffffffn,Cm=0x0fffn,km=0x3fffffffffffffffn;function hu(t){let e=t instanceof Date?t.getTime():t??Date.now(),r=BigInt(e);if(r<0n||r>Nm)throw new RangeError(`Unsupported UUIDv7 timestamp: ${e}`);let n=Dm(),s=new Uint8Array(10);n.getRandomValues(s);let o=(BigInt(s[0])<<8n|BigInt(s[1]))&Cm,i=$m(s.slice(2))&km,a=r<<80n|0x7n<<76n|o<<64n|0x2n<<62n|i;return qm(a.toString(16).padStart(32,"0"))}function Dm(){let t=globalThis.crypto;if(!t?.getRandomValues)throw new Error("crypto.getRandomValues is required to create IDs.");return t}function $m(t){let e=0n;for(let r of t)e=e<<8n|BigInt(r);return e}function qm(t){return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Ye=1e4,Um=1,fo="prod";var Km=/^\/local\/project\/[^/]+\/env\/[^/]+\/repo\/[^/]+\/(?:main|DEV\d{6,})(?=\/|$)/u;function Bm(t){let e=Fo({pathname:t,search:""});if(e){let r=e.remotePreview||e.remoteProduct?t.slice(0,t.indexOf("/local/project/")):"",n=t.slice(r.length),s=n.match(/^\/local\/project\/[^/]+\/env\/[^/]+\/workspace\/[^/]+/u)[0],o=e.codebaseRuntime?n.slice(s.length).match(/^\/repo\/[^/]+\/codebases\/~[^/]+(?=\/|$)/u)[0]:"";return`${r}${s}${o}`}return t.match(Km)?.[0]}function yu(t){let e=Bm(t),r=e?t.slice(e.length)||"/":t,n=r.match(/^\/api\/project\/([^/]+)\/env\/([^/]+)\/ext\/([^/]+)(?:\/(.*))?$/u);if(n){let i=le(decodeURIComponent(n[1])),a=Y(decodeURIComponent(n[2]??""));return i===null?void 0:{kind:"api",projectId:i,projectEnvKey:a,extensionId:decodeURIComponent(n[3]),remainder:n[4]?`/${n[4]}`:"/"}}let s=r.match(/^\/project\/([^/]+)\/env\/([^/]+)\/ext\/([^/]+)(?:\/(.*))?$/u);if(s){let i=le(decodeURIComponent(s[1])),a=Y(decodeURIComponent(s[2]??""));return i===null?void 0:{kind:"page",projectId:i,projectEnvKey:a,extensionId:decodeURIComponent(s[3]),remainder:s[4]?`/${s[4]}`:"/"}}let o=r.match(/^\/assets\/project\/([^/]+)\/env\/([^/]+)\/ext\/([^/]+)(?:\/(.*))?$/u);if(o){let i=le(decodeURIComponent(o[1])),a=Y(decodeURIComponent(o[2]??""));return i===null?void 0:{kind:"asset",projectId:i,projectEnvKey:a,extensionId:decodeURIComponent(o[3]),remainder:o[4]?`/${o[4]}`:"/"}}return Fm(r)}function le(t){if(typeof t=="number")return gu(t)?t:null;if(typeof t!="string"||!t.trim())return null;let e=Number(t);return gu(e)?e:null}function gu(t){return typeof t=="number"&&Number.isInteger(t)&&t>=Um}function Xr(t){return String(t)}function Y(t){let e=typeof t=="string"?t.trim().toLowerCase():"";return/^[a-z0-9][a-z0-9_-]{0,62}$/u.test(e)?e:fo}function Ut(t){return encodeURIComponent(Y(t))}function Fm(t){let e=t.match(/^\/api\/project\/([^/]+)\/ext\/([^/]+)(?:\/(.*))?$/u);if(e)return ya({kind:"api",encodedProjectId:e[1],encodedExtensionId:e[2],rawRemainder:e[3]});let r=t.match(/^\/project\/([^/]+)\/ext\/([^/]+)(?:\/(.*))?$/u);if(r)return ya({kind:"page",encodedProjectId:r[1],encodedExtensionId:r[2],rawRemainder:r[3]});let n=t.match(/^\/assets\/project\/([^/]+)\/ext\/([^/]+)(?:\/(.*))?$/u);if(n)return ya({kind:"asset",encodedProjectId:n[1],encodedExtensionId:n[2],rawRemainder:n[3]})}function ya(t){let e=le(decodeURIComponent(t.encodedProjectId??""));if(!(e===null||!t.encodedExtensionId))return{kind:t.kind,projectId:e,projectEnvKey:fo,extensionId:decodeURIComponent(t.encodedExtensionId),remainder:t.rawRemainder?`/${t.rawRemainder}`:"/"}}var bu=Symbol.for("@kuafucloud/extension-kit:internal-bindings"),wu=Symbol.for("@kuafucloud/extension-kit:internal-extension-invoker"),Wn=globalThis[bu]??(globalThis[bu]=new WeakMap),po=globalThis[wu]??(globalThis[wu]=new WeakMap);function vu(t,e,r){let n=Object.freeze({...e});po.set(t,s=>{if(!Number.isSafeInteger(n.projectId)||n.projectId<1||typeof n.projectEnvKey!="string"||!/^[a-z0-9][a-z0-9_-]{0,62}$/u.test(n.projectEnvKey)||typeof n.extensionId!="string"||!/^[A-Za-z0-9][A-Za-z0-9_-]{0,159}$/u.test(n.extensionId))throw new Error("\u5185\u90E8 API \u8C03\u7528\u7F3A\u5C11\u6709\u6548\u7684\u670D\u52A1\u7AEF\u8EAB\u4EFD\u3002");return r(n,s)})}function It(t){return[t.projectId,Y(t.projectEnvKey),t.extensionId.trim(),t.databaseName.trim()].join("__")}function en(t){let e=t?.[Hr];return!e||typeof e!="object"||typeof e.idFromName!="function"||typeof e.get!="function"?null:e}function ba(t){return Y(t.projectEnvKey)!==fo?"do":(typeof t.env?.KUAFUCLOUD_DATABASE_BACKEND=="string"?t.env.KUAFUCLOUD_DATABASE_BACKEND.trim().toLowerCase():"")==="postgres"?"postgres":"do"}var Qm="kuafu-sql-executor-v1";async function xu(t){let e=t.env,r=en(e);if(!r)return{body:{code:"runtime.sql_executor_not_configured",message:`Durable Object binding ${Hr} is missing.`},status:503};try{let n=It({...t.resolveScope(),extensionId:t.extensionId,databaseName:"default"}),o=await r.get(r.idFromName(n)).fetch("https://sql-executor.local/execute",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"query",statement:{sql:"SELECT 1 AS ready",method:"get"}})}),i=await o.json().catch(()=>null);if(!o.ok||!i||!("rows"in i))throw new Error(`SQL Executor returned ${o.status}.`);return{body:{data:{status:"healthy",extensionId:t.extensionId,executorContract:Qm}},status:200}}catch(n){return{body:{code:"runtime.sql_executor_unhealthy",message:n instanceof Error?n.message:String(n)},status:503}}}var _u=new Set(["system","im","center","developer","data"]),Vm=new Set(["CLOUDFLARE_API_TOKEN","GITHUB_APP_PRIVATE_KEY","GITHUB_WEBHOOK_SECRET","INTERNAL_API_SIGNING_KEY","PLATFORM_CONTROL_DB","PLATFORM_CREDENTIAL_MASTER_KEY","PLATFORM_DATABASE_BOOTSTRAP_TOKEN","PLATFORM_GATEWAY_INGRESS_TOKEN","PLATFORM_GATEWAY_SERVICE","PLATFORM_GATEWAY_TOKEN","PLATFORM_GATEWAY_TOKEN_PENDING","PLATFORM_MANAGER_SERVICE","PLATFORM_MANAGER_TOKEN","PLATFORM_MANAGER_TOKEN_PENDING","PLATFORM_RUNTIME_BUCKET","PLATFORM_OBJECT_STORAGE_RUNTIME","KUAFUCLOUD_LOCAL_RESOURCE_INVENTORY","PLATFORM_SYSTEM_SERVICE","RELEASE_EXECUTION_SIGNING_KEY","PROJECT_INTERNAL_SIGNING_KEY","RELEASE_DIRECTORY_READ_SIGNING_KEY","RUNTIME_INTERNAL_RPC","MONITOR_PROVIDER_MODE","MONITOR_LOGPUSH_TOKEN","MONITOR_LOGPUSH_TOKEN_VERSION_MARKER","MONITOR_CAPTURE_MODE","MONITOR_RAW_BUCKET","MONITOR_RAW_BUCKET_NAME","MONITOR_DELIVERY_QUEUE","MONITOR_DELIVERY_QUEUE_NAME","MONITOR_RESOURCE_CONFIG","MONITOR_SOURCE_SIGNING_KEY","MONITOR_SOURCE_EVIDENCE","MONITOR_SOURCE_GRANT_ID","MONITOR_TRACE_SAMPLE_RATE","IM_RESOURCE_CONFIG","IM_CAPABILITY_KEY","IM_DIRECTORY_SIGNING_KEY"]);function Wm(t){return!t||typeof t!="object"?{}:Object.freeze(Object.fromEntries(Object.entries(t).filter(([e])=>!Vm.has(e))))}function wa(t,e){return _u.has(t)?e&&typeof e=="object"?e:{}:Wm(e)}function Su(t){return _u.has(t)}function Eu(t,e,r){let n=r.projectId,s=r.projectEnvKey;if(t.allowCrossEnvironment!==!0&&e.projectEnvKey!==s)return{code:"runtime.internal_forbidden",message:"Cross-env internal request is not allowed."};if(!(t.allowCrossProject===!0)&&(n===null||e.projectId!==n))return{code:"runtime.internal_forbidden",message:"Cross-project internal request is not allowed."};let i=e.extensionId,a=t.allowedCallerExtensions??[];if(a.length>0&&!a.includes(i))return{code:"runtime.internal_forbidden",message:`Internal caller extension "${i}" is not allowed.`};let c=e.projectId,l=t.allowedCallerProjects??[];return l.length>0&&!l.includes(c)?{code:"runtime.internal_forbidden",message:`Internal caller project "${c}" is not allowed.`}:null}function ae(t){return Object.freeze({...t})}function be(t,e){return{route:t,handler:e}}function Zn(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r}function K(t,e){var r;return((r=t?._def)===null||r===void 0?void 0:r.typeName)===e}function Jm(t){return"_def"in t}function Hn(t,e){let r=t.ZodType.prototype[e];t.ZodType.prototype[e]=function(...n){let s=r.apply(this,n);return s._def.openapi=this._def.openapi,s}}function wo(t){if(typeof t.ZodType.prototype.openapi<"u")return;t.ZodType.prototype.openapi=function(s,o){var i,a,c,l,u,d;let p=typeof s=="string"?o:s,g=p??{},{param:w}=g,b=Zn(g,["param"]),E=Object.assign(Object.assign({},(i=this._def.openapi)===null||i===void 0?void 0:i._internal),typeof s=="string"?{refId:s}:void 0),S=Object.assign(Object.assign(Object.assign({},(a=this._def.openapi)===null||a===void 0?void 0:a.metadata),b),!((l=(c=this._def.openapi)===null||c===void 0?void 0:c.metadata)===null||l===void 0)&&l.param||w?{param:Object.assign(Object.assign({},(d=(u=this._def.openapi)===null||u===void 0?void 0:u.metadata)===null||d===void 0?void 0:d.param),w)}:void 0),k=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(E).length>0?{_internal:E}:void 0),Object.keys(S).length>0?{metadata:S}:void 0)}));if(K(this,"ZodObject")){let q=this.extend;k.extend=function(...P){var X,L,I,A,V,oe,we;let ue=q.apply(this,P);return ue._def.openapi={_internal:{extendedFrom:!((L=(X=this._def.openapi)===null||X===void 0?void 0:X._internal)===null||L===void 0)&&L.refId?{refId:(A=(I=this._def.openapi)===null||I===void 0?void 0:I._internal)===null||A===void 0?void 0:A.refId,schema:this}:(oe=(V=this._def.openapi)===null||V===void 0?void 0:V._internal)===null||oe===void 0?void 0:oe.extendedFrom},metadata:(we=ue._def.openapi)===null||we===void 0?void 0:we.metadata},ue}}return k},Hn(t,"optional"),Hn(t,"nullable"),Hn(t,"default"),Hn(t,"transform"),Hn(t,"refine");let e=t.ZodObject.prototype.deepPartial;t.ZodObject.prototype.deepPartial=function(){let s=this._def.shape(),o=e.apply(this),i=o._def.shape();return Object.entries(i).forEach(([a,c])=>{var l,u;c._def.openapi=(u=(l=s[a])===null||l===void 0?void 0:l._def)===null||u===void 0?void 0:u.openapi}),o._def.openapi=void 0,o};let r=t.ZodObject.prototype.pick;t.ZodObject.prototype.pick=function(...s){let o=r.apply(this,s);return o._def.openapi=void 0,o};let n=t.ZodObject.prototype.omit;t.ZodObject.prototype.omit=function(...s){let o=n.apply(this,s);return o._def.openapi=void 0,o}}function mo(t,e){if(t==null||e===null||e===void 0)return t===e;if(t===e||t.valueOf()===e.valueOf())return!0;if(Array.isArray(t)&&(!Array.isArray(e)||t.length!==e.length)||!(t instanceof Object)||!(e instanceof Object))return!1;let r=Object.keys(t);return Object.keys(e).every(n=>r.indexOf(n)!==-1)&&r.every(n=>mo(t[n],e[n]))}var va=class{constructor(){this.buckets=new Map}put(e){let r=this.hashCodeOf(e),n=this.buckets.get(r);if(!n){this.buckets.set(r,[e]);return}n.some(o=>mo(o,e))||n.push(e)}contains(e){let r=this.hashCodeOf(e),n=this.buckets.get(r);return n?n.some(s=>mo(s,e)):!1}values(){return[...this.buckets.values()].flat()}stats(){let e=0,r=0,n=0;for(let o of this.buckets.values())e+=1,r+=o.length,o.length>1&&(n+=1);let s=e/r;return{totalBuckets:e,collisions:n,totalValues:r,hashEffectiveness:s}}hashCodeOf(e){let r=0;if(Array.isArray(e)){for(let n=0;n<e.length;n++)r^=this.hashCodeOf(e[n])*n;return r}if(typeof e=="string"){for(let n=0;n<e.length;n++)r^=e.charCodeAt(n)*n;return r}if(typeof e=="number")return e;if(typeof e=="object")for(let[n,s]of Object.entries(e))r^=this.hashCodeOf(n)+this.hashCodeOf(s??"");return r}};function Gn(t){return t===void 0}function Yn(t,e){let r={};return Object.entries(t).forEach(([n,s])=>{r[n]=e(s)}),r}function Zm(t,e){let r={};return Object.entries(t).forEach(([n,s])=>{e.some(o=>o===n)||(r[n]=s)}),r}function tn(t,e){let r={};return Object.entries(t).forEach(([n,s])=>{e(s,n)||(r[n]=s)}),r}function Iu(t){return t.filter(e=>!Gn(e))}var xa=mo;function Gm(t){let e=new va;return t.forEach(r=>e.put(r)),[...e.values()]}function ju(t){return typeof t=="string"}var ho=class{constructor(e){this.parents=e,this._definitions=[]}get definitions(){var e,r;return[...(r=(e=this.parents)===null||e===void 0?void 0:e.flatMap(s=>s.definitions))!==null&&r!==void 0?r:[],...this._definitions]}register(e,r){let n=this.schemaWithRefId(e,r);return this._definitions.push({type:"schema",schema:n}),n}registerParameter(e,r){var n,s,o;let i=this.schemaWithRefId(e,r),a=(n=i._def.openapi)===null||n===void 0?void 0:n.metadata,c=i.openapi(Object.assign(Object.assign({},a),{param:Object.assign(Object.assign({},a?.param),{name:(o=(s=a?.param)===null||s===void 0?void 0:s.name)!==null&&o!==void 0?o:e})}));return this._definitions.push({type:"parameter",schema:c}),c}registerPath(e){this._definitions.push({type:"route",route:e})}registerWebhook(e){this._definitions.push({type:"webhook",webhook:e})}registerComponent(e,r,n){return this._definitions.push({type:"component",componentType:e,name:r,component:n}),{name:r,ref:{$ref:`#/components/${e}/${r}`}}}schemaWithRefId(e,r){return r.openapi(e)}},rn=class{constructor(e){this.message=e}},mr=class extends rn{constructor(e,r){super(e),this.data=r}},nn=class extends rn{constructor(e){super(`Missing parameter data, please specify \`${e.missingField}\` and other OpenAPI parameter props using the \`param\` field of \`ZodSchema.openapi\``),this.data=e}};function Jn(t,e){try{return t()}catch(r){throw r instanceof nn?new nn(Object.assign(Object.assign({},r.data),e)):r}}var _a=class extends rn{constructor(e){super("Unknown zod object type, please specify `type` and other OpenAPI props using `ZodSchema.openapi`."),this.data=e}},ee=class{static getMetadata(e){var r;let n=this.unwrapChained(e),s=e._def.openapi?e._def.openapi:n._def.openapi,o=(r=e.description)!==null&&r!==void 0?r:n.description;return{_internal:s?._internal,metadata:Object.assign({description:o},s?.metadata)}}static getInternalMetadata(e){let r=this.unwrapChained(e),n=e._def.openapi?e._def.openapi:r._def.openapi;return n?._internal}static getParamMetadata(e){var r,n;let s=this.unwrapChained(e),o=e._def.openapi?e._def.openapi:s._def.openapi,i=(r=e.description)!==null&&r!==void 0?r:s.description;return{_internal:o?._internal,metadata:Object.assign(Object.assign({},o?.metadata),{param:Object.assign({description:i},(n=o?.metadata)===null||n===void 0?void 0:n.param)})}}static buildSchemaMetadata(e){return tn(Zm(e,["param"]),Gn)}static buildParameterMetadata(e){return tn(e,Gn)}static applySchemaMetadata(e,r){return tn(Object.assign(Object.assign({},e),this.buildSchemaMetadata(r)),Gn)}static getRefId(e){var r;return(r=this.getInternalMetadata(e))===null||r===void 0?void 0:r.refId}static unwrapChained(e){return this.unwrapUntil(e)}static getDefaultValue(e){let r=this.unwrapUntil(e,"ZodDefault");return r?._def.defaultValue()}static unwrapUntil(e,r){return r&&K(e,r)?e:K(e,"ZodOptional")||K(e,"ZodNullable")||K(e,"ZodBranded")?this.unwrapUntil(e.unwrap(),r):K(e,"ZodDefault")||K(e,"ZodReadonly")?this.unwrapUntil(e._def.innerType,r):K(e,"ZodEffects")?this.unwrapUntil(e._def.schema,r):K(e,"ZodPipeline")?this.unwrapUntil(e._def.in,r):r?void 0:e}static isOptionalSchema(e){return e.isOptional()}},Sa=class{transform(e,r,n){var s,o;let i=e._def.type;return Object.assign(Object.assign({},r("array")),{items:n(i),minItems:(s=e._def.minLength)===null||s===void 0?void 0:s.value,maxItems:(o=e._def.maxLength)===null||o===void 0?void 0:o.value})}},Ea=class{transform(e){return Object.assign(Object.assign({},e("string")),{pattern:"^d+$"})}},Ia=class{transform(e,r,n,s,o){let i=[...e.options.values()],a=i.map(s);return r?{oneOf:n(a,r)}:{oneOf:a,discriminator:this.mapDiscriminator(i,e.discriminator,o)}}mapDiscriminator(e,r,n){if(e.some(o=>ee.getRefId(o)===void 0))return;let s={};return e.forEach(o=>{var i;let a=ee.getRefId(o),c=(i=o.shape)===null||i===void 0?void 0:i[r];if(K(c,"ZodEnum")||K(c,"ZodNativeEnum")){Object.values(c.enum).filter(ju).forEach(d=>{s[d]=n(a)});return}let l=c?._def.value;if(typeof l!="string")throw new Error(`Discriminator ${r} could not be found in one of the values of a discriminated union`);s[l]=n(a)}),{propertyName:r,mapping:s}}},ja=class{transform(e,r){return Object.assign(Object.assign({},r("string")),{enum:e._def.values})}},Ta=class{transform(e,r,n,s){let i={allOf:this.flattenIntersectionTypes(e).map(s)};return r?{anyOf:n([i],r)}:i}flattenIntersectionTypes(e){if(!K(e,"ZodIntersection"))return[e];let r=this.flattenIntersectionTypes(e._def.left),n=this.flattenIntersectionTypes(e._def.right);return[...r,...n]}},Ra=class{transform(e,r){return Object.assign(Object.assign({},r(typeof e._def.value)),{enum:[e._def.value]})}};function Ym(t){let r=Object.keys(t).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),n=r.filter(o=>typeof o=="number").length,s=n===0?"string":n===r.length?"numeric":"mixed";return{values:r,type:s}}var Aa=class{transform(e,r){let{type:n,values:s}=Ym(e._def.values);if(n==="mixed")throw new rn("Enum has mixed string and number values, please specify the OpenAPI type manually");return Object.assign(Object.assign({},r(n==="numeric"?"integer":"string")),{enum:s})}},Oa=class{transform(e,r,n){return Object.assign(Object.assign({},r(e.isInt?"integer":"number")),n(e._def.checks))}},Pa=class{transform(e,r,n,s){var o;let i=(o=ee.getInternalMetadata(e))===null||o===void 0?void 0:o.extendedFrom,a=this.requiredKeysOf(e),c=Yn(e._def.shape(),s);if(!i)return Object.assign(Object.assign(Object.assign(Object.assign({},n("object")),{properties:c,default:r}),a.length>0?{required:a}:{}),this.generateAdditionalProperties(e,s));let l=i.schema;s(l);let u=this.requiredKeysOf(l),d=Yn(l?._def.shape(),s),p=Object.fromEntries(Object.entries(c).filter(([b,E])=>!xa(d[b],E))),g=a.filter(b=>!u.includes(b)),w=Object.assign(Object.assign(Object.assign(Object.assign({},n("object")),{default:r,properties:p}),g.length>0?{required:g}:{}),this.generateAdditionalProperties(e,s));return{allOf:[{$ref:`#/components/schemas/${i.refId}`},w]}}generateAdditionalProperties(e,r){let n=e._def.unknownKeys,s=e._def.catchall;return K(s,"ZodNever")?n==="strict"?{additionalProperties:!1}:{}:{additionalProperties:r(s)}}requiredKeysOf(e){return Object.entries(e._def.shape()).filter(([r,n])=>!ee.isOptionalSchema(n)).map(([r,n])=>r)}},Na=class{transform(e,r,n){let s=e._def.valueType,o=e._def.keyType,i=n(s);if(K(o,"ZodEnum")||K(o,"ZodNativeEnum")){let c=Object.values(o.enum).filter(ju).reduce((l,u)=>Object.assign(Object.assign({},l),{[u]:i}),{});return Object.assign(Object.assign({},r("object")),{properties:c})}return Object.assign(Object.assign({},r("object")),{additionalProperties:i})}},Ca=class{transform(e,r){var n,s,o;let i=this.getZodStringCheck(e,"regex"),a=(n=this.getZodStringCheck(e,"length"))===null||n===void 0?void 0:n.value,c=Number.isFinite(e.minLength)&&(s=e.minLength)!==null&&s!==void 0?s:void 0,l=Number.isFinite(e.maxLength)&&(o=e.maxLength)!==null&&o!==void 0?o:void 0;return Object.assign(Object.assign({},r("string")),{minLength:a??c,maxLength:a??l,format:this.mapStringFormat(e),pattern:i?.regex.source})}mapStringFormat(e){if(e.isUUID)return"uuid";if(e.isEmail)return"email";if(e.isURL)return"uri";if(e.isDate)return"date";if(e.isDatetime)return"date-time";if(e.isCUID)return"cuid";if(e.isCUID2)return"cuid2";if(e.isULID)return"ulid";if(e.isIP)return"ip";if(e.isEmoji)return"emoji"}getZodStringCheck(e,r){return e._def.checks.find(n=>n.kind===r)}},ka=class{constructor(e){this.versionSpecifics=e}transform(e,r,n){let{items:s}=e._def,o=s.map(n);return Object.assign(Object.assign({},r("array")),this.versionSpecifics.mapTupleItems(o))}},Da=class{transform(e,r,n){let o=this.flattenUnionTypes(e).map(i=>{let a=this.unwrapNullable(i);return n(a)});return{anyOf:r(o)}}flattenUnionTypes(e){return K(e,"ZodUnion")?e._def.options.flatMap(n=>this.flattenUnionTypes(n)):[e]}unwrapNullable(e){return K(e,"ZodNullable")?this.unwrapNullable(e.unwrap()):e}},$a=class{constructor(e){this.versionSpecifics=e,this.objectTransformer=new Pa,this.stringTransformer=new Ca,this.numberTransformer=new Oa,this.bigIntTransformer=new Ea,this.literalTransformer=new Ra,this.enumTransformer=new ja,this.nativeEnumTransformer=new Aa,this.arrayTransformer=new Sa,this.unionTransformer=new Da,this.discriminatedUnionTransformer=new Ia,this.intersectionTransformer=new Ta,this.recordTransformer=new Na,this.tupleTransformer=new ka(e)}transform(e,r,n,s,o){if(K(e,"ZodNull"))return this.versionSpecifics.nullType;if(K(e,"ZodUnknown")||K(e,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,r);if(K(e,"ZodObject"))return this.objectTransformer.transform(e,o,a=>this.versionSpecifics.mapNullableType(a,r),n);let i=this.transformSchemaWithoutDefault(e,r,n,s);return Object.assign(Object.assign({},i),{default:o})}transformSchemaWithoutDefault(e,r,n,s){if(K(e,"ZodUnknown")||K(e,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,r);if(K(e,"ZodString"))return this.stringTransformer.transform(e,i=>this.versionSpecifics.mapNullableType(i,r));if(K(e,"ZodNumber"))return this.numberTransformer.transform(e,i=>this.versionSpecifics.mapNullableType(i,r),i=>this.versionSpecifics.getNumberChecks(i));if(K(e,"ZodBigInt"))return this.bigIntTransformer.transform(i=>this.versionSpecifics.mapNullableType(i,r));if(K(e,"ZodBoolean"))return this.versionSpecifics.mapNullableType("boolean",r);if(K(e,"ZodLiteral"))return this.literalTransformer.transform(e,i=>this.versionSpecifics.mapNullableType(i,r));if(K(e,"ZodEnum"))return this.enumTransformer.transform(e,i=>this.versionSpecifics.mapNullableType(i,r));if(K(e,"ZodNativeEnum"))return this.nativeEnumTransformer.transform(e,i=>this.versionSpecifics.mapNullableType(i,r));if(K(e,"ZodArray"))return this.arrayTransformer.transform(e,i=>this.versionSpecifics.mapNullableType(i,r),n);if(K(e,"ZodTuple"))return this.tupleTransformer.transform(e,i=>this.versionSpecifics.mapNullableType(i,r),n);if(K(e,"ZodUnion"))return this.unionTransformer.transform(e,i=>this.versionSpecifics.mapNullableOfArray(i,r),n);if(K(e,"ZodDiscriminatedUnion"))return this.discriminatedUnionTransformer.transform(e,r,i=>this.versionSpecifics.mapNullableOfArray(i,r),n,s);if(K(e,"ZodIntersection"))return this.intersectionTransformer.transform(e,r,i=>this.versionSpecifics.mapNullableOfArray(i,r),n);if(K(e,"ZodRecord"))return this.recordTransformer.transform(e,i=>this.versionSpecifics.mapNullableType(i,r),n);if(K(e,"ZodDate"))return this.versionSpecifics.mapNullableType("string",r);let o=ee.getRefId(e);throw new _a({currentSchema:e._def,schemaName:o})}},go=class{constructor(e,r){this.definitions=e,this.versionSpecifics=r,this.schemaRefs={},this.paramRefs={},this.pathRefs={},this.rawComponents=[],this.openApiTransformer=new $a(r),this.sortDefinitions()}generateDocumentData(){return this.definitions.forEach(e=>this.generateSingle(e)),{components:this.buildComponents(),paths:this.pathRefs}}generateComponents(){return this.definitions.forEach(e=>this.generateSingle(e)),{components:this.buildComponents()}}buildComponents(){var e,r;let n={};return this.rawComponents.forEach(({componentType:s,name:o,component:i})=>{var a;(a=n[s])!==null&&a!==void 0||(n[s]={}),n[s][o]=i}),Object.assign(Object.assign({},n),{schemas:Object.assign(Object.assign({},(e=n.schemas)!==null&&e!==void 0?e:{}),this.schemaRefs),parameters:Object.assign(Object.assign({},(r=n.parameters)!==null&&r!==void 0?r:{}),this.paramRefs)})}sortDefinitions(){let e=["schema","parameter","component","route"];this.definitions.sort((r,n)=>{if(!("type"in r))return"type"in n?-1:0;if(!("type"in n))return 1;let s=e.findIndex(i=>i===r.type),o=e.findIndex(i=>i===n.type);return s-o})}generateSingle(e){if(!("type"in e)){this.generateSchemaWithRef(e);return}switch(e.type){case"parameter":this.generateParameterDefinition(e.schema);return;case"schema":this.generateSchemaWithRef(e.schema);return;case"route":this.generateSingleRoute(e.route);return;case"component":this.rawComponents.push(e);return}}generateParameterDefinition(e){let r=ee.getRefId(e),n=this.generateParameter(e);return r&&(this.paramRefs[r]=n),n}getParameterRef(e,r){var n,s,o,i,a;let c=(n=e?.metadata)===null||n===void 0?void 0:n.param,l=!((s=e?._internal)===null||s===void 0)&&s.refId?this.paramRefs[(o=e._internal)===null||o===void 0?void 0:o.refId]:void 0;if(!(!(!((i=e?._internal)===null||i===void 0)&&i.refId)||!l)){if(c&&l.in!==c.in||r?.in&&l.in!==r.in)throw new mr(`Conflicting location for parameter ${l.name}`,{key:"in",values:Iu([l.in,r?.in,c?.in])});if(c&&l.name!==c.name||r?.name&&l.name!==r?.name)throw new mr("Conflicting names for parameter",{key:"name",values:Iu([l.name,r?.name,c?.name])});return{$ref:`#/components/parameters/${(a=e._internal)===null||a===void 0?void 0:a.refId}`}}}generateInlineParameters(e,r){var n;let s=ee.getMetadata(e),o=(n=s?.metadata)===null||n===void 0?void 0:n.param,i=this.getParameterRef(s,{in:r});if(i)return[i];if(K(e,"ZodObject")){let a=e._def.shape();return Object.entries(a).map(([l,u])=>{var d,p;let g=ee.getMetadata(u),w=this.getParameterRef(g,{in:r,name:l});if(w)return w;let b=(d=g?.metadata)===null||d===void 0?void 0:d.param;if(b?.name&&b.name!==l)throw new mr("Conflicting names for parameter",{key:"name",values:[l,b.name]});if(b?.in&&b.in!==r)throw new mr(`Conflicting location for parameter ${(p=b.name)!==null&&p!==void 0?p:l}`,{key:"in",values:[r,b.in]});return this.generateParameter(u.openapi({param:{name:l,in:r}}))})}if(o?.in&&o.in!==r)throw new mr(`Conflicting location for parameter ${o.name}`,{key:"in",values:[r,o.in]});return[this.generateParameter(e.openapi({param:{in:r}}))]}generateSimpleParameter(e){var r;let n=ee.getParamMetadata(e),s=(r=n?.metadata)===null||r===void 0?void 0:r.param,o=!ee.isOptionalSchema(e)&&!e.isNullable(),i=this.generateSchemaWithRef(e);return Object.assign({schema:i,required:o},s?ee.buildParameterMetadata(s):{})}generateParameter(e){var r;let n=ee.getMetadata(e),s=(r=n?.metadata)===null||r===void 0?void 0:r.param,o=s?.name,i=s?.in;if(!o)throw new nn({missingField:"name"});if(!i)throw new nn({missingField:"in",paramName:o});let a=this.generateSimpleParameter(e);return Object.assign(Object.assign({},a),{in:i,name:o})}generateSchemaWithMetadata(e){var r;let n=ee.unwrapChained(e),s=ee.getMetadata(e),o=ee.getDefaultValue(e),i=!((r=s?.metadata)===null||r===void 0)&&r.type?{type:s?.metadata.type}:this.toOpenAPISchema(n,e.isNullable(),o);return s?.metadata?ee.applySchemaMetadata(i,s.metadata):tn(i,Gn)}constructReferencedOpenAPISchema(e){var r;let n=ee.getMetadata(e),s=ee.unwrapChained(e),o=ee.getDefaultValue(e),i=e.isNullable();return!((r=n?.metadata)===null||r===void 0)&&r.type?this.versionSpecifics.mapNullableType(n.metadata.type,i):this.toOpenAPISchema(s,i,o)}generateSimpleSchema(e){var r;let n=ee.getMetadata(e),s=ee.getRefId(e);if(!s||!this.schemaRefs[s])return this.generateSchemaWithMetadata(e);let o=this.schemaRefs[s],i={$ref:this.generateSchemaRef(s)},a=tn(ee.buildSchemaMetadata((r=n?.metadata)!==null&&r!==void 0?r:{}),(u,d)=>u===void 0||xa(u,o[d]));if(a.type)return{allOf:[i,a]};let c=tn(this.constructReferencedOpenAPISchema(e),(u,d)=>u===void 0||xa(u,o[d])),l=ee.applySchemaMetadata(c,a);return Object.keys(l).length>0?{allOf:[i,l]}:i}generateSchemaWithRef(e){let r=ee.getRefId(e),n=this.generateSimpleSchema(e);return r&&this.schemaRefs[r]===void 0?(this.schemaRefs[r]=n,{$ref:this.generateSchemaRef(r)}):n}generateSchemaRef(e){return`#/components/schemas/${e}`}getRequestBody(e){if(!e)return;let{content:r}=e,n=Zn(e,["content"]),s=this.getBodyContent(r);return Object.assign(Object.assign({},n),{content:s})}getParameters(e){if(!e)return[];let{headers:r}=e,n=this.cleanParameter(e.query),s=this.cleanParameter(e.params),o=this.cleanParameter(e.cookies),i=Jn(()=>n?this.generateInlineParameters(n,"query"):[],{location:"query"}),a=Jn(()=>s?this.generateInlineParameters(s,"path"):[],{location:"path"}),c=Jn(()=>o?this.generateInlineParameters(o,"cookie"):[],{location:"cookie"}),l=Jn(()=>{if(Array.isArray(r))return r.flatMap(d=>this.generateInlineParameters(d,"header"));let u=this.cleanParameter(r);return u?this.generateInlineParameters(u,"header"):[]},{location:"header"});return[...a,...i,...l,...c]}cleanParameter(e){if(e)return K(e,"ZodEffects")?this.cleanParameter(e._def.schema):e}generatePath(e){let{method:r,path:n,request:s,responses:o}=e,i=Zn(e,["method","path","request","responses"]),a=Yn(o,d=>this.getResponse(d)),c=Jn(()=>this.getParameters(s),{route:`${r} ${n}`}),l=this.getRequestBody(s?.body);return{[r]:Object.assign(Object.assign(Object.assign(Object.assign({},i),c.length>0?{parameters:[...i.parameters||[],...c]}:{}),l?{requestBody:l}:{}),{responses:a})}}generateSingleRoute(e){let r=this.generatePath(e);return this.pathRefs[e.path]=Object.assign(Object.assign({},this.pathRefs[e.path]),r),r}getResponse(e){if(this.isReferenceObject(e))return e;let{content:r,headers:n}=e,s=Zn(e,["content","headers"]),o=r?{content:this.getBodyContent(r)}:{};if(!n)return Object.assign(Object.assign({},s),o);let i=K(n,"ZodObject")?this.getResponseHeaders(n):n;return Object.assign(Object.assign(Object.assign({},s),{headers:i}),o)}isReferenceObject(e){return"$ref"in e}getResponseHeaders(e){let r=e._def.shape();return Yn(r,s=>this.generateSimpleParameter(s))}getBodyContent(e){return Yn(e,r=>{if(!r||!Jm(r.schema))return r;let{schema:n}=r,s=Zn(r,["schema"]),o=this.generateSchemaWithRef(n);return Object.assign({schema:o},s)})}toOpenAPISchema(e,r,n){return this.openApiTransformer.transform(e,r,s=>this.generateSchemaWithRef(s),s=>this.generateSchemaRef(s),n)}},qa=class{get nullType(){return{nullable:!0}}mapNullableOfArray(e,r){return r?[...e,this.nullType]:e}mapNullableType(e,r){return Object.assign(Object.assign({},e?{type:e}:void 0),r?this.nullType:void 0)}mapTupleItems(e){let r=Gm(e);return{items:r.length===1?r[0]:{anyOf:r},minItems:e.length,maxItems:e.length}}getNumberChecks(e){return Object.assign({},...e.map(r=>{switch(r.kind){case"min":return r.inclusive?{minimum:Number(r.value)}:{minimum:Number(r.value),exclusiveMinimum:!0};case"max":return r.inclusive?{maximum:Number(r.value)}:{maximum:Number(r.value),exclusiveMaximum:!0};default:return{}}}))}},yo=class{constructor(e){let r=new qa;this.generator=new go(e,r)}generateDocument(e){let r=this.generator.generateDocumentData();return Object.assign(Object.assign({},e),r)}generateComponents(){return this.generator.generateComponents()}},La=class{get nullType(){return{type:"null"}}mapNullableOfArray(e,r){return r?[...e,this.nullType]:e}mapNullableType(e,r){return e?r?{type:Array.isArray(e)?[...e,"null"]:[e,"null"]}:{type:e}:{}}mapTupleItems(e){return{prefixItems:e}}getNumberChecks(e){return Object.assign({},...e.map(r=>{switch(r.kind){case"min":return r.inclusive?{minimum:Number(r.value)}:{exclusiveMinimum:Number(r.value)};case"max":return r.inclusive?{maximum:Number(r.value)}:{exclusiveMaximum:Number(r.value)};default:return{}}}))}};function Xm(t){return"type"in t&&t.type==="webhook"}var bo=class{constructor(e){this.definitions=e,this.webhookRefs={};let r=new La;this.generator=new go(this.definitions,r)}generateDocument(e){let r=this.generator.generateDocumentData();return this.definitions.filter(Xm).forEach(n=>this.generateSingleWebhook(n.webhook)),Object.assign(Object.assign(Object.assign({},e),r),{webhooks:this.webhookRefs})}generateComponents(){return this.generator.generateComponents()}generateSingleWebhook(e){let r=this.generator.generatePath(e);return this.webhookRefs[e.path]=Object.assign(Object.assign({},this.webhookRefs[e.path]),r),r}};var za=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Tu=t=>{let{groups:e,path:r}=eh(t),n=za(r);return th(n,e)},eh=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let s=`@${n}`;return e.push([s,r]),s}),{groups:e,path:t}},th=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let s=t.length-1;s>=0;s--)if(t[s].includes(n)){t[s]=t[s].replace(n,e[r][1]);break}}return t},vo={},Ru=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return vo[n]||(r[2]?vo[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:vo[n]=[t,r[1],!0]),vo[n]}return null},sn=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},rh=t=>sn(t,decodeURI),Ua=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let s=e.charCodeAt(n);if(s===37){let o=e.indexOf("?",n),i=e.indexOf("#",n),a=o===-1?i===-1?void 0:i:i===-1?o:Math.min(o,i),c=e.slice(r,a);return rh(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(s===63||s===35)break}return e.slice(r,n)};var Au=t=>{let e=Ua(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},Fe=(t,e,...r)=>(r.length&&(e=Fe(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),xo=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(s=>{if(s!==""&&!/\:/.test(s))n+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){r.length===0&&n===""?r.push("/"):r.push(n);let o=s.replace("?","");n+="/"+o,r.push(n)}else n+="/"+s}),r.filter((s,o,i)=>i.indexOf(s)===o)},Ma=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?sn(t,Xn):t):t,Ou=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let a=t.charCodeAt(i+e.length+1);if(a===61){let c=i+e.length+2,l=t.indexOf("&",c);return Ma(t.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=t.indexOf(`&${e}`,i+1)}if(n=/[%+]/.test(t),!n)return}let s={};n??=/[%+]/.test(t);let o=t.indexOf("?",8);for(;o!==-1;){let i=t.indexOf("&",o+1),a=t.indexOf("=",o);a>i&&i!==-1&&(a=-1);let c=t.slice(o+1,a===-1?i===-1?void 0:i:a);if(n&&(c=Ma(c)),o=i,c==="")continue;let l;a===-1?l="":(l=t.slice(a+1,i===-1?void 0:i),n&&(l=Ma(l))),r?(s[c]&&Array.isArray(s[c])||(s[c]=[]),s[c].push(l)):s[c]??=l}return e?s[e]:s},Pu=Ou,Nu=(t,e)=>Ou(t,e,!0),Xn=decodeURIComponent;var nh=/^[\w!#$%&'*.^`|~+-]+$/,sh=/^[ !#-:<-[\]-~]*$/,Cu=t=>{let e=0,r=t.length;for(;e<r;){let n=t.charCodeAt(e);if(n!==32&&n!==9)break;e++}for(;r>e;){let n=t.charCodeAt(r-1);if(n!==32&&n!==9)break;r--}return e===0&&r===t.length?t:t.slice(e,r)},Ka=(t,e)=>{if(e&&t.indexOf(e)===-1)return{};let r=t.split(";"),n=Object.create(null);for(let s of r){let o=s.indexOf("=");if(o===-1)continue;let i=Cu(s.substring(0,o));if(e&&e!==i||!nh.test(i)||i in n)continue;let a=Cu(s.substring(o+1));if(a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),sh.test(a)&&(n[i]=a.indexOf("%")!==-1?sn(a,Xn):a,e))break}return n};var ku=(t,e,r)=>{let n=t.req.raw.headers.get("Cookie");if(typeof e=="string"){if(!n)return;let o=e;return r==="secure"?o="__Secure-"+e:r==="host"&&(o="__Host-"+e),Ka(n,o)[o]}return n?Ka(n):{}};var Kt=class extends Error{res;status;constructor(t=500,e){super(e?.message,{cause:e?.cause}),this.res=e?.res,this.status=t}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};var Du=(t,e)=>new Response(t,{headers:{"Content-Type":e}}).formData();var oh=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,ih=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,ah=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Ba=(t,e)=>async(r,n)=>{let s={},o=r.req.header("Content-Type");switch(t){case"json":if(!o||!oh.test(o))break;try{s=await r.req.json()}catch{let a="Malformed JSON in request body";throw new Kt(400,{message:a})}break;case"form":{if(!o||!(ih.test(o)||ah.test(o)))break;let a;if(r.req.bodyCache.formData)a=await r.req.bodyCache.formData;else try{let l=await r.req.arrayBuffer();a=await Du(l,o),r.req.bodyCache.formData=a}catch(l){let u="Malformed FormData request.";throw u+=l instanceof Error?` ${l.message}`:` ${String(l)}`,new Kt(400,{message:u})}let c=Object.create(null);a.forEach((l,u)=>{u.endsWith("[]")?(c[u]??=[]).push(l):Array.isArray(c[u])?c[u].push(l):Object.hasOwn(c,u)?c[u]=[c[u],l]:c[u]=l}),s=c;break}case"query":s=Object.fromEntries(Object.entries(r.req.queries()).map(([a,c])=>c.length===1?[a,c[0]]:[a,c]));break;case"param":s=r.req.param();break;case"header":s=r.req.header();break;case"cookie":s=ku(r);break}let i=await e(s,r);return i instanceof Response?i:(r.req.addValidatedData(t,i),await n())};var hr=(t,e,r)=>Ba(t,async(n,s)=>{let o=await e.safeParseAsync(n);if(r){let i=await r({data:n,...o,target:t},s);if(i){if(i instanceof Response)return i;if("response"in i)return i.response}}return o.success?o.data:s.json(o,400)});var Fa=(t,e,r)=>(n,s)=>{let o=-1;return i(0);async function i(a){if(a<=o)throw new Error("next() called multiple times");o=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],n.req.routeIndex=a):u=a===t.length&&s||void 0,u)try{c=await u(n,()=>i(a+1))}catch(d){if(d instanceof Error&&e)n.error=d,c=await e(d,n),l=!0;else throw d}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var $u=Symbol();var qu=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,o=(t instanceof _o?t.raw.headers:t.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?ch(t,{all:r,dot:n}):{}};async function ch(t,e){let r=await t.formData();return r?lh(r,e):{}}function lh(t,e){let r=Object.create(null);return t.forEach((n,s)=>{e.all||s.endsWith("[]")?uh(r,s,n):r[s]=n}),e.dot&&Object.entries(r).forEach(([n,s])=>{n.includes(".")&&(dh(r,n,s),delete r[n])}),r}var uh=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},dh=(t,e,r)=>{if(/(?:^|\.)__proto__\./.test(e))return;let n=t,s=e.split(".");s.forEach((o,i)=>{i===s.length-1?n[o]=r:((!n[o]||typeof n[o]!="object"||Array.isArray(n[o])||n[o]instanceof File)&&(n[o]=Object.create(null)),n=n[o])})};var Lu=t=>sn(t,Xn),_o=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r,this.#t={}}param(t){return t?this.#r(t):this.#o()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#s(e);return r&&/\%/.test(r)?Lu(r):r}#o(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#s(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?Lu(n):n)}return t}#s(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Pu(this.url,t)}queries(t){return Nu(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return qu(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let s=Object.keys(e)[0];return s?e[s].then(o=>(s==="json"&&(o=JSON.stringify(o)),new Response(o)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[$u](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Mu={Stringify:1,BeforeStream:2,Stream:3},fh=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var Qa=async(t,e,r,n,s)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let o=t.callbacks;if(!o?.length)return Promise.resolve(t);s?s[0]+=t:s=[t];let i=Promise.all(o.map(a=>a({phase:e,buffer:s,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>Qa(c,e,!1,n,s))).then(()=>s[0]));return r?fh(await i,o):i};var ph="text/plain; charset=UTF-8",Va=(t,e)=>({"Content-Type":t,...e}),es=(t,e)=>new Response(t,e),Wa=class{#t;#e;env={};#r;finalized=!1;error;#o;#s;#n;#u;#c;#l;#a;#d;#f;constructor(t,e){this.#t=t,e&&(this.#s=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#f=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new _o(this.#t,this.#f,this.#d),this.#e}get event(){if(this.#s&&"respondWith"in this.#s)return this.#s;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#s)return this.#s;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=es(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=es(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let s of n)t.headers.append("set-cookie",s)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#c=t};header=(t,e,r)=>{this.finalized&&(this.#n=es(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#o=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let o=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,a]of o)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[o,i]of Object.entries(r))if(typeof i=="string")n.set(o,i);else{n.delete(o);for(let a of i)n.append(o,a)}let s=typeof e=="number"?e:e?.status??this.#o;return es(t,{status:s,headers:n})}newResponse=(...t)=>this.#i(...t);body=(t,e,r)=>this.#i(t,e,r);text=(t,e,r)=>!this.#a&&!this.#o&&!e&&!r&&!this.finalized?new Response(t):this.#i(t,e,Va(ph,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,Va("application/json",r));html=(t,e,r)=>{let n=s=>this.#i(s,e,Va("text/html; charset=UTF-8",r));return typeof t=="object"?Qa(t,Mu.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>es(),this.#l(this))};var se="ALL",zu="all",Uu=["get","post","put","delete","options","patch"],So="Can not add a route since the matcher is already built.",Eo=class extends Error{};var Ku="__COMPOSED_HANDLER";var mh=t=>t.text("404 Not Found",404),Bu=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},Fu=class Qu{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Uu,zu].forEach(o=>{this[o]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#o(o,this.#t,i),a.forEach(c=>{this.#o(o,this.#t,c)}),this)}),this.on=(o,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[o].flat())a.map(u=>{this.#o(l.toUpperCase(),this.#t,u)})}return this},this.use=(o,...i)=>(typeof o=="string"?this.#t=o:(this.#t="*",i.unshift(o)),i.forEach(a=>{this.#o(se,this.#t,a)}),this);let{strict:n,...s}=e;Object.assign(this,s),this.getPath=n??!0?e.getPath??Ua:Au}#e(){let e=new Qu({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=mh;errorHandler=Bu;route(e,r){let n=this.basePath(e);return r.routes.map(s=>{let o;r.errorHandler===Bu?o=s.handler:(o=async(i,a)=>(await Fa([],r.errorHandler)(i,()=>s.handler(i,a))).res,o[Ku]=s.handler),n.#o(s.method,s.path,o,s.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=Fe(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,r,n){let s,o;n&&(typeof n=="function"?o=n:(o=n.optionHandler,n.replaceRequest===!1?s=c=>c:s=n.replaceRequest));let i=o?c=>{let l=o(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};s||=(()=>{let c=Fe(this._basePath,e),l=c==="/"?0:c.length;return u=>{let d=new URL(u.url);return d.pathname=this.getPath(u).slice(l)||"/",new Request(d,u)}})();let a=async(c,l)=>{let u=await r(s(c.req.raw),...i(c));if(u)return u;await l()};return this.#o(se,Fe(e,"*"),a),this}#o(e,r,n,s){e=e.toUpperCase(),r=Fe(this._basePath,r);let o={basePath:s!==void 0?Fe(this._basePath,s):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,o]),this.routes.push(o)}#s(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#n(e,r,n,s){if(s==="HEAD")return(async()=>new Response(null,await this.#n(e,r,n,"GET")))();let o=this.getPath(e,{env:n}),i=this.router.match(s,o),a=new Wa(e,{path:o,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#s(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#s(u,a)):l??this.#r(a)}let c=Fa(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#s(l,a)}})()}fetch=(e,...r)=>this.#n(e,r[1],r[0],e.method);request=(e,r,n,s)=>e instanceof Request?this.fetch(r?new Request(e,r):e,n,s):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${Fe("/",e)}`,r),n,s));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var Io=[];function Ha(t,e){let r=this.buildAllMatchers(),n=((s,o)=>{let i=r[s]||r[se],a=i[2][o];if(a)return a;let c=o.match(i[0]);if(!c)return[[],Io];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(t,e)}var jo="[^/]+",ts=".*",rs="(?:|/.*)",gr=Symbol(),hh=new Set(".\\+*[^]$()");function gh(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===ts||t===rs?1:e===ts||e===rs?-1:t===jo?1:e===jo?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Vu=class Ja{#t;#e;#r=Object.create(null);insert(e,r,n,s,o){if(e.length===0){if(this.#t!==void 0)throw gr;if(o)return;this.#t=r;return}let[i,...a]=e,c=i==="*"?a.length===0?["","",ts]:["","",jo]:i==="/*"?["","",rs]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||jo;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw gr;if(l=this.#r[d],!l){if(Object.keys(this.#r).some(p=>p!==ts&&p!==rs))throw gr;if(o)return;l=this.#r[d]=new Ja,u!==""&&(l.#e=s.varIndex++)}!o&&u!==""&&n.push([u,l.#e])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==ts&&u!==rs))throw gr;if(o)return;l=this.#r[i]=new Ja}l.insert(a,r,n,s,o)}buildRegExpStr(){let r=Object.keys(this.#r).sort(gh).map(n=>{let s=this.#r[n];return(typeof s.#e=="number"?`(${n})@${s.#e}`:hh.has(n)?`\\${n}`:n)+s.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var Wu=class{#t={varIndex:0};#e=new Vu;insert(t,e,r){let n=[],s=[];for(let i=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return s[i]=[l,c],i++,a=!0,l}),!a)break}let o=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=s.length-1;i>=0;i--){let[a]=s[i];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(a)!==-1){o[c]=o[c].replace(a,s[i][1]);break}}return this.#e.insert(o,e,n,this.#t,r),n}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,o,i)=>o!==void 0?(r[++e]=Number(o),"$()"):(i!==void 0&&(n[Number(i)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var yh=[/^$/,[],Object.create(null)],Hu=Object.create(null);function Ju(t){return Hu[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function bh(){Hu=Object.create(null)}function wh(t){let e=new Wu,r=[];if(t.length===0)return yh;let n=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[d,p])=>l?1:d?-1:u.length-p.length),s=Object.create(null);for(let l=0,u=-1,d=n.length;l<d;l++){let[p,g,w]=n[l];p?s[g]=[w.map(([E])=>[E,Object.create(null)]),Io]:u++;let b;try{b=e.insert(g,u,p)}catch(E){throw E===gr?new Eo(g):E}p||(r[u]=w.map(([E,S])=>{let k=Object.create(null);for(S-=1;S>=0;S--){let[q,P]=b[S];k[q]=P}return[E,k]}))}let[o,i,a]=e.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let d=0,p=r[l].length;d<p;d++){let g=r[l][d]?.[1];if(!g)continue;let w=Object.keys(g);for(let b=0,E=w.length;b<E;b++)g[w[b]]=a[g[w[b]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[o,c,s]}function on(t,e){if(t){for(let r of Object.keys(t).sort((n,s)=>s.length-n.length))if(Ju(r).test(e))return[...t[r]]}}var To=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[se]:Object.create(null)},this.#e={[se]:Object.create(null)}}add(t,e,r){let n=this.#t,s=this.#e;if(!n||!s)throw new Error(So);n[t]||[n,s].forEach(a=>{a[t]=Object.create(null),Object.keys(a[se]).forEach(c=>{a[t][c]=[...a[se][c]]})}),e==="/*"&&(e="*");let o=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=Ju(e);t===se?Object.keys(n).forEach(c=>{n[c][e]||=on(n[c],e)||on(n[se],e)||[]}):n[t][e]||=on(n[t],e)||on(n[se],e)||[],Object.keys(n).forEach(c=>{(t===se||t===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,o])})}),Object.keys(s).forEach(c=>{(t===se||t===c)&&Object.keys(s[c]).forEach(l=>a.test(l)&&s[c][l].push([r,o]))});return}let i=xo(e)||[e];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(s).forEach(u=>{(t===se||t===u)&&(s[u][l]||=[...on(n[u],l)||on(n[se],l)||[]],s[u][l].push([r,o-c+a+1]))})}}match=Ha;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,bh(),t}#r(t){let e=[],r=t===se;return[this.#t,this.#e].forEach(n=>{let s=n[t]?Object.keys(n[t]).map(o=>[o,n[t][o]]):[];s.length!==0?(r||=!0,e.push(...s)):t!==se&&e.push(...Object.keys(n[se]).map(o=>[o,n[se][o]]))}),r?wh(e):null}};var Za=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(So);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,s=r.length,o=0,i;for(;o<s;o++){let a=r[o];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(t,e)}catch(c){if(c instanceof Eo)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(o===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var ns=Object.create(null),vh=t=>{for(let e in t)return!0;return!1},Zu=class Gu{#t;#e;#r;#o=0;#s=ns;constructor(e,r,n){if(this.#e=n||Object.create(null),this.#t=[],e&&r){let s=Object.create(null);s[e]={handler:r,possibleKeys:[],score:0},this.#t=[s]}this.#r=[]}insert(e,r,n){this.#o=++this.#o;let s=this,o=Tu(r),i=[];for(let a=0,c=o.length;a<c;a++){let l=o[a],u=o[a+1],d=Ru(l,u),p=Array.isArray(d)?d[0]:l;if(p in s.#e){s=s.#e[p],d&&i.push(d[1]);continue}s.#e[p]=new Gu,d&&(s.#r.push(d),i.push(d[1])),s=s.#e[p]}return s.#t.push({[e]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#o}}),s}#n(e,r,n,s,o){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[se],u={};if(l!==void 0&&(l.params=Object.create(null),e.push(l),s!==ns||o&&o!==ns))for(let d=0,p=l.possibleKeys.length;d<p;d++){let g=l.possibleKeys[d],w=u[l.score];l.params[g]=o?.[g]&&!w?o[g]:s[g]??o?.[g],u[l.score]=!0}}}search(e,r){let n=[];this.#s=ns;let o=[this],i=za(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let d=i[u],p=u===c-1,g=[];for(let b=0,E=o.length;b<E;b++){let S=o[b],k=S.#e[d];k&&(k.#s=S.#s,p?(k.#e["*"]&&this.#n(n,k.#e["*"],e,S.#s),this.#n(n,k,e,S.#s)):g.push(k));for(let q=0,P=S.#r.length;q<P;q++){let X=S.#r[q],L=S.#s===ns?{}:{...S.#s};if(X==="*"){let we=S.#e["*"];we&&(this.#n(n,we,e,S.#s),we.#s=L,g.push(we));continue}let[I,A,V]=X;if(!d&&!(V instanceof RegExp))continue;let oe=S.#e[I];if(V instanceof RegExp){if(l===null){l=new Array(c);let re=r[0]==="/"?1:0;for(let J=0;J<c;J++)l[J]=re,re+=i[J].length+1}let we=r.substring(l[u]),ue=V.exec(we);if(ue){if(L[A]=ue[0],this.#n(n,oe,e,S.#s,L),vh(oe.#e)){oe.#s=L;let re=ue[0].match(/\//)?.length??0;(a[re]||=[]).push(oe)}continue}}(V===!0||V.test(d))&&(L[A]=d,p?(this.#n(n,oe,e,L,S.#s),oe.#e["*"]&&this.#n(n,oe.#e["*"],e,L,S.#s)):(oe.#s=L,g.push(oe)))}}let w=a.shift();o=w?g.concat(w):g}return n.length>1&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var Ga=class{name="TrieRouter";#t;constructor(){this.#t=new Zu}add(t,e,r){let n=xo(e);if(n){for(let s=0,o=n.length;s<o;s++)this.#t.insert(t,n[s],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}};var Ya=class extends Fu{constructor(t={}){super(t),this.router=t.router??new Za({routers:[new To,new Ga]})}};var y={};Rc(y,{BRAND:()=>ad,DIRTY:()=>Bt,EMPTY_PATH:()=>td,INVALID:()=>C,NEVER:()=>qd,OK:()=>Ee,ParseStatus:()=>_e,Schema:()=>$,ZodAny:()=>At,ZodArray:()=>mt,ZodBigInt:()=>Qt,ZodBoolean:()=>Vt,ZodBranded:()=>ln,ZodCatch:()=>nr,ZodDate:()=>Wt,ZodDefault:()=>rr,ZodDiscriminatedUnion:()=>is,ZodEffects:()=>ze,ZodEnum:()=>er,ZodError:()=>Ne,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>cs,ZodIntersection:()=>Gt,ZodIssueCode:()=>x,ZodLazy:()=>Yt,ZodLiteral:()=>Xt,ZodMap:()=>xr,ZodNaN:()=>Sr,ZodNativeEnum:()=>tr,ZodNever:()=>Ve,ZodNull:()=>Jt,ZodNullable:()=>tt,ZodNumber:()=>Ft,ZodObject:()=>Ce,ZodOptional:()=>Me,ZodParsedType:()=>R,ZodPipeline:()=>un,ZodPromise:()=>Ot,ZodReadonly:()=>sr,ZodRecord:()=>as,ZodSchema:()=>$,ZodSet:()=>_r,ZodString:()=>Rt,ZodSymbol:()=>wr,ZodTransformer:()=>ze,ZodTuple:()=>et,ZodType:()=>$,ZodUndefined:()=>Ht,ZodUnion:()=>Zt,ZodUnknown:()=>pt,ZodVoid:()=>vr,addIssueToContext:()=>T,any:()=>gd,array:()=>qe,bigint:()=>dd,boolean:()=>nc,coerce:()=>$d,custom:()=>rc,date:()=>fd,datetimeRegex:()=>tc,default:()=>Bh,defaultErrorMap:()=>ft,discriminatedUnion:()=>pn,effect:()=>Rd,enum:()=>We,function:()=>Ed,getErrorMap:()=>yr,getParsedType:()=>Xe,instanceof:()=>ld,intersection:()=>vd,isAborted:()=>ss,isAsync:()=>br,isDirty:()=>os,isValid:()=>jt,late:()=>cd,lazy:()=>Id,literal:()=>Ie,makeIssue:()=>an,map:()=>_d,nan:()=>ud,nativeEnum:()=>jd,never:()=>yd,null:()=>hd,nullable:()=>Od,number:()=>pe,object:()=>B,objectUtil:()=>Ro,oboolean:()=>Dd,onumber:()=>kd,optional:()=>Ad,ostring:()=>Cd,pipeline:()=>Nd,preprocess:()=>Pd,promise:()=>Td,quotelessJson:()=>Yu,record:()=>Er,set:()=>Sd,setErrorMap:()=>ed,strictObject:()=>wd,string:()=>N,symbol:()=>pd,transformer:()=>Rd,tuple:()=>xd,undefined:()=>md,union:()=>fn,unknown:()=>dn,util:()=>F,void:()=>bd,z:()=>j});var j={};Rc(j,{BRAND:()=>ad,DIRTY:()=>Bt,EMPTY_PATH:()=>td,INVALID:()=>C,NEVER:()=>qd,OK:()=>Ee,ParseStatus:()=>_e,Schema:()=>$,ZodAny:()=>At,ZodArray:()=>mt,ZodBigInt:()=>Qt,ZodBoolean:()=>Vt,ZodBranded:()=>ln,ZodCatch:()=>nr,ZodDate:()=>Wt,ZodDefault:()=>rr,ZodDiscriminatedUnion:()=>is,ZodEffects:()=>ze,ZodEnum:()=>er,ZodError:()=>Ne,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>cs,ZodIntersection:()=>Gt,ZodIssueCode:()=>x,ZodLazy:()=>Yt,ZodLiteral:()=>Xt,ZodMap:()=>xr,ZodNaN:()=>Sr,ZodNativeEnum:()=>tr,ZodNever:()=>Ve,ZodNull:()=>Jt,ZodNullable:()=>tt,ZodNumber:()=>Ft,ZodObject:()=>Ce,ZodOptional:()=>Me,ZodParsedType:()=>R,ZodPipeline:()=>un,ZodPromise:()=>Ot,ZodReadonly:()=>sr,ZodRecord:()=>as,ZodSchema:()=>$,ZodSet:()=>_r,ZodString:()=>Rt,ZodSymbol:()=>wr,ZodTransformer:()=>ze,ZodTuple:()=>et,ZodType:()=>$,ZodUndefined:()=>Ht,ZodUnion:()=>Zt,ZodUnknown:()=>pt,ZodVoid:()=>vr,addIssueToContext:()=>T,any:()=>gd,array:()=>qe,bigint:()=>dd,boolean:()=>nc,coerce:()=>$d,custom:()=>rc,date:()=>fd,datetimeRegex:()=>tc,defaultErrorMap:()=>ft,discriminatedUnion:()=>pn,effect:()=>Rd,enum:()=>We,function:()=>Ed,getErrorMap:()=>yr,getParsedType:()=>Xe,instanceof:()=>ld,intersection:()=>vd,isAborted:()=>ss,isAsync:()=>br,isDirty:()=>os,isValid:()=>jt,late:()=>cd,lazy:()=>Id,literal:()=>Ie,makeIssue:()=>an,map:()=>_d,nan:()=>ud,nativeEnum:()=>jd,never:()=>yd,null:()=>hd,nullable:()=>Od,number:()=>pe,object:()=>B,objectUtil:()=>Ro,oboolean:()=>Dd,onumber:()=>kd,optional:()=>Ad,ostring:()=>Cd,pipeline:()=>Nd,preprocess:()=>Pd,promise:()=>Td,quotelessJson:()=>Yu,record:()=>Er,set:()=>Sd,setErrorMap:()=>ed,strictObject:()=>wd,string:()=>N,symbol:()=>pd,transformer:()=>Rd,tuple:()=>xd,undefined:()=>md,union:()=>fn,unknown:()=>dn,util:()=>F,void:()=>bd});var F;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(F||(F={}));var Ro;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ro||(Ro={}));var R=F.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Xe=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}};var x=F.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Yu=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ne=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,F.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ne.create=t=>new Ne(t);var xh=(t,e)=>{let r;switch(t.code){case x.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case x.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,F.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:r=`Unrecognized key(s) in object: ${F.joinValues(t.keys,", ")}`;break;case x.invalid_union:r="Invalid input";break;case x.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${F.joinValues(t.options)}`;break;case x.invalid_enum_value:r=`Invalid enum value. Expected ${F.joinValues(t.options)}, received '${t.received}'`;break;case x.invalid_arguments:r="Invalid function arguments";break;case x.invalid_return_type:r="Invalid function return type";break;case x.invalid_date:r="Invalid date";break;case x.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:F.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case x.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case x.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case x.custom:r="Invalid input";break;case x.invalid_intersection_types:r="Intersection results could not be merged";break;case x.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case x.not_finite:r="Number must be finite";break;default:r=e.defaultError,F.assertNever(t)}return{message:r}},ft=xh;var Xu=ft;function ed(t){Xu=t}function yr(){return Xu}var an=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},td=[];function T(t,e){let r=yr(),n=an({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===ft?void 0:ft].filter(s=>!!s)});t.common.issues.push(n)}var _e=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return C;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return C;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},C=Object.freeze({status:"aborted"}),Bt=t=>({status:"dirty",value:t}),Ee=t=>({status:"valid",value:t}),ss=t=>t.status==="aborted",os=t=>t.status==="dirty",jt=t=>t.status==="valid",br=t=>typeof Promise<"u"&&t instanceof Promise;var O;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(O||(O={}));var Qe=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},rd=(t,e)=>{if(jt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ne(t.common.issues);return this._error=r,this._error}}};function M(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:s}}var $=class{get description(){return this._def.description}_getType(e){return Xe(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _e,ctx:{common:e.parent.common,data:e.data,parsedType:Xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(br(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)},s=this._parseSync({data:e,path:n.path,parent:n});return rd(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return jt(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>jt(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(br(s)?s:Promise.resolve(s));return rd(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:x.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new ze({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Me.create(this,this._def)}nullable(){return tt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return mt.create(this)}promise(){return Ot.create(this,this._def)}or(e){return Zt.create([this,e],this._def)}and(e){return Gt.create(this,e,this._def)}transform(e){return new ze({...M(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new rr({...M(this._def),innerType:this,defaultValue:r,typeName:D.ZodDefault})}brand(){return new ln({typeName:D.ZodBranded,type:this,...M(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new nr({...M(this._def),innerType:this,catchValue:r,typeName:D.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return un.create(this,e)}readonly(){return sr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},_h=/^c[^\s-]{8,}$/i,Sh=/^[0-9a-z]+$/,Eh=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ih=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,jh=/^[a-z0-9_-]{21}$/i,Th=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rh=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ah=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Oh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Xa,Ph=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Nh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ch=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,kh=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Dh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$h=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,sd="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",qh=new RegExp(`^${sd}$`);function od(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Lh(t){return new RegExp(`^${od(t)}$`)}function tc(t){let e=`${sd}T${od(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Mh(t,e){return!!((e==="v4"||!e)&&Ph.test(t)||(e==="v6"||!e)&&Ch.test(t))}function zh(t,e){if(!Th.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Uh(t,e){return!!((e==="v4"||!e)&&Nh.test(t)||(e==="v6"||!e)&&kh.test(t))}var Rt=class t extends ${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let o=this._getOrReturnCtx(e);return T(o,{code:x.invalid_type,expected:R.string,received:o.parsedType}),C}let n=new _e,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),T(s,{code:x.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),T(s,{code:x.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?T(s,{code:x.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&T(s,{code:x.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Ah.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"email",code:x.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Xa||(Xa=new RegExp(Oh,"u")),Xa.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"emoji",code:x.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Ih.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"uuid",code:x.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")jh.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"nanoid",code:x.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")_h.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"cuid",code:x.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Sh.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"cuid2",code:x.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Eh.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"ulid",code:x.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),T(s,{validation:"url",code:x.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"regex",code:x.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),T(s,{code:x.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),T(s,{code:x.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),T(s,{code:x.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?tc(o).test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{code:x.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?qh.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{code:x.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?Lh(o).test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{code:x.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?Rh.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"duration",code:x.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?Mh(e.data,o.version)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"ip",code:x.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?zh(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"jwt",code:x.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?Uh(e.data,o.version)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"cidr",code:x.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Dh.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"base64",code:x.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?$h.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"base64url",code:x.invalid_string,message:o.message}),n.dirty()):F.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:x.invalid_string,...O.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...O.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...O.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...O.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...O.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...O.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...O.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...O.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...O.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...O.errToObj(r)})}nonempty(e){return this.min(1,O.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Rt.create=t=>new Rt({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...M(t)});function Kh(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}var Ft=class t extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){let o=this._getOrReturnCtx(e);return T(o,{code:x.invalid_type,expected:R.number,received:o.parsedType}),C}let n,s=new _e;for(let o of this._def.checks)o.kind==="int"?F.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:x.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:x.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:x.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?Kh(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:x.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:x.not_finite,message:o.message}),s.dirty()):F.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,O.toString(r))}gt(e,r){return this.setLimit("min",e,!1,O.toString(r))}lte(e,r){return this.setLimit("max",e,!0,O.toString(r))}lt(e,r){return this.setLimit("max",e,!1,O.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:O.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:O.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&F.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Ft.create=t=>new Ft({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...M(t)});var Qt=class t extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let n,s=new _e;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:x.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:x.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:x.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):F.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:x.invalid_type,expected:R.bigint,received:r.parsedType}),C}gte(e,r){return this.setLimit("min",e,!0,O.toString(r))}gt(e,r){return this.setLimit("min",e,!1,O.toString(r))}lte(e,r){return this.setLimit("max",e,!0,O.toString(r))}lt(e,r){return this.setLimit("max",e,!1,O.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:O.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Qt.create=t=>new Qt({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...M(t)});var Vt=class extends ${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:x.invalid_type,expected:R.boolean,received:n.parsedType}),C}return Ee(e.data)}};Vt.create=t=>new Vt({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...M(t)});var Wt=class t extends ${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let o=this._getOrReturnCtx(e);return T(o,{code:x.invalid_type,expected:R.date,received:o.parsedType}),C}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return T(o,{code:x.invalid_date}),C}let n=new _e,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),T(s,{code:x.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),T(s,{code:x.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):F.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:O.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:O.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Wt.create=t=>new Wt({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...M(t)});var wr=class extends ${_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:x.invalid_type,expected:R.symbol,received:n.parsedType}),C}return Ee(e.data)}};wr.create=t=>new wr({typeName:D.ZodSymbol,...M(t)});var Ht=class extends ${_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:x.invalid_type,expected:R.undefined,received:n.parsedType}),C}return Ee(e.data)}};Ht.create=t=>new Ht({typeName:D.ZodUndefined,...M(t)});var Jt=class extends ${_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:x.invalid_type,expected:R.null,received:n.parsedType}),C}return Ee(e.data)}};Jt.create=t=>new Jt({typeName:D.ZodNull,...M(t)});var At=class extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return Ee(e.data)}};At.create=t=>new At({typeName:D.ZodAny,...M(t)});var pt=class extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ee(e.data)}};pt.create=t=>new pt({typeName:D.ZodUnknown,...M(t)});var Ve=class extends ${_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:x.invalid_type,expected:R.never,received:r.parsedType}),C}};Ve.create=t=>new Ve({typeName:D.ZodNever,...M(t)});var vr=class extends ${_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:x.invalid_type,expected:R.void,received:n.parsedType}),C}return Ee(e.data)}};vr.create=t=>new vr({typeName:D.ZodVoid,...M(t)});var mt=class t extends ${_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==R.array)return T(r,{code:x.invalid_type,expected:R.array,received:r.parsedType}),C;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(T(r,{code:i?x.too_big:x.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(T(r,{code:x.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(T(r,{code:x.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new Qe(r,i,r.path,a)))).then(i=>_e.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new Qe(r,i,r.path,a)));return _e.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:O.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:O.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:O.toString(r)}})}nonempty(e){return this.min(1,e)}};mt.create=(t,e)=>new mt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...M(e)});function cn(t){if(t instanceof Ce){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Me.create(cn(n))}return new Ce({...t._def,shape:()=>e})}else return t instanceof mt?new mt({...t._def,type:cn(t.element)}):t instanceof Me?Me.create(cn(t.unwrap())):t instanceof tt?tt.create(cn(t.unwrap())):t instanceof et?et.create(t.items.map(e=>cn(e))):t}var Ce=class t extends ${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=F.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==R.object){let l=this._getOrReturnCtx(e);return T(l,{code:x.invalid_type,expected:R.object,received:l.parsedType}),C}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ve&&this._def.unknownKeys==="strip"))for(let l in s.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=o[l],d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Qe(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Ve){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")a.length>0&&(T(s,{code:x.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Qe(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,p=await u.value;l.push({key:d,value:p,alwaysSet:u.alwaysSet})}return l}).then(l=>_e.mergeObjectSync(n,l)):_e.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return O.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:O.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of F.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of F.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return cn(this)}partial(e){let r={};for(let n of F.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of F.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Me;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return id(F.objectKeys(this.shape))}};Ce.create=(t,e)=>new Ce({shape:()=>t,unknownKeys:"strip",catchall:Ve.create(),typeName:D.ZodObject,...M(e)});Ce.strictCreate=(t,e)=>new Ce({shape:()=>t,unknownKeys:"strict",catchall:Ve.create(),typeName:D.ZodObject,...M(e)});Ce.lazycreate=(t,e)=>new Ce({shape:t,unknownKeys:"strip",catchall:Ve.create(),typeName:D.ZodObject,...M(e)});var Zt=class extends ${_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new Ne(a.ctx.common.issues));return T(r,{code:x.invalid_union,unionErrors:i}),C}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new Ne(c));return T(r,{code:x.invalid_union,unionErrors:a}),C}}get options(){return this._def.options}};Zt.create=(t,e)=>new Zt({options:t,typeName:D.ZodUnion,...M(e)});var Tt=t=>t instanceof Yt?Tt(t.schema):t instanceof ze?Tt(t.innerType()):t instanceof Xt?[t.value]:t instanceof er?t.options:t instanceof tr?F.objectValues(t.enum):t instanceof rr?Tt(t._def.innerType):t instanceof Ht?[void 0]:t instanceof Jt?[null]:t instanceof Me?[void 0,...Tt(t.unwrap())]:t instanceof tt?[null,...Tt(t.unwrap())]:t instanceof ln||t instanceof sr?Tt(t.unwrap()):t instanceof nr?Tt(t._def.innerType):[],is=class t extends ${_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return T(r,{code:x.invalid_type,expected:R.object,received:r.parsedType}),C;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),C)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=Tt(o.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...M(n)})}};function ec(t,e){let r=Xe(t),n=Xe(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){let s=F.objectKeys(e),o=F.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=ec(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===R.array&&n===R.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=ec(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===R.date&&n===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Gt=class extends ${_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(ss(o)||ss(i))return C;let a=ec(o.value,i.value);return a.valid?((os(o)||os(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:x.invalid_intersection_types}),C)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Gt.create=(t,e,r)=>new Gt({left:t,right:e,typeName:D.ZodIntersection,...M(r)});var et=class t extends ${_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:x.invalid_type,expected:R.array,received:n.parsedType}),C;if(n.data.length<this._def.items.length)return T(n,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),C;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Qe(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>_e.mergeArray(r,i)):_e.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};et.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new et({items:t,typeName:D.ZodTuple,rest:null,...M(e)})};var as=class t extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return T(n,{code:x.invalid_type,expected:R.object,received:n.parsedType}),C;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new Qe(n,a,n.path,a)),value:i._parse(new Qe(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?_e.mergeObjectAsync(r,s):_e.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof $?new t({keyType:e,valueType:r,typeName:D.ZodRecord,...M(n)}):new t({keyType:Rt.create(),valueType:e,typeName:D.ZodRecord,...M(r)})}},xr=class extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return T(n,{code:x.invalid_type,expected:R.map,received:n.parsedType}),C;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:s._parse(new Qe(n,a,n.path,[l,"key"])),value:o._parse(new Qe(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return C;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return C;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};xr.create=(t,e,r)=>new xr({valueType:e,keyType:t,typeName:D.ZodMap,...M(r)});var _r=class t extends ${_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:x.invalid_type,expected:R.set,received:n.parsedType}),C;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(T(n,{code:x.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(T(n,{code:x.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return C;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>o._parse(new Qe(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:O.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:O.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};_r.create=(t,e)=>new _r({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...M(e)});var cs=class t extends ${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.function)return T(r,{code:x.invalid_type,expected:R.function,received:r.parsedType}),C;function n(a,c){return an({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,yr(),ft].filter(l=>!!l),issueData:{code:x.invalid_arguments,argumentsError:c}})}function s(a,c){return an({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,yr(),ft].filter(l=>!!l),issueData:{code:x.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Ot){let a=this;return Ee(async function(...c){let l=new Ne([]),u=await a._def.args.parseAsync(c,o).catch(g=>{throw l.addIssue(n(c,g)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(g=>{throw l.addIssue(s(d,g)),l})})}else{let a=this;return Ee(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new Ne([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new Ne([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:et.create(e).rest(pt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||et.create([]).rest(pt.create()),returns:r||pt.create(),typeName:D.ZodFunction,...M(n)})}},Yt=class extends ${get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Yt.create=(t,e)=>new Yt({getter:t,typeName:D.ZodLazy,...M(e)});var Xt=class extends ${_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:x.invalid_literal,expected:this._def.value}),C}return{status:"valid",value:e.data}}get value(){return this._def.value}};Xt.create=(t,e)=>new Xt({value:t,typeName:D.ZodLiteral,...M(e)});function id(t,e){return new er({values:t,typeName:D.ZodEnum,...M(e)})}var er=class t extends ${_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:F.joinValues(n),received:r.parsedType,code:x.invalid_type}),C}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{received:r.data,code:x.invalid_enum_value,options:n}),C}return Ee(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};er.create=id;var tr=class extends ${_parse(e){let r=F.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let s=F.objectValues(r);return T(n,{expected:F.joinValues(s),received:n.parsedType,code:x.invalid_type}),C}if(this._cache||(this._cache=new Set(F.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=F.objectValues(r);return T(n,{received:n.data,code:x.invalid_enum_value,options:s}),C}return Ee(e.data)}get enum(){return this._def.values}};tr.create=(t,e)=>new tr({values:t,typeName:D.ZodNativeEnum,...M(e)});var Ot=class extends ${unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.promise&&r.common.async===!1)return T(r,{code:x.invalid_type,expected:R.promise,received:r.parsedType}),C;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return Ee(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ot.create=(t,e)=>new Ot({type:t,typeName:D.ZodPromise,...M(e)});var ze=class extends ${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{T(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return C;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?C:c.status==="dirty"?Bt(c.value):r.value==="dirty"?Bt(c.value):c});{if(r.value==="aborted")return C;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?C:a.status==="dirty"?Bt(a.value):r.value==="dirty"?Bt(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?C:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?C:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!jt(i))return C;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>jt(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):C);F.assertNever(s)}};ze.create=(t,e,r)=>new ze({schema:t,typeName:D.ZodEffects,effect:e,...M(r)});ze.createWithPreprocess=(t,e,r)=>new ze({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...M(r)});var Me=class extends ${_parse(e){return this._getType(e)===R.undefined?Ee(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Me.create=(t,e)=>new Me({innerType:t,typeName:D.ZodOptional,...M(e)});var tt=class extends ${_parse(e){return this._getType(e)===R.null?Ee(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};tt.create=(t,e)=>new tt({innerType:t,typeName:D.ZodNullable,...M(e)});var rr=class extends ${_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};rr.create=(t,e)=>new rr({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...M(e)});var nr=class extends ${_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return br(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ne(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ne(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};nr.create=(t,e)=>new nr({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...M(e)});var Sr=class extends ${_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:x.invalid_type,expected:R.nan,received:n.parsedType}),C}return{status:"valid",value:e.data}}};Sr.create=t=>new Sr({typeName:D.ZodNaN,...M(t)});var ad=Symbol("zod_brand"),ln=class extends ${_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},un=class t extends ${_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?C:o.status==="dirty"?(r.dirty(),Bt(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?C:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:D.ZodPipeline})}},sr=class extends ${_parse(e){let r=this._def.innerType._parse(e),n=s=>(jt(s)&&(s.value=Object.freeze(s.value)),s);return br(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};sr.create=(t,e)=>new sr({innerType:t,typeName:D.ZodReadonly,...M(e)});function nd(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function rc(t,e={},r){return t?At.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=nd(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=nd(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):At.create()}var cd={object:Ce.lazycreate},D;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(D||(D={}));var ld=(t,e={message:`Input not instance of ${t.name}`})=>rc(r=>r instanceof t,e),N=Rt.create,pe=Ft.create,ud=Sr.create,dd=Qt.create,nc=Vt.create,fd=Wt.create,pd=wr.create,md=Ht.create,hd=Jt.create,gd=At.create,dn=pt.create,yd=Ve.create,bd=vr.create,qe=mt.create,B=Ce.create,wd=Ce.strictCreate,fn=Zt.create,pn=is.create,vd=Gt.create,xd=et.create,Er=as.create,_d=xr.create,Sd=_r.create,Ed=cs.create,Id=Yt.create,Ie=Xt.create,We=er.create,jd=tr.create,Td=Ot.create,Rd=ze.create,Ad=Me.create,Od=tt.create,Pd=ze.createWithPreprocess,Nd=un.create,Cd=()=>N().optional(),kd=()=>pe().optional(),Dd=()=>nc().optional(),$d={string:(t=>Rt.create({...t,coerce:!0})),number:(t=>Ft.create({...t,coerce:!0})),boolean:(t=>Vt.create({...t,coerce:!0})),bigint:(t=>Qt.create({...t,coerce:!0})),date:(t=>Wt.create({...t,coerce:!0}))};var qd=C;var Bh=j;var oc=class sc extends Ya{openAPIRegistry;defaultHook;constructor(e){super(e),this.openAPIRegistry=new ho,this.defaultHook=e?.defaultHook}openapi=({middleware:e,...r},n,s=this.defaultHook)=>{this.openAPIRegistry.registerPath(r);let o=[];if(r.request?.query){let c=hr("query",r.request.query,s);o.push(c)}if(r.request?.params){let c=hr("param",r.request.params,s);o.push(c)}if(r.request?.headers){let c=hr("header",r.request.headers,s);o.push(c)}if(r.request?.cookies){let c=hr("cookie",r.request.cookies,s);o.push(c)}let i=r.request?.body?.content;if(i)for(let c of Object.keys(i)){if(!i[c])continue;let l=i[c].schema;if(l instanceof $){if(Md(c)){let u=hr("json",l,s);if(r.request?.body?.required)o.push(u);else{let d=async(p,g)=>{if(p.req.header("content-type")&&Md(p.req.header("content-type")))return await u(p,g);p.req.addValidatedData("json",{}),await g()};o.push(d)}}if(zd(c)){let u=hr("form",l,s);if(r.request?.body?.required)o.push(u);else{let d=async(p,g)=>{if(p.req.header("content-type")&&zd(p.req.header("content-type")))return await u(p,g);p.req.addValidatedData("form",{}),await g()};o.push(d)}}}}let a=e?Array.isArray(e)?e:[e]:[];return this.on([r.method],r.path.replaceAll(/\/{(.+?)}/g,"/:$1"),...a,...o,n),this};getOpenAPIDocument=e=>{let n=new yo(this.openAPIRegistry.definitions).generateDocument(e);return this._basePath?Ld(n,this._basePath):n};getOpenAPI31Document=e=>{let n=new bo(this.openAPIRegistry.definitions).generateDocument(e);return this._basePath?Ld(n,this._basePath):n};doc=(e,r)=>this.get(e,n=>{let s=typeof r=="function"?r(n):r;try{let o=this.getOpenAPIDocument(s);return n.json(o)}catch(o){return n.json(o,500)}});doc31=(e,r)=>this.get(e,n=>{let s=typeof r=="function"?r(n):r;try{let o=this.getOpenAPI31Document(s);return n.json(o)}catch(o){return n.json(o,500)}});route(e,r){let n=e.replaceAll(/:([^\/]+)/g,"{$1}");return super.route(e,r),r instanceof sc?(r.openAPIRegistry.definitions.forEach(s=>{switch(s.type){case"component":return this.openAPIRegistry.registerComponent(s.componentType,s.name,s.component);case"route":return this.openAPIRegistry.registerPath({...s.route,path:Fe(n,s.route.path)});case"webhook":return this.openAPIRegistry.registerWebhook({...s.webhook,path:Fe(n,s.webhook.path)});case"schema":return this.openAPIRegistry.register(s.schema._def.openapi._internal.refId,s.schema);case"parameter":return this.openAPIRegistry.registerParameter(s.schema._def.openapi._internal.refId,s.schema);default:{let o=s;throw new Error(`Unknown registry type: ${o}`)}}}),this):this}basePath(e){return new sc({...super.basePath(e),defaultHook:this.defaultHook})}},Ud=t=>{let e={...t,getRoutingPath(){return t.path.replaceAll(/\/{(.+?)}/g,"/:$1")}};return Object.defineProperty(e,"getRoutingPath",{enumerable:!1})};wo(j);function Ld(t,e){let r={};return Object.keys(t.paths).forEach(n=>{r[Fe(e,n)]=t.paths[n]}),{...t,paths:r}}function Md(t){return/^application\/([a-z-\.]+\+)?json/.test(t)}function zd(t){return t.startsWith("multipart/form-data")||t.startsWith("application/x-www-form-urlencoded")}var ls=32;function Kd(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).every(r=>["code","groupingKey","tags"].includes(r))&&[t.code,t.groupingKey].every(r=>r===void 0||typeof r=="string"&&/^[a-zA-Z][a-zA-Z0-9_.:-]{0,127}$/u.test(r))&&(t.tags===void 0||t.tags&&typeof t.tags=="object"&&!Array.isArray(t.tags)&&Object.entries(t.tags).length<=16&&Object.entries(t.tags).every(([r,n])=>/^[a-zA-Z][a-zA-Z0-9_.-]{0,47}$/u.test(r)&&!Bd(r)&&typeof n=="string"&&n.length<=128))}function Bd(t){return/token|password|secret|authorization|cookie|headers|body|sql|params/iu.test(t)}function Fd(t){return t?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,Ue(r,128)])):void 0}function ic(t){let e=Object.entries(t??{}),r=e.slice(0,16).filter(([n,s])=>/^[a-zA-Z][a-zA-Z0-9_.-]{0,47}$/u.test(n)&&!Bd(n)&&(typeof s=="string"||typeof s=="boolean"||typeof s=="number"&&Number.isFinite(s))).map(([n,s])=>[n,typeof s=="string"?Ue(s,128):s]);return{values:Object.fromEntries(r),dropped:e.length-r.length}}function Qd(t){try{if(!(t instanceof Error))return{name:"NonError",message:typeof t=="string"?Ue(t,2048):"Non-Error exception",stack:null};let{name:e,message:r,stack:n}=t;return{name:typeof e=="string"&&/^[a-zA-Z][a-zA-Z0-9_.]{0,95}$/u.test(e)?e:"Error",message:typeof r=="string"?Ue(r,2048):"",stack:typeof n=="string"?Ue(n,16384):null}}catch{return{name:"Error",message:"[unreadable exception]",stack:null}}}function Ao(t,e){let r=new Set;for(let n=0;n<10&&t&&typeof t=="object"&&!r.has(t);n++){r.add(t);let s=e.errorSpans.get(t),o=e.safeSqlErrors.get(t);if(s||o)return{spanId:s,safeSqlError:o};try{t=Object.getOwnPropertyDescriptor(t,"cause")?.value}catch{break}}return null}import{AsyncLocalStorage as Fh}from"node:async_hooks";var Ir=new Fh,Qh=100,Vh=20;async function Wh(t,e,r){let n=Ir.getStore();if(!n||n.session.closed)return{status:"unavailable",reason:"outside_request"};let s=n.session;if(!s.provider)return{status:"unavailable",reason:"not_configured"};let o=s.source();if(!o)return{status:"unavailable",reason:"source_unavailable"};if(!Kd(e))return{status:"rejected",reason:"invalid_context"};let i=t&&typeof t=="object"?t:null,a=i?s.errors.get(i):void 0;if(a)return a;if(s.errorCount>=Vh){try{s.provider.recordDroppedError?.(o)}catch{}return{status:"rejected",reason:"limit_exceeded"}}s.errorCount+=1;let c={schemaVersion:1,kind:"error",eventId:crypto.randomUUID(),occurredAt:new Date().toISOString(),source:{...o,routeTemplate:s.routeTemplate},mechanism:r,error:Ao(t,s)?.safeSqlError??Qd(t),context:{...e,tags:Fd(e.tags)},traceId:s.traceId,spanId:s.traceId?Ao(t,s)?.spanId??n.parentSpanId:null},l=(async()=>{try{let u=await s.provider.acceptError(c);return u.eventId!==c.eventId||!Number.isFinite(Date.parse(u.emittedAt))?{status:"failed",eventId:c.eventId}:{status:"emitted",eventId:c.eventId,emittedAt:u.emittedAt}}catch{return{status:"failed",eventId:c.eventId}}})();return i&&s.errors.set(i,l),s.pendingErrors.add(l),l}async function us(t,e,r,n){try{return await Hh(t,e,r,n)}catch(s){let o=Ir.getStore();throw t==="sql"&&o&&!o.session.closed&&s&&typeof s=="object"&&o.session.safeSqlErrors.set(s,Jh()),s}}async function Hh(t,e,r,n){let s=Ir.getStore();if(!s||s.session.closed||!s.session.traceId)return await r();let o=s.session;if(typeof e!="string"||!/^[\p{L}][\p{L}\p{N}_. -]{0,95}$/u.test(e)||o.spans.length>=Qh)return o.droppedSpans+=1,await r();let i=ic(n?.attributes),a={spanId:Jd(),parentSpanId:s.parentSpanId,name:e,kind:t,startedAt:new Date().toISOString(),durationMs:null,state:"running",status:"ok",attributes:i.values,droppedAttributes:i.dropped};o.spans.push(a);let c=performance.now();return Ir.run({session:o,parentSpanId:a.spanId},async()=>{try{let l=await r();if(n?.result){let u=n.result(l),d=ic({...a.attributes,...u.attributes});a.attributes=d.values,a.droppedAttributes+=d.dropped,u.error&&(a.status="error")}return l}catch(l){if(a.status="error",l&&typeof l=="object"&&!o.errorSpans.has(l)){let u=Ao(l,o);o.errorSpans.set(l,u?.spanId??a.spanId),u?.safeSqlError&&o.safeSqlErrors.set(l,u.safeSqlError)}throw l}finally{a.durationMs=Math.max(0,performance.now()-c),a.state="finished"}})}function Wd(t){let e=Ir.getStore();e&&(e.session.routeTemplate=t)}function Hd(t,e){let r=Ir.getStore();if(!r||r.session.closed||!r.session.propagation||!r.parentSpanId)return null;let n=r.session.source();if(!n||n.projectId!==String(t.projectId)||n.projectEnvKey!==t.projectEnvKey||n.productId!==t.extensionId||e.projectId!==t.projectId||e.projectEnvKey!==t.projectEnvKey)return null;if(r.session.propagation.hop>=ls){let s=r.session.spans.find(o=>o.spanId===r.parentSpanId);return s&&(s.attributes={...s.attributes,"trace.propagation":"hop_limit"}),null}return{...r.session.propagation,parentSpanId:r.parentSpanId,hop:r.session.propagation.hop+1}}async function ac(t,e){let r=t.background,n=t.incomingTrace?.status==="inherited"||t.incomingTrace?.status==="gateway"?t.incomingTrace.context:null,s=(t.incomingTrace?.status==="inherited"?t.incomingTrace.context.sampled:void 0)??!!(t.provider&&Math.random()<t.provider.traceSampleRate),o=!!(t.provider&&s),i=t.incomingTrace?.status==="inherited"?{unit:"trace",rule:"inherited",probability:null,ruleVersion:null}:{unit:"trace",rule:"head-random",probability:t.provider?.traceSampleRate??0,ruleVersion:1},a=n?{traceId:n.traceId,sampled:s,hop:n.hop}:t.provider&&t.source()?{traceId:crypto.randomUUID().replaceAll("-",""),sampled:s,hop:0}:null,c={spanId:a?Jd():"",parentSpanId:n?.parentSpanId??null,kind:r?"business":"http",name:t.method,startedAt:new Date().toISOString(),durationMs:null,state:"running",status:"ok",attributes:{},droppedAttributes:0},l={provider:t.provider,source:t.source,routeTemplate:r?.kind??null,traceId:o?a?.traceId??null:null,propagation:a,sampling:i,spans:o?[c]:[],droppedSpans:0,errorCount:0,errors:new WeakMap,pendingErrors:new Set,errorSpans:new WeakMap,safeSqlErrors:new WeakMap,closed:!1},u=performance.now();await Qc(()=>Ir.run({session:l,parentSpanId:c.spanId},async()=>{let d,p=!1;try{await e()}catch(g){throw d=g,p=!0,g}finally{c.durationMs=Math.max(0,performance.now()-u),c.state="finished",c.name=r?r.kind==="queue"?"Queue batch":"Scheduled task":`${t.method} ${l.routeTemplate??"unmatched"}`,c.status=p||t.status()>=500?"error":"ok",c.attributes=r?{"faas.trigger":r.kind==="queue"?"pubsub":"timer",...r.kind==="queue"&&Number.isSafeInteger(r.messageCount)&&r.messageCount>=0?{"messaging.batch.message_count":r.messageCount}:{}}:{"http.request.method":t.method,"http.span_role":"server",...t.incomingTrace&&t.incomingTrace.status!=="none"?{"trace.context":t.incomingTrace.status}:{},...p?{}:{"http.status_code":t.status()}};let g=l.source(),w=l.traceId&&g?{schemaVersion:1,kind:"trace",traceId:l.traceId,source:{...g,routeTemplate:l.routeTemplate},sampling:l.sampling,spans:l.spans.map(k=>({...k,attributes:{...k.attributes}})),droppedSpans:l.droppedSpans}:null,b=p?d:t.error(),E=p||b!=null?Wh(b,{},"unhandled"):null;l.closed=!0;let S=(async()=>{let k=await Promise.all([...l.pendingErrors,...E?[E]:[]]),q=new Set;for(let P of k){let X="eventId"in P?P.eventId:P.status;P.status!=="emitted"&&!q.has(X)&&(q.add(X),Vd(t.requestId,P.status))}if(w&&l.provider)try{await l.provider.acceptTrace(w)}catch{Vd(t.requestId,"failed")}})();Vc(S)||(t.defer?t.defer(S):await S)}}),t.defer)}function Vd(t,e){console.warn(JSON.stringify({event:"runtime.telemetry_delivery",requestId:t,status:e}))}function cc(t,e,r="runtime.http_error"){let n=["Error","TypeError","RangeError","SyntaxError","ReferenceError","URIError","EvalError","AggregateError"],s="Error";try{if(t instanceof Error){let o=t.name;n.includes(o)&&(s=o)}}catch{}console.error(JSON.stringify({event:r,requestId:e,errorName:s}))}function Jd(){return crypto.randomUUID().replaceAll("-","").slice(0,16)}function Jh(){let t="Database operation failed.";try{let e=new Error(t).stack;return{name:"DatabaseError",message:t,stack:typeof e=="string"?Ue(e,16384):null}}catch{return{name:"DatabaseError",message:t,stack:null}}}function Zd(t){return{execute:e=>{let r=e.type,n="statements"in e?e.statements.length:r==="query"?1:0;return us("sql",`SQL ${r}`,()=>t.execute(e),{attributes:{"db.system":"sqlite","db.operation":r,"db.statement_count":n}})}}}function Gd(t){return{execute:e=>us("sql","SQL query",()=>t.execute(e),{attributes:{"db.system":"postgresql","db.operation":"query","db.statement_count":1}}),...t.transactionBatch?{transactionBatch:e=>us("sql","SQL transactionBatch",()=>t.transactionBatch(e),{attributes:{"db.system":"postgresql","db.operation":"transactionBatch","db.statement_count":e.length}})}:{}}}function lc(t,e,r,n){return us("rpc",r?"RPC system":"RPC extension",n,{attributes:{"rpc.system":"kuafu","rpc.target":t,"http.request.method":e},result:s=>({error:!s||s.status>=400,attributes:s?{"http.status_code":s.status}:{}})})}var Yd=Symbol.for("@kuafucloud/extension-kit:object-storage-contexts"),ds=globalThis[Yd]??(globalThis[Yd]=new WeakMap);function Xd(t,e){let r=ds.get(t);if(!r||r.scope.projectId!==e.projectId||r.scope.projectEnvKey!==e.projectEnvKey||r.scope.extensionId!==e.extensionId)throw new W("storage.outside_request")}function ef(t,e){return ds.set(t,{scope:Object.freeze({...e.scope}),bindings:e.bindings??{},readRegion:e.readRegion,homeRegion:e.homeRegion}),()=>{ds.delete(t)}}function Oo(t,e,r){let n=ds.get(t);if(!n)throw new W("storage.outside_request");let s=r??n.readRegion();if(!Pe(s))throw new W("storage.region_unavailable");let i=(n.config??=Dc(n.bindings[kc],n.scope)).regions[s]?.[e];if(!i)throw new W("storage.region_not_configured");let a=n.bindings.PLATFORM_GATEWAY_SERVICE;if(!a?.fetch)throw new W("storage.configuration_unavailable");let c=Nc({service:a,...i,extensionId:n.scope.extensionId}),l=()=>{if(ds.get(t)!==n)throw new W("storage.outside_request")};return{sign(u,d){return l(),c.sign(u,d)},head(u){return l(),c.head(u)},get(u,d){return l(),c.get(u,d)},put(u){return l(),c.put(u)},list(u){return l(),c.list(u)},delete(u){return l(),c.delete(u)}}}var uc=N().regex(/^[a-z][a-z0-9-]{0,62}$/u),mn=B({projectId:N(),projectEnvKey:N(),extensionId:N(),region:We(["cn","global"]),collectionId:uc,objectId:N().uuid()}),tf=B({ref:mn,ownerId:N().nullable(),size:pe(),contentType:N(),createdAt:pe()}),rf=B({url:N(),method:We(["GET","HEAD","PUT","POST","DELETE"]),headers:Er(N()),expiresAt:pe(),digestMetadataHeader:N().optional()}),Zh=fn([tf,rf,B({ref:mn,request:rf}),B({objects:qe(tf),cursor:N().nullable()}),B({deleted:Ie(!0)})]),fs=B({code:N(),message:N()}),Gh=pn("action",[B({action:Ie("createUpload"),collectionId:uc,size:pe().int().min(0),contentType:N(),input:dn().optional()}),B({action:Ie("resumeUpload"),ref:mn}),B({action:Ie("completeUpload"),ref:mn}),B({action:Ie("createDownload"),ref:mn}),B({action:Ie("delete"),ref:mn}),B({action:Ie("list"),collectionId:uc,cursor:N().optional(),limit:pe().int().min(1).max(100).optional()})]);function sf(t){return be(ae({method:"POST",path:"/_storage/objects",accessLevel:"private",authScope:"account",request:{body:Gh},responses:{200:{schema:B({data:Zh})},400:{schema:fs},403:{schema:fs},404:{schema:fs},409:{schema:fs},503:{schema:fs}}}),async(e,{body:r})=>{let n="ref"in r?r.ref.collectionId:r.collectionId,s=t.find(i=>i.id===n);if(!s)return e.json({code:"storage.collection_not_found",message:"\u96C6\u5408\u4E0D\u5B58\u5728\u3002"},404);let o=e.get("cloudStorage").collection(s);e.header("cache-control","private, no-store");try{switch(r.action){case"createUpload":{let i=await o.createUpload(r);return e.json({data:{ref:i.object.ref,request:i.request}},200)}case"resumeUpload":{let i=await o.resumeUpload(r.ref);return e.json({data:{ref:i.object.ref,request:i.request}},200)}case"completeUpload":return e.json({data:nf(await o.completeUpload(r.ref))},200);case"createDownload":return e.json({data:await o.createDownload(r.ref)},200);case"delete":return await o.delete(r.ref),e.json({data:{deleted:!0}},200);case"list":{let i=await o.list(r);return e.json({data:{objects:i.objects.map(nf),cursor:i.cursor}},200)}}}catch(i){if(!(i instanceof W))throw i;return i.code==="storage.forbidden"||i.code==="storage.object_scope_mismatch"?e.json({code:i.code,message:"\u65E0\u6743\u64CD\u4F5C\u6B64\u6587\u4EF6\u3002"},403):i.code==="storage.object_not_found"?e.json({code:i.code,message:"\u6587\u4EF6\u4E0D\u5B58\u5728\u3002"},404):["storage.upload_invalid","storage.request_invalid"].includes(i.code)?e.json({code:i.code,message:"\u6587\u4EF6\u53C2\u6570\u65E0\u6548\u3002"},400):["storage.upload_incomplete","storage.object_receipt_invalid","storage.object_not_uploading","storage.object_not_ready","storage.object_state_conflict"].includes(i.code)?e.json({code:i.code,message:"\u6587\u4EF6\u72B6\u6001\u4E0D\u652F\u6301\u6B64\u64CD\u4F5C\u3002"},409):e.json({code:"storage.operation_unavailable",message:"\u6587\u4EF6\u64CD\u4F5C\u6682\u65F6\u4E0D\u53EF\u7528\u3002"},503)}})}function nf(t){return{ref:t.ref,ownerId:t.ownerId,size:t.size,contentType:t.contentType,createdAt:t.createdAt}}import{AsyncLocalStorage as Yh}from"node:async_hooks";var of=new Yh;function ht(t,e){return of.run(t,e)}function Pt(){return of.getStore()}var ps={internalOnly:!0,auth:"signed",allowedCallerExtensions:["system"],allowCrossProject:!1,allowCrossEnvironment:!1},je=B({code:N(),message:N()});function af(t){let e=be(ae({method:"GET",path:"/_internal/cloud-storage/catalog",accessLevel:"public",internalPolicy:ps,responses:{200:{schema:B({data:B({collections:qe(B({id:N(),upload:B({maxBytes:pe(),contentTypes:qe(N())}),operations:qe(N())})),usage:qe(B({region:We(["cn","global"]),collectionId:N(),state:We(["uploading","ready","deleting"]),count:pe(),bytes:pe()}))})})}}}),async a=>a.json({data:{collections:a.get("cloudStorage").describeCollections(),usage:await a.get("cloudStorage").describeUsage()}},200)),r=be(ae({method:"POST",path:"/_internal/cloud-storage/objects/list",accessLevel:"public",internalPolicy:ps,request:{body:B({collectionId:N(),region:We(["cn","global"]),adminId:N().min(1),roles:qe(N()),cursor:N().optional(),limit:pe().int().min(1).max(100).default(50)})},responses:{200:{schema:B({data:B({objects:qe(B({id:N(),ownerId:N().nullable(),size:pe(),contentType:N(),createdAt:pe()})),cursor:N().nullable()})})},400:{schema:je},403:{schema:je},404:{schema:je},503:{schema:je}}}),async(a,{body:c})=>{let l=t.find(u=>u.id===c.collectionId);if(!l)return a.json({code:"storage.collection_not_found",message:"\u96C6\u5408\u4E0D\u5B58\u5728\u3002"},404);if(!Po(a,c))return a.json({code:"storage.region_scope_mismatch",message:"\u6240\u9009\u533A\u57DF\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE\u3002"},400);try{let u=await ht({...Pt(),userId:c.adminId,authScope:"admin",roles:[...c.roles],regionContext:a.get("regionContext")},()=>a.get("cloudStorage").collection(l).list({cursor:c.cursor,limit:c.limit}));return a.json({data:{objects:u.objects.map(d=>({id:d.ref.objectId,ownerId:d.ownerId,size:d.size,contentType:d.contentType,createdAt:d.createdAt})),cursor:u.cursor}},200)}catch(u){if(!(u instanceof W))throw u;return u.code==="storage.forbidden"?a.json({code:u.code,message:"\u96C6\u5408\u89C4\u5219\u4E0D\u5141\u8BB8\u5F53\u524D\u7BA1\u7406\u5458\u67E5\u770B\u6587\u4EF6\u5217\u8868\u3002"},403):u.code==="storage.request_invalid"?a.json({code:u.code,message:"\u5217\u8868\u53C2\u6570\u65E0\u6548\u3002"},400):a.json({code:"storage.directory_unavailable",message:"\u6587\u4EF6\u76EE\u5F55\u6682\u65F6\u4E0D\u53EF\u7528\u3002"},503)}}),n=be(ae({method:"POST",path:"/_internal/cloud-storage/objects/delete",accessLevel:"public",internalPolicy:ps,request:{body:B({collectionId:N(),objectId:N().uuid(),region:We(["cn","global"]),adminId:N().min(1),roles:qe(N())})},responses:{200:{schema:B({data:B({deleted:Ie(!0)})})},400:{schema:je},403:{schema:je},404:{schema:je},503:{schema:je}}}),async(a,{body:c})=>{let l=t.find(u=>u.id===c.collectionId);if(!l)return a.json({code:"storage.collection_not_found",message:"\u96C6\u5408\u4E0D\u5B58\u5728\u3002"},404);if(!Po(a,c))return a.json({code:"storage.region_scope_mismatch",message:"\u6240\u9009\u533A\u57DF\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE\u3002"},400);try{return await ht({...Pt(),userId:c.adminId,authScope:"admin",roles:[...c.roles],regionContext:a.get("regionContext")},()=>a.get("cloudStorage").collection(l).delete({projectId:String(a.get("projectId")),projectEnvKey:String(a.get("projectEnvKey")),extensionId:String(a.get("extensionId")),region:c.region,collectionId:c.collectionId,objectId:c.objectId})),a.json({data:{deleted:!0}},200)}catch(u){if(!(u instanceof W))throw u;return u.code==="storage.forbidden"?a.json({code:u.code,message:"\u96C6\u5408\u89C4\u5219\u4E0D\u5141\u8BB8\u5F53\u524D\u7BA1\u7406\u5458\u5220\u9664\u6B64\u6587\u4EF6\u3002"},403):u.code==="storage.object_not_found"?a.json({code:u.code,message:"\u6587\u4EF6\u4E0D\u5B58\u5728\u3002"},404):a.json({code:"storage.delete_unavailable",message:"\u6587\u4EF6\u5220\u9664\u672A\u5B8C\u6210\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"},503)}}),s=be(ae({method:"POST",path:"/_internal/cloud-storage/objects/download",accessLevel:"public",internalPolicy:ps,request:{body:B({collectionId:N(),objectId:N().uuid(),region:We(["cn","global"]),adminId:N().min(1),roles:qe(N())})},responses:{200:{schema:B({data:B({request:B({url:N(),method:Ie("GET"),headers:Er(N(),N()),expiresAt:pe()})})})},400:{schema:je},403:{schema:je},404:{schema:je},503:{schema:je}}}),async(a,{body:c})=>{let l=t.find(u=>u.id===c.collectionId);if(!l)return a.json({code:"storage.collection_not_found",message:"\u96C6\u5408\u4E0D\u5B58\u5728\u3002"},404);if(!Po(a,c))return a.json({code:"storage.region_scope_mismatch",message:"\u6240\u9009\u533A\u57DF\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE\u3002"},400);try{let u=await ht({...Pt(),userId:c.adminId,authScope:"admin",roles:[...c.roles],regionContext:a.get("regionContext")},()=>a.get("cloudStorage").collection(l).createDownload({projectId:String(a.get("projectId")),projectEnvKey:String(a.get("projectEnvKey")),extensionId:String(a.get("extensionId")),region:c.region,collectionId:c.collectionId,objectId:c.objectId}));return a.header("cache-control","private, no-store"),a.json({data:{request:{...u,method:"GET"}}},200)}catch(u){if(!(u instanceof W))throw u;return u.code==="storage.forbidden"?a.json({code:u.code,message:"\u96C6\u5408\u89C4\u5219\u4E0D\u5141\u8BB8\u5F53\u524D\u7BA1\u7406\u5458\u4E0B\u8F7D\u6B64\u6587\u4EF6\u3002"},403):u.code==="storage.object_not_found"?a.json({code:u.code,message:"\u6587\u4EF6\u4E0D\u5B58\u5728\u3002"},404):a.json({code:"storage.download_unavailable",message:"\u6587\u4EF6\u4E0B\u8F7D\u672A\u5B8C\u6210\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"},503)}}),o=B({collectionId:N(),region:We(["cn","global"]),adminId:N().min(1),roles:qe(N())}),i=be(ae({method:"POST",path:"/_internal/cloud-storage/objects/upload",accessLevel:"public",internalPolicy:ps,request:{body:pn("action",[o.extend({action:Ie("create"),size:pe().int().min(0),contentType:N(),input:dn().optional()}),o.extend({action:Ie("resume"),objectId:N().uuid()}),o.extend({action:Ie("complete"),objectId:N().uuid()})])},responses:{200:{schema:B({data:fn([B({objectId:N().uuid(),request:B({url:N(),method:Ie("PUT"),headers:Er(N(),N()),expiresAt:pe()})}),B({objectId:N().uuid(),size:pe(),contentType:N()})])})},400:{schema:je},403:{schema:je},404:{schema:je},409:{schema:je},503:{schema:je}}}),async(a,{body:c})=>{let l=t.find(u=>u.id===c.collectionId);if(!l)return a.json({code:"storage.collection_not_found",message:"\u96C6\u5408\u4E0D\u5B58\u5728\u3002"},404);if(!Po(a,c))return a.json({code:"storage.region_scope_mismatch",message:"\u6240\u9009\u533A\u57DF\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE\u3002"},400);a.header("cache-control","private, no-store");try{return await ht({...Pt(),userId:c.adminId,authScope:"admin",roles:[...c.roles],regionContext:a.get("regionContext")},async()=>{let u=a.get("cloudStorage").collection(l),d={projectId:String(a.get("projectId")),projectEnvKey:String(a.get("projectEnvKey")),extensionId:String(a.get("extensionId")),region:c.region,collectionId:c.collectionId,objectId:"objectId"in c?c.objectId:""};if(c.action==="complete"){let g=await u.completeUpload(d);return a.json({data:{objectId:g.ref.objectId,size:g.size,contentType:g.contentType}},200)}let p=c.action==="create"?await u.createUpload(c):await u.resumeUpload(d);return a.json({data:{objectId:p.object.ref.objectId,request:{...p.request,method:"PUT"}}},200)})}catch(u){if(!(u instanceof W))throw u;return u.code==="storage.forbidden"?a.json({code:u.code,message:"\u96C6\u5408\u89C4\u5219\u4E0D\u5141\u8BB8\u5F53\u524D\u7BA1\u7406\u5458\u4E0A\u4F20\u6587\u4EF6\u3002"},403):u.code==="storage.object_not_found"?a.json({code:u.code,message:"\u6587\u4EF6\u4E0D\u5B58\u5728\u3002"},404):["storage.upload_invalid","storage.request_invalid"].includes(u.code)?a.json({code:u.code,message:"\u6587\u4EF6\u5927\u5C0F\u3001\u7C7B\u578B\u6216\u53C2\u6570\u4E0D\u7B26\u5408\u96C6\u5408\u8981\u6C42\u3002"},400):["storage.upload_incomplete","storage.object_receipt_invalid","storage.object_not_uploading","storage.object_state_conflict"].includes(u.code)?a.json({code:u.code,message:"\u6587\u4EF6\u4E0A\u4F20\u5C1A\u672A\u5B8C\u6210\u6216\u5185\u5BB9\u4E0D\u7B26\u5408\u6388\u6743\u3002"},409):a.json({code:"storage.upload_unavailable",message:"\u6587\u4EF6\u4E0A\u4F20\u6682\u65F6\u4E0D\u53EF\u7528\u3002"},503)}});return[e,r,n,s,i,sf(t)]}function Po(t,e){let r=t.get("projectRegionPolicy");return!r||!r.splitRegions&&e.region!==r.homeRegion?!1:(t.set("userId",e.adminId),t.set("roles",[...e.roles]),t.set("regionContext",{region:e.region,source:"admin-selection",detection:{status:"unknown",region:null,countryCode:null,source:"unavailable"}}),!0)}var Xh=new WeakSet;function cf(t){return Xh.has(t)}function ms({actor:t,object:e}){return t.kind==="account"&&e.ownerId===t.id}var eg=Object.freeze({ownerPrivate(){return{create:ms,read:ms,delete:ms,list:({actor:t})=>t.kind==="account"?{ownerId:t.id}:null}},ownerWritePublicRead(){return{create:ms,read:()=>!0,delete:ms}}});function jr(t){let e;try{e=JSON.stringify(t)}catch{throw new W("storage.binding_invalid")}if(e===void 0||new TextEncoder().encode(e).length>8192)throw new W("storage.binding_invalid");let r=n=>{if(n&&typeof n=="object"){for(let s of Object.values(n))r(s);Object.freeze(n)}return n};return r(JSON.parse(e))}var dc=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u;function lf(t,e){let r=new Map;for(let n of e)(!cf(n)||r.has(n.id))&&te("collection_invalid"),r.set(n.id,n);return Object.freeze({describeUsage:()=>r.size?t.directory().usage():Promise.resolve([]),describeCollections:()=>[...r.values()].map(n=>({id:n.id,upload:{maxBytes:n.upload.maxBytes,contentTypes:[...n.upload.contentTypes]},operations:Object.keys(n.permissions).filter(s=>typeof n.permissions[s]=="function")})),collection(n){r.get(n.id)!==n&&te("collection_not_declared");let s=()=>t.current(),o=async(d,p)=>{let{actor:g}=s(),w=n.permissions[d];(!w||await w(Object.freeze({actor:Object.freeze({...g}),object:p,context:t.context()}))!==!0)&&te("forbidden"),s()},i=async d=>{let{scope:p}=s();(!d||Object.keys(p).some(w=>d[w]!==p[w])||d.collectionId!==n.id||!dc.test(d.objectId))&&te("object_scope_mismatch");let g=await t.directory().get(p.region,n.id,d.objectId);return g||te("object_not_found"),g},a=async d=>{let p=await i(d);return await o("read",p),p.state!=="ready"&&te("object_not_ready"),p},c=async d=>{let{scope:p,actor:g}=s();(!Number.isSafeInteger(d.size)||d.size<0||d.size>n.upload.maxBytes||!n.upload.contentTypes.includes(d.contentType))&&te("upload_invalid");let w=n.resolveBinding?await n.resolveBinding(d.input,t.context()):null,b=jr({ref:{...p,collectionId:n.id,objectId:t.createId()},ownerId:g.kind==="account"?g.id:null,binding:w,size:d.size,contentType:d.contentType,createdAt:t.now(),state:"uploading",etag:null});return dc.test(b.ref.objectId)||te("object_identity_invalid"),await o("create",b),b},l=d=>t.sign(d.map(p=>({key:Tr(p),method:"PUT",size:p.size,contentType:p.contentType,ifAbsent:!0})),t.now()+15*6e4),u=async d=>{let[p]=await l([d]);return{object:d,request:p}};return Object.freeze({async createUpload(d){let p=await c(d),g=await u(p);return await t.directory().insert(p),g},async createUploads(d){(!d.length||d.length>64)&&te("upload_invalid");let p=[];for(let w of d)p.push(await c(w));let g=await l(p);return g.length!==p.length&&te("operation_unavailable"),await t.directory().insertBatch(p),p.map(({ref:w},b)=>({ref:w,request:g[b]}))},async resumeUpload(d){let p=await i(d);return await o("create",p),p.state!=="uploading"&&te("object_not_uploading"),u(p)},async completeUpload(d){let p=await i(d);if(await o("create",p),p.state==="ready")return p;p.state!=="uploading"&&te("object_not_uploading");let g=await t.storage().head(Tr(p));if(g||te("upload_incomplete"),(g.size!==p.size||g.contentType!==p.contentType||!g.etag)&&te("object_receipt_invalid"),!await t.directory().transition(p,"ready",g.etag)){let b=await i(d);if(b.state==="ready"&&b.etag===g.etag)return b;te("object_state_conflict")}return jr({...p,state:"ready",etag:g.etag})},async put(d){let p=typeof d.body=="string"?new TextEncoder().encode(d.body):d.body;p instanceof Uint8Array||te("upload_invalid");let g=await c({...d,size:p.byteLength}),w=t.directory(),b=t.storage();await w.insert(g);let E=await b.put({key:Tr(g),body:p,size:p.byteLength,contentType:d.contentType,condition:{kind:"if-absent"},signal:d.signal});return E.status!=="written"&&te("object_conflict"),(E.object.key!==Tr(g)||E.object.size!==g.size||E.object.contentType!==g.contentType||!E.object.etag)&&te("object_receipt_invalid"),await w.transition(g,"ready",E.object.etag)||te("object_state_conflict"),jr({...g,state:"ready",etag:E.object.etag})},head:a,async createDownload(d){let p=await a(d),[g]=await t.sign([{key:Tr(p),method:"GET"}],t.now()+5*6e4);return g},async get(d,p){let g=await a(d),w=await t.storage().get(Tr(g),p);return w||te("object_not_found"),(w.object.etag!==g.etag||w.object.size!==g.size||w.object.contentType!==g.contentType)&&(await w.body.cancel(),te("object_changed")),{object:g,body:w.body}},async delete(d){let p=await i(d);if(await o("delete",p),p.state==="deleted")return;let g=t.directory();p.state==="ready"&&(await g.transition(p,"deleting")||te("object_state_conflict"),p=jr({...p,state:"deleting"})),p.state!=="deleting"&&te("object_not_ready"),await t.storage().delete(Tr(p)),await g.transition(p,"deleted")||(await g.get(p.ref.region,p.ref.collectionId,p.ref.objectId))?.state!=="deleted"&&te("object_state_conflict")},async list(d={}){let{scope:p,actor:g}=s(),w=n.permissions.list,b=w?await w(Object.freeze({actor:Object.freeze({...g}),context:t.context()})):null;s(),rg(b)||te("forbidden");let E=d.limit??50;(!Number.isSafeInteger(E)||E<1||E>100||d.cursor!==void 0&&!dc.test(d.cursor))&&te("request_invalid");let S=await t.directory().list({region:p.region,collectionId:n.id,scope:b,after:d.cursor??null,limit:E+1}),k=S.slice(0,E);return{objects:k,cursor:S.length>E?k.at(-1).ref.objectId:null}}})}})}function rg(t){return!!t&&Object.keys(t).length===1&&("ownerId"in t&&typeof t.ownerId=="string"&&!!t.ownerId||"all"in t&&t.all===!0)}function Tr(t){return`collections/${t.ref.collectionId}/${t.ref.objectId}`}function te(t){throw new W(`storage.${t}`)}function uf(t){let e,r=()=>e??=t.execute({type:"applyMigration",migrationId:"cloud-storage-objects-v1",statements:[`CREATE TABLE IF NOT EXISTS CloudStorageObject (region TEXT NOT NULL, collection_id TEXT NOT NULL,
32
+ object_id TEXT NOT NULL, owner_id TEXT, state TEXT NOT NULL, etag TEXT, payload TEXT NOT NULL,
33
+ PRIMARY KEY (region, collection_id, object_id))`,"CREATE INDEX IF NOT EXISTS CloudStorageOwnerList ON CloudStorageObject(region, collection_id, state, owner_id, object_id)"]}),n=async(i,a)=>{await r();let c=await t.execute({type:"query",statement:{sql:i,params:a,method:"all"}});if(!Array.isArray(c.rows))throw new W("storage.directory_invalid");return c.rows},s=i=>{try{let a=JSON.parse(String(i.payload));if(!["uploading","ready","deleting","deleted"].includes(String(i.state))||i.etag!==null&&typeof i.etag!="string"||!a.ref||!a.ref.objectId||!Number.isSafeInteger(a.size))throw new Error;return jr({...a,state:i.state,etag:i.etag})}catch{throw new W("storage.directory_invalid")}},o=i=>({method:"run",sql:"INSERT INTO CloudStorageObject(region, collection_id, object_id, owner_id, state, etag, payload) VALUES (?,?,?,?,?,?,?)",params:[i.ref.region,i.ref.collectionId,i.ref.objectId,i.ownerId,i.state,i.etag,JSON.stringify(i)]});return{async usage(){return(await n(`SELECT region, collection_id, state, COUNT(*) AS object_count,
34
+ SUM(json_extract(payload, '$.size')) AS object_bytes FROM CloudStorageObject
35
+ WHERE state IN ('uploading','ready','deleting') GROUP BY region, collection_id, state`,[])).map(a=>({region:a.region,collectionId:String(a.collection_id),state:a.state,count:Number(a.object_count),bytes:Number(a.object_bytes)}))},async insert(i){await r(),await t.execute({type:"query",statement:o(i)})},async insertBatch(i){await r(),await t.execute({type:"transactionBatch",statements:i.map(o)})},async get(i,a,c){let l=await n("SELECT payload, state, etag FROM CloudStorageObject WHERE region=? AND collection_id=? AND object_id=?",[i,a,c]);return l.length?s(l[0]):null},async transition(i,a,c=i.etag){return(await n("UPDATE CloudStorageObject SET state=?, etag=? WHERE region=? AND collection_id=? AND object_id=? AND state=? RETURNING object_id",[a,c,i.ref.region,i.ref.collectionId,i.ref.objectId,i.state])).length===1},async list(i){let a="ownerId"in i.scope?i.scope.ownerId:null;return(await n(`SELECT payload, state, etag FROM CloudStorageObject WHERE region=? AND collection_id=? AND state='ready'
36
+ AND object_id>? ${a===null?"":"AND owner_id=?"} ORDER BY object_id ASC LIMIT ?`,[i.region,i.collectionId,i.after??"",...a===null?[]:[a],i.limit])).map(s)}}}function df(t){let e=Object.freeze({...t.scope}),r=(s=!1)=>{let o=t.readContext();if(!o||o.projectId!==Number(e.projectId)||o.projectEnvKey!==e.projectEnvKey||o.extensionId!==e.extensionId||!Pe(o.regionContext?.region))throw new W("storage.outside_request");s?Xd(t.context,e):Oo(t.context,"objects",o.regionContext.region);let i=o.userId&&o.authScope?{kind:o.authScope,id:o.userId}:{kind:"anonymous"};return{scope:{...e,region:o.regionContext.region},actor:i}},n;return lf({current:r,directory(){if(r(!0),!n){let s=en(t.bindings);if(!s)throw new W("storage.directory_not_configured");let o=It({projectId:Number(e.projectId),projectEnvKey:e.projectEnvKey,extensionId:e.extensionId,databaseName:"cloud-storage-v1"});n=uf(Bn(s.get(s.idFromName(o))))}return n},storage(){return Oo(t.context,"objects",r().scope.region)},sign(s,o){return Oo(t.context,"objects",r().scope.region).sign(s,o)},context(){return r(),t.context},createId:hu,now:Date.now},t.collections)}function Rr(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}function ng(t){let e=t.replaceAll("-","+").replaceAll("_","/").padEnd(Math.ceil(t.length/4)*4,"="),r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.charCodeAt(s);return n}function ff(t){let e=new TextDecoder,r=ng(t);return JSON.parse(e.decode(r))}function fc(){let t=new Uint8Array(16);return crypto.getRandomValues(t),Rr(t)}var sg=300*1e3;async function Ar(t){let e=t.requestId??fc(),r=t.timestamp??String(Date.now()),n=t.nonce??fc(),s=await mf(t.bodyText??""),o=await pf({method:t.method,path:t.path,timestamp:r,nonce:n,contentSha256:s,caller:t.caller,secret:t.secret});return{"x-request-id":e,"x-internal-caller-project-id":Xr(t.caller.projectId),"x-internal-caller-project-env-key":Ut(t.caller.projectEnvKey),"x-internal-caller-extension-id":t.caller.extensionId,"x-internal-source-request-id":t.sourceRequestId??e,"x-internal-timestamp":r,"x-internal-nonce":n,"x-internal-content-sha256":s,"x-internal-signature":o}}async function pf(t){return await cg(ag({method:t.method,path:t.path,timestamp:t.timestamp,nonce:t.nonce,contentSha256:t.contentSha256,caller:t.caller}),t.secret)}async function No(t,e){let r=og(t),n=t.req.header("x-internal-timestamp"),s=t.req.header("x-internal-nonce"),o=t.req.header("x-internal-content-sha256"),i=t.req.header("x-internal-signature"),a=t.req.header("x-internal-source-request-id")??t.req.header("x-request-id")??"";if(!r||!n||!s||!o||!i)return{ok:!1,response:t.json({code:"runtime.internal_unauthorized",message:"Missing internal request signature."},401)};let c=Number(n);if(!Number.isFinite(c))return{ok:!1,response:t.json({code:"runtime.internal_unauthorized",message:"Invalid internal request timestamp."},401)};let l=e.maxSkewMs??sg;if(Math.abs(Date.now()-c)>l)return{ok:!1,response:t.json({code:"runtime.internal_unauthorized",message:"Internal request timestamp expired."},401)};let u=typeof t.req.text=="function"?await t.req.text():await t.req.raw.clone().text();if(await mf(u)!==o)return{ok:!1,response:t.json({code:"runtime.internal_unauthorized",message:"Internal request body hash mismatch."},401)};let p=new URL(t.req.raw.url),g=`${p.pathname}${p.search}`;return await pf({method:t.req.raw.method,path:g,timestamp:n,nonce:s,contentSha256:o,caller:r,secret:e.secret})!==i?{ok:!1,response:t.json({code:"runtime.internal_unauthorized",message:"Invalid internal request signature."},401)}:e.allowedCallers?.length&&!e.allowedCallers.some(b=>ig(r,b))?{ok:!1,response:t.json({code:"runtime.internal_forbidden",message:"Internal caller is not allowed."},403)}:{ok:!0,caller:r,sourceRequestId:a}}function og(t){let e=le(t.req.header("x-internal-caller-project-id")),r=Y(t.req.header("x-internal-caller-project-env-key")),n=t.req.header("x-internal-caller-extension-id");return!e||!n?null:{projectId:e,projectEnvKey:r,extensionId:n}}function ig(t,e){return!(e.projectId&&e.projectId!==t.projectId||e.projectEnvKey&&Y(e.projectEnvKey)!==t.projectEnvKey||e.extensionId&&e.extensionId!==t.extensionId)}function ag(t){return[t.method.toUpperCase(),t.path,t.timestamp,t.nonce,t.contentSha256,String(t.caller.projectId),Y(t.caller.projectEnvKey),t.caller.extensionId].join(`
37
+ `)}async function mf(t){let e=new TextEncoder,r=await crypto.subtle.digest("SHA-256",e.encode(t));return Rr(new Uint8Array(r))}async function cg(t,e){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=await crypto.subtle.sign("HMAC",n,r.encode(t));return Rr(new Uint8Array(s))}var hf="traceparent",gf="x-kuafu-trace-hop",Co="x-kuafu-trace-signature";async function pc(t){let{request:e,source:r}=t,n=e.headers,s=t.env&&typeof t.env=="object"?t.env:{},o=s.INTERNAL_API_SIGNING_KEY,i=s.PLATFORM_GATEWAY_INGRESS_TOKEN;if(n.has("x-platform-trace-id")||n.has("x-platform-upstream-span-id")){if(!r||typeof i!="string"||!i||n.get("x-kuafu-gateway-ingress-token")!==i)return{status:"rejected_untrusted"};if(n.get("x-platform-project-id")!==r.projectId||n.get("x-platform-project-env-key")!==r.projectEnvKey||n.get("x-platform-product-id")!==r.productId)return{status:"rejected_scope"};let b=n.get("x-platform-trace-id")??"",E=n.get("x-platform-upstream-span-id")??"";return!/^(?!0+$)[a-f0-9]{32}$/u.test(b)||!/^(?!0+$)[a-f0-9]{16}$/u.test(E)||!/^gw_[0-9a-f-]{36}$/u.test(n.get("x-platform-request-id")??"")?{status:"rejected_format"}:{status:"gateway",context:{traceId:b,parentSpanId:E,hop:0}}}if(![hf,gf,Co].some(b=>n.has(b)))return{status:"none"};if(!r||typeof o!="string"||!o||typeof i!="string"||!i||n.get("x-kuafu-gateway-ingress-token")!==i||!n.has(Co))return{status:"rejected_untrusted"};let a=n.get(hf)??"",c=n.get(gf)??"",l=/^00-([0-9a-f]{32})-([0-9a-f]{16})-(00|01)$/u.exec(a),u=Number(c);if(!l||/^0{32}$/u.test(l[1])||/^0{16}$/u.test(l[2])||!/^[1-9][0-9]?$/u.test(c)||u>ls||!/^[a-zA-Z0-9_-]{43}$/u.test(n.get(Co)??""))return{status:"rejected_format"};let d=n.get("x-internal-caller-project-id"),p=n.get("x-internal-caller-project-env-key");if(d!==r.projectId||p!==r.projectEnvKey||!Number.isSafeInteger(Number(r.projectId)))return{status:"rejected_scope"};if(!/^[a-zA-Z0-9_-]{43}$/u.test(n.get("x-internal-signature")??""))return{status:"rejected_request"};let g={projectId:Number(r.projectId),projectEnvKey:r.projectEnvKey,extensionId:r.productId};if(await mc(a,c,g,n.get("x-internal-signature")??"",o)!==n.get(Co))return{status:"rejected_signature"};try{if(!(await No({req:{raw:e,header:E=>n.get(E)??void 0},get:()=>{},json:(E,S)=>new Response(JSON.stringify(E),{status:S})},{secret:o})).ok)return{status:"rejected_request"}}catch{return{status:"rejected_request"}}return{status:"inherited",context:{traceId:l[1],parentSpanId:l[2],sampled:l[3]==="01",hop:u}}}async function mc(t,e,r,n,s){let o=new TextEncoder,i=await crypto.subtle.importKey("raw",o.encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=["kuafu.server-trace.v1",t,e,String(r.projectId),r.projectEnvKey,r.extensionId,n].join(`
38
+ `);return Rr(new Uint8Array(await crypto.subtle.sign("HMAC",i,o.encode(a))))}var lg="traceparent",ug="x-kuafu-trace-hop",dg="x-kuafu-trace-signature";async function hc(t){let e=Hd(t.caller,t.target);if(!e)return{};let r=`00-${e.traceId}-${e.parentSpanId}-${e.sampled?"01":"00"}`,n=String(e.hop),s=await mc(r,n,t.target,t.signedHeaders["x-internal-signature"],t.secret);return{[lg]:r,[ug]:n,[dg]:s}}var yf="kuafucloud_local_internal_api_signing_key",fg="x-kuafu-gateway-ingress-token";function Nt(t){let e=hn(t,"INTERNAL_API_SIGNING_KEY");if(e)return e;if(!$t(t))throw new Error("INTERNAL_API_SIGNING_KEY is required in a Platform Product Worker.");return yf}function ko(t){return hn(t,"PROJECT_INTERNAL_SIGNING_KEY")||Nt(t)}function gc(t){let e=t?.RUNTIME_INTERNAL_RPC;return typeof e=="function"?e:null}function pg(t){let e=t?.PLATFORM_SYSTEM_SERVICE;return e&&typeof e=="object"&&"fetch"in e&&typeof e.fetch=="function"?e:null}function bf(t){let e=t?.PLATFORM_GATEWAY_SERVICE;return e&&typeof e=="object"&&"fetch"in e&&typeof e.fetch=="function"?e:null}function mg(t){return`https://platform-internal${Or(t)}`}function Or(t){return Do("system",t)}function Do(t,e){let r=e.startsWith("/")?e:`/${e}`;return`/api/${t}${r}`}function wf(t){return vf({...t,extensionId:"system"})}function vf(t){return or({projectId:t.projectId,projectEnvKey:t.projectEnvKey,extensionId:t.extensionId},t.path)}async function xf(t){t.signal?.throwIfAborted();let e=new Headers(t.headers);Sf(e,t.env);let r=Y(t.projectEnvKey);e.has("x-project-id")||e.set("x-project-id",Xr(t.projectId)),e.has("x-project-env-key")||e.set("x-project-env-key",Ut(r)),e.has("x-platform-project-env-key")||e.set("x-platform-project-env-key",Ut(r));let n=vf({projectId:t.projectId,projectEnvKey:r,extensionId:t.extensionId,path:t.path}),s=bf(t.env);if(s)return await yc(s,{apiPath:n,method:t.method,headers:e,body:t.body,...t.signal?{signal:t.signal}:{}});let o=gc(t.env);if(o)return await o({path:n,method:t.method,headers:Object.fromEntries(e.entries()),...typeof t.body=="string"?{body:t.body}:{},...t.signal?{signal:t.signal}:{}});let i=_f(t.env,t.request);if(!i)return null;try{return await fetch(`${i}${n}`,{method:t.method,headers:e,...typeof t.body=="string"?{body:t.body}:{},...t.signal?{signal:t.signal}:{}})}catch{return null}}function hg(t){let e=_f(t.env,t.request);return e?`${e}${wf({projectId:t.projectId,projectEnvKey:t.projectEnvKey,path:t.path})}`:""}function _f(t,e){let r=hn(t,"RUNTIME_INTERNAL_ORIGIN")||hn(t,"PLATFORM_GATEWAY_ENDPOINT")||hn(t,"KUAFUCLOUD_DEVMANAGER_ORIGIN");if(r)return gg(r);if(e)try{let n=new URL(e.url);return yg(n.hostname)?"":`${n.protocol}//${n.host}`}catch{}return""}function hn(t,e){let r=t?.[e];return typeof r=="string"?r.trim():""}function Sf(t,e){let r=hn(e,"PLATFORM_GATEWAY_INGRESS_TOKEN");r&&t.set(fg,r)}function gg(t){return t.replace(/\/+$/u,"")}function yg(t){return t==="platform-internal"||t==="cloud-manager.internal"}async function hs(t){let e=new Headers(t.headers);Sf(e,t.env);let r=Y(t.projectEnvKey);Number.isInteger(t.projectId)&&!e.has("x-project-id")&&e.set("x-project-id",Xr(t.projectId)),e.has("x-project-env-key")||e.set("x-project-env-key",Ut(r)),e.has("x-platform-project-env-key")||e.set("x-platform-project-env-key",Ut(r));let n=wf({projectId:t.projectId,projectEnvKey:r,path:t.path}),s=bf(t.env);if(t.preferGateway===!0){if(s)return await yc(s,{apiPath:n,method:t.method,headers:e,body:t.body});let c=gc(t.env);return c?await c({path:n,method:t.method,headers:Object.fromEntries(e.entries()),...typeof t.body=="string"?{body:t.body}:{}}):null}let o=pg(t.env);if(o){let c=new Request(mg(t.path),{method:t.method,headers:e,...typeof t.body=="string"?{body:t.body}:{}});try{return await o.fetch(c)}catch{return null}}let i=gc(t.env);if(i)return await i({path:n,method:t.method,headers:Object.fromEntries(e.entries()),...typeof t.body=="string"?{body:t.body}:{}});if(s)return await yc(s,{apiPath:n,method:t.method,headers:e,body:t.body});let a=hg({env:t.env,request:t.request,projectId:t.projectId,projectEnvKey:r,path:t.path});if(!a)return null;try{return await fetch(a,{method:t.method,headers:e,...typeof t.body=="string"?{body:t.body}:{}})}catch{return null}}async function yc(t,e){let r=new Request(`https://platform-internal${e.apiPath}`,{method:e.method,headers:e.headers,...typeof e.body=="string"?{body:e.body}:{},...e.signal?{signal:e.signal}:{}});try{return await t.fetch(r)}catch{return null}}async function Ef(t){let e=t.target.extensionId==="developer"&&t.path.startsWith("/internal/monitoring/"),r=async()=>{let n=t.body===void 0?void 0:JSON.stringify(t.body),s=await Ar({method:t.method,path:Do(t.target.extensionId,t.path),...n===void 0?{}:{bodyText:n},caller:t.caller,secret:t.signingSecret??Nt(t.env)}),o=e?{}:await hc({caller:t.caller,target:t.target,secret:t.signingSecret??Nt(t.env),signedHeaders:s});return await xf({env:t.env,request:t.request,...t.target,path:t.path,method:t.method,...t.signal?{signal:t.signal}:{},headers:{...n===void 0?{}:{"content-type":"application/json"},...s,...o},...n===void 0?{}:{body:n}})};return e?r():lc(t.target.extensionId,t.method,!1,r)}function bc(t,e,r){if(!t||typeof t!="object"||!e.extensionId||!e.version)return null;let n=t,s=String(n.PLATFORM_PROJECT_ID??""),o=String(n.PLATFORM_PROJECT_ENV_KEY??"");return!/^\d{1,20}$/u.test(s)||!/^[a-zA-Z0-9_-]{1,64}$/u.test(o)||n.PLATFORM_EXTENSION_ID!==e.extensionId?null:{projectId:s,projectEnvKey:o,productId:e.extensionId,productRelease:e.version,runtime:"server",requestId:r,userId:null,routeTemplate:null}}function wc(t){let e=t.env;if(!e||e.MONITOR_PROVIDER_MODE===void 0||e.MONITOR_PROVIDER_MODE==="disabled"||e.MONITOR_CAPTURE_MODE==="disabled"||t.entry==="background"&&t.source?.productId==="developer"||t.request&&new URL(t.request.url).pathname.startsWith("/api/developer/internal/monitoring/"))return;let r=e.MONITOR_TRACE_SAMPLE_RATE,n=typeof r=="number"?r:typeof r=="string"&&/^(?:0(?:\.\d+)?|1(?:\.0+)?)$/u.test(r)?Number(r):NaN;if(e.MONITOR_PROVIDER_MODE!=="cloudflare"||!t.source||e.MONITOR_CAPTURE_MODE!==void 0&&e.MONITOR_CAPTURE_MODE!=="enabled"||typeof e.MONITOR_SOURCE_GRANT_ID!="string"||!/^monitor-[0-9a-f]{64}$/u.test(e.MONITOR_SOURCE_GRANT_ID)||!Number.isFinite(n)||n<0||n>1)return;let s=Fc(e.MONITOR_SOURCE_GRANT_ID);return{traceSampleRate:n,recordDroppedError:o=>s.recordDroppedError(o),async acceptError(o){if(!s(o))throw new Error("monitor.log_not_emitted");return{eventId:o.eventId,emittedAt:new Date().toISOString()}},async acceptTrace(o){if(!s(o))throw new Error("monitor.log_not_emitted")}}}var gs=new WeakMap;function If(t){t&&(gs.has(t)||gs.set(t,new Map))}function vc(t,e,r){if(!t||!e||!Number.isFinite(r)||r<0)return;let n=_g(t),s=Sg(e),o=n.get(s);if(o){o.durationMs+=r,o.count+=1;return}n.set(s,{durationMs:r,count:1})}function vg(t){if(!t)return"";let e=gs.get(t);if(!e||e.size===0)return"";let r=[];for(let[n,s]of e.entries()){let o=`${n};dur=${s.durationMs.toFixed(1)}`;s.count>1?r.push(`${o};desc="count=${s.count}"`):r.push(o)}return r.join(", ")}function jf(t,e){let r=vg(t);r&&e.append("server-timing",r)}function Pr(t){let e=t.req?.raw;return e instanceof Request?e:null}function ys(){return typeof globalThis.performance<"u"?globalThis.performance.now():Date.now()}async function xg(t){try{return await t.run()}finally{vc(t.request,t.metricName,ys()-t.startMs)}}async function xc(t,e,r){let n=ys();return await xg({startMs:n,request:t,metricName:e,run:r})}function _g(t){let e=gs.get(t);if(e)return e;let r=new Map;return gs.set(t,r),r}function Sg(t){return t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"_")||"metric"}var _c="/runtime/auth/verify",Tf="/runtime/setting/read",Rf="/runtime/credential/read";var Eg="accountIdentityVerifier";async function Af(t,e,r=t.env){let n=e.requirePermissions;if(e.accessLevel==="public")return(n?.length??0)>0?t.json({code:"runtime.route_misconfigured",message:"Public routes cannot declare requirePermissions."},500):e.authScope!==void 0?t.json({code:"runtime.route_misconfigured",message:"Public routes cannot declare authScope."},500):null;if(e.authScope!=="admin"&&e.authScope!=="account")return t.json({code:"runtime.route_misconfigured",message:"Private/protected routes must declare authScope."},500);if(e.accessLevel==="protected"&&!n?.length)return t.json({code:"runtime.route_misconfigured",message:"Protected routes must declare requirePermissions."},500);if(e.accessLevel==="protected"&&e.authScope!=="admin")return t.json({code:"runtime.route_misconfigured",message:"Protected routes must declare authScope=admin."},500);if(e.accessLevel==="private"&&n?.length)return t.json({code:"runtime.route_misconfigured",message:"requirePermissions can only be used on protected routes."},500);let s=t.req.header("authorization"),o=Og(s);if(!o)return t.json({code:"runtime.unauthenticated",message:"Authentication required."},401);let i=String(t.get("extensionId")??""),a=le(t.get("projectId"))??Ye,c=Y(t.get("projectEnvKey")),l=i==="center",u=l?Pg(o,{projectId:a,projectEnvKey:c}):{projectId:a,projectEnvKey:c},d=Pr(t),p=e.accessLevel==="protected"?"protected":"private",g=e.authScope,w=await xc(d,"auth_remote",async()=>await Nf({req:t.req,env:r,request:d,verificationProjectId:u.projectId,verificationProjectEnvKey:u.projectEnvKey,requestProjectId:a,requestProjectEnvKey:c,callerExtensionId:i,credential:o,accessLevel:p,authScope:g,requiredPermissions:(n??[]).map(b=>b.key),allowCrossProjectToken:l}));return w.ok?(t.set("userId",w.data.userId),t.set("roles",w.data.roles),w.data.extra&&t.set("extra",w.data.extra),t.set("regionContext",ws({policy:Dt(t.get("projectRegionPolicy")),accountRegion:w.data.extra?.serviceRegion})),null):t.json({code:w.error.code,message:w.error.message},w.error.status)}function Of(t,e){return async r=>await Ig(t,r,e)}function Pf(t,e){t.set(Eg,e)}async function Ig(t,e,r){let n=Pr({req:t.req??null}),s=le(t.get("projectId"))??Ye,o=Y(t.get("projectEnvKey")),i=String(t.get("extensionId")??""),a=await xc(n,"auth_remote",async()=>await Nf({req:t.req??null,env:r,request:n,verificationProjectId:s,verificationProjectEnvKey:o,requestProjectId:s,requestProjectEnvKey:o,callerExtensionId:i,credential:{kind:"bearer",token:e},accessLevel:"private",authScope:"account",requiredPermissions:[],allowCrossProjectToken:!1}));if(!a.ok)return{ok:!1,response:t.json({code:a.error.code,message:a.error.message},a.error.status)};let c=Cf(e),l=le(c?.accountProjectId),u=Y(c?.accountProjectEnvKey);return!c||c.typ!=="account-identity"||c.iss!=="system"||typeof c.sub!="string"||typeof c.jti!="string"||typeof c.iat!="number"||typeof c.exp!="number"||l===null||u!==o?{ok:!1,response:t.json({code:"runtime.unauthenticated",message:"Invalid account identity token."},401)}:{ok:!0,payload:{...c,accountProjectId:l,accountProjectEnvKey:u}}}async function Nf(t){let e=t.req?.header("x-request-id")??"",r=JSON.stringify({credentialType:t.credential.kind==="bearer"?"bearer":"access-key",...t.credential.kind==="bearer"?{token:t.credential.token}:{keyId:t.credential.keyId,secret:t.credential.secret},accessLevel:t.accessLevel,authScope:t.authScope,requiredPermissions:t.requiredPermissions,requestProjectId:t.requestProjectId,requestProjectEnvKey:Y(t.requestProjectEnvKey),allowCrossProjectToken:t.allowCrossProjectToken}),n=await Ar({method:"POST",path:Or(_c),bodyText:r,caller:{projectId:t.requestProjectId,projectEnvKey:t.requestProjectEnvKey,extensionId:t.callerExtensionId},secret:ko(t.env),...e?{requestId:e,sourceRequestId:e}:{}}),s=new Headers({"content-type":"application/json",...n}),o=await hs({env:t.env,request:t.request,projectId:t.verificationProjectId,projectEnvKey:t.verificationProjectEnvKey,path:_c,method:"POST",headers:s,body:r});if(!o)return{ok:!1,error:{status:502,code:"runtime.internal_unavailable",message:"System auth call failed."}};let i=await Tg(o);if(!o.ok){let d=gn(i?.code)||(o.status===401?"runtime.unauthenticated":"runtime.internal_error");return{ok:!1,error:{status:jg(o.status,d),code:d,message:gn(i?.message)||`System auth verify failed with status ${o.status}.`}}}let a=Rg(i),c=gn(a?.userId);if(!c)return{ok:!1,error:{status:500,code:"runtime.internal_error",message:"System auth verify returned invalid payload."}};let l=Array.isArray(a?.roles)?a.roles.filter(d=>typeof d=="string"):[],u=Ag(a?.extra);return{ok:!0,data:{userId:c,roles:l,...u?{extra:u}:{}}}}function jg(t,e){return e==="runtime.unauthenticated"||e==="runtime.token_expired"||e==="runtime.token_revoked"?401:t}async function Tg(t){try{return await t.json()}catch{return null}}function Rg(t){if(!t||typeof t!="object")return null;let e=t;if(!("data"in e))return null;let r=e.data;return!r||typeof r!="object"?null:r}function Ag(t){if(!t||typeof t!="object")return null;let e=t;if(e.tokenType!=="account")return null;let r=gn(e.email)??"",n=gn(e.displayName)??"",s=le(e.accountProjectId);return s===null?null:{tokenType:"account",email:r,displayName:n,accountProjectId:s,accountProjectEnvKey:gn(e.accountProjectEnvKey)??void 0,...Pe(e.serviceRegion)?{serviceRegion:e.serviceRegion}:{}}}function Og(t){if(!t)return null;let[e,r]=t.split(" "),n=e?.trim().toLowerCase(),s=r?.trim()??"";if(!n||!s)return null;if(n==="bearer")return{kind:"bearer",token:s};if(n==="accesskey"){let o=s.indexOf(".");if(o<=0||o>=s.length-1)return null;let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();return!i||!a?null:{kind:"access-key",keyId:i,secret:a}}return null}function Pg(t,e){if(t.kind!=="bearer")return e;let r=Cf(t.token);if(!r||r.iss!=="system")return e;let n=r.typ==="project-session"?le(r.projectId):r.typ==="account-identity"||r.typ==="account-refresh"?le(r.accountProjectId):null;if(n===null)return e;let s=r.typ==="project-session"?Y(r.projectEnvKey):Y(r.accountProjectEnvKey);return{projectId:n,projectEnvKey:s}}function Cf(t){let e=t.split(".");if(e.length!==3)return null;let r=e[1];if(!r)return null;try{return ff(r)}catch{return null}}function gn(t){if(typeof t!="string")return null;let e=t.trim();return e||null}function kf(t){let e=new Map,r=async n=>{let s=JSON.stringify(n),o=e.get(s);return o||(o=$f(t,Tf,{...n.key?{key:n.key}:{},...n.keys?{keys:[...n.keys]}:{},...n.productId?{productId:n.productId}:{}}).then(i=>{let a=Nr(Nr(i.data).settings);return Object.fromEntries(Object.entries(a).map(([c,l])=>[c,Nr(l).value]))}),e.set(s,o)),await o};return{async get(n,s){return Sc(n),(await r({key:n,...s}))[n]},async getMany(n,s){for(let o of n)Sc(o);return await r({keys:n,...s})},async snapshot(n){return await r({...n})}}}function Df(t){let e=new Map;return{async get(r,n){Sc(r);let s=n?.purpose??"runtime",o=`${s}:${r}`,i=e.get(o);return i||(i=$f(t,Rf,{key:r,purpose:s}).then(a=>Nr(Nr(a.data).payload)),e.set(o,i)),await i}}}async function $f(t,e,r){let n=JSON.stringify(r),s=await Ar({method:"POST",path:Or(e),bodyText:n,caller:{projectId:t.projectId,projectEnvKey:t.projectEnvKey,extensionId:t.extensionId},secret:Nt(t.env),...t.request?.headers.get("x-request-id")?{sourceRequestId:t.request.headers.get("x-request-id")}:{}}),o=await hs({env:t.env,request:t.request,projectId:t.projectId,projectEnvKey:t.projectEnvKey,path:e,method:"POST",headers:{"content-type":"application/json",...s},body:n});if(!o)throw new Error(`System service is unavailable for ${e}.`);let i=await Ng(o);if(!o.ok){let a=Nr(i).code;throw new Error(typeof a=="string"?a:`System request failed with ${o.status}.`)}return Nr(i)}function Sc(t){if(!t.trim()||t.includes("*"))throw new Error("A non-wildcard key is required.")}function Nr(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}async function Ng(t){try{return await t.json()}catch{return null}}function qf(){return async(t,e)=>{let r={env:t.env,request:Pr(t),projectId:le(t.get("projectId"))??Ye,projectEnvKey:Y(t.get("projectEnvKey")),extensionId:String(t.get("extensionId")??"")};return t.set("settingReader",kf(r)),t.set("credentialReader",Df(r)),Pf(t,Of(t,r.env)),await e()}}function Lf(t){if(!t||typeof t!="object")return"";let e=t.PLATFORM_WORKER_VERSION_METADATA;if(!e||typeof e!="object")return"";let r=e.id;return typeof r=="string"&&/^[a-zA-Z0-9-]{1,128}$/u.test(r)?r:""}function Mf(t,e){if(!t||typeof t!="object")return null;let r=t.PLATFORM_GATEWAY_INGRESS_TOKEN;if(typeof r!="string"||!r||e.get("x-kuafu-gateway-ingress-token")!==r)return null;let n=e.get("x-platform-request-id");return n&&/^gw_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u.test(n)?n:null}function zf(t={},e){return async(r,n)=>{let s=Mf(r.env,r.req.raw.headers)??$g(),o=Pr(r),i=ys();r.set("requestId",s),r.header("x-request-id",s),If(o);let a=bc(r.env,t,s),c=e??wc({env:r.env,request:r.req.raw,source:a}),l=await pc({env:r.env,request:r.req.raw,source:a});await ac({provider:c,requestId:s,method:r.req.method,incomingTrace:l,source:()=>a?{...a,userId:String(r.get("userId")??"")||null}:null,error:()=>r.error instanceof Kt?null:r.error,status:()=>r.res.status,...c&&Dg(r.env)?{defer:p=>r.executionCtx.waitUntil(p)}:{}},n),r.header("x-request-id",s),vc(o,"app_total",ys()-i),jf(o,r.res.headers),r.res.headers.delete("x-kuafu-product-release"),r.res.headers.delete("x-kuafu-api-route-template"),t.version&&r.header("x-kuafu-product-release",t.version);let u=r.get("apiRouteTemplate");typeof u=="string"&&r.header("x-kuafu-api-route-template",encodeURIComponent(u));let d=Lf(r.env);d&&r.header("x-kuafu-worker-version-id",d)}}function Dg(t){return!$t(t)}function $g(){return`req_${crypto.randomUUID()}`}var qg="x-kuafu-gateway-ingress-token";function Uf(){return async(t,e)=>{let r=!$t(t.env),n=Lg(t.env,"PLATFORM_GATEWAY_INGRESS_TOKEN");if(!r&&!n){await e();return}if(!n)return t.json({code:"runtime.gateway_ingress_not_configured",message:"Platform Gateway ingress credential is missing."},503);if((t.req.header(qg)?.trim()??"")!==n)return t.json({code:"runtime.gateway_ingress_unauthorized",message:"Extension API must be accessed through the platform Gateway."},403);await e()}}function Lg(t,e){if(!t||typeof t!="object")return"";let r=t[e];return typeof r=="string"?r.trim():""}function Bf(t){return async(e,r)=>{let n=new URL(e.req.raw.url).pathname,s=yu(n),o=le(e.req.header("x-project-id")),i=Kf(e.req.header("x-project-env-key")??e.req.header("x-platform-project-env-key")),a=Kf(e.env?.PLATFORM_PROJECT_ENV_KEY),c=o??s?.projectId??Ye,l=i??s?.projectEnvKey??a??Y(null),u=String(e.req.header("authorization")??""),d=e.env?.PLATFORM_PROJECT_REGION_POLICY,p=Dt(d===void 0?t.regionPolicy:d),g=ws({policy:p}),w=String(e.get("requestId")??"");e.set("extensionId",t.extensionId),e.set("projectId",c),e.set("projectEnvKey",l),e.set("accessKey",u),e.set("userId",""),e.set("roles",[]),e.set("projectRegionPolicy",p),e.set("regionContext",g);let b={};for(let[E,S]of e.req.raw.headers)b[E.toLowerCase()]=S;return ht({extensionId:t.extensionId,projectId:c,projectEnvKey:l,userId:"",accessKey:u,roles:[],regionContext:g,requestId:w,headers:b},()=>r())}}function Kf(t){if(!(typeof t!="string"||!t.trim()))return Y(t)}wo(y);function Wf(t){return zg(t)}function Mg(t,e){return async(r,n)=>{let s=r.env,o=Su(t)?s:wa(t,s);Wn.set(r,s);let i=s,a=i?.PLATFORM_PROJECT_ID!==void 0||i?.PLATFORM_PROJECT_ENV_KEY!==void 0,c=Object.freeze({extensionId:t,projectId:a?le(i?.PLATFORM_PROJECT_ID)??0:$o(r.get("projectId")),projectEnvKey:a?typeof i?.PLATFORM_PROJECT_ENV_KEY=="string"?i.PLATFORM_PROJECT_ENV_KEY:"":bs(r.get("projectEnvKey"))}),l=ef(r,{bindings:s,scope:{extensionId:c.extensionId,projectId:String(c.projectId),projectEnvKey:c.projectEnvKey},homeRegion:r.get("projectRegionPolicy")?.homeRegion,readRegion:()=>Pt()?.regionContext?.region});r.set("cloudStorage",df({context:r,bindings:s??{},collections:e,readContext:Pt,scope:{extensionId:c.extensionId,projectId:String(c.projectId),projectEnvKey:c.projectEnvKey}})),vu(r,c,(u,d)=>Ef({env:s,request:null,caller:u,target:{projectId:u.projectId,projectEnvKey:u.projectEnvKey,extensionId:d.extensionId},path:d.path,method:d.method,body:d.body})),r.env=o;try{await n()}finally{r.env=s,Wn.delete(r),po.delete(r),l()}}}function zg(t){let e=t.mountPath??Kg(t.config.extensionId),r=new oc,n=new oc;if(t.telemetry&&(!Number.isFinite(t.telemetry.traceSampleRate)||t.telemetry.traceSampleRate<0||t.telemetry.traceSampleRate>1))throw new Error("Server telemetry traceSampleRate must be between 0 and 1.");n.onError((s,o)=>s instanceof Kt?s.getResponse():(cc(s,String(o.get("requestId")??"")),o.text("Internal Server Error",500))),Ff(r),Ff(n),r.doc(`${e}/doc`,{openapi:"3.0.0",info:Ug(t.config)}),n.use("*",zf(t.config,t.telemetry)),n.use("*",Uf()),n.use("*",Bf(t.config)),n.get("/__kuafu/health",async s=>{let o=await xu({env:s.env,resolveScope:()=>({projectId:$o(s.get("projectId")),projectEnvKey:bs(s.get("projectEnvKey"))}),extensionId:t.config.extensionId});return s.json(o.body,o.status)}),Bg(t)&&n.use("*",Fg(t.config,t.tables,t.resolveDatabase)),n.use("*",qf()),n.use("*",Mg(t.config.extensionId,t.cloudCollections??[]));for(let s of t.middleware??[])n.use("*",s);for(let s of af(t.cloudCollections??[]))n.openapi(Qf(s.route),Vf(s));for(let s of t.apis){let o=Qf(s.route);n.openapi(o,Vf(s))}return r.route(e,n),r}function Ug(t){return{title:t.displayName??t.name??t.extensionId,version:t.version??"0.0.0",description:t.description}}function Ff(t){t.openAPIRegistry.registerComponent("securitySchemes","BearerAuth",{type:"http",scheme:"bearer",bearerFormat:"JWT"})}function Kg(t){return`/api/${t}`}function Bg(t){return!!t.tables||typeof t.resolveDatabase=="function"||t.apis.length>0}function Fg(t,e,r){return async(n,s)=>{let o=r?await r(n,{config:t,tables:e}):(()=>{if(!e)throw new Error(`Database schema (tables) is required for ${t.extensionId}`);let i=n.env,a=e,c=$o(n.get("projectId")),l=bs(n.get("projectEnvKey")),u="default";if(ba({env:i,projectEnvKey:l})==="postgres"){let E=Wg(i);if(!E)throw new Error(`PostgreSQL service binding ${ga} is required for ${t.extensionId}`);let S=pu(E,{projectId:c,projectEnvKey:l,extensionId:t.extensionId,databaseName:u});return mu(Gd(S),{schema:a})}let p=en(i);if(!p)throw new Error(`Durable Object binding ${Hr} is required for ${t.extensionId}`);let g=It({projectId:c,projectEnvKey:l,extensionId:t.extensionId,databaseName:u}),w=p.get(p.idFromName(g)),b=Bn(w);return Xl(Zd(b),{schema:a})})();n.set("db",o),await s()}}function Qf(t){let e={};t.request?.params&&(e.params=t.request.params),t.request?.query&&(e.query=t.request.query),t.request?.body&&(e.body={content:{"application/json":{schema:t.request.body}}});let r=t.responses&&Object.keys(t.responses).length>0?Object.fromEntries(Object.entries(t.responses).map(([s,o])=>{let i={description:o.description??`HTTP ${s}`};return"schema"in o&&o.schema&&(i.content={"application/json":{schema:o.schema}}),[s,i]})):{200:{description:"OK"}},n={method:t.method.toLowerCase(),path:Ec(t.path),summary:t.summary,description:t.description,tags:t.tags,responses:r,middleware:async(s,o)=>{s.set("apiRouteTemplate",Ec(t.path)),Wd(Ec(t.path)),await o()}};return Object.keys(e).length>0&&(n.request=e),t.accessLevel&&t.accessLevel!=="public"&&(n.security=[{BearerAuth:[]}],n["x-auth-scope"]=t.authScope),t.requirePermissions?.length&&(n["x-permissions"]=t.requirePermissions.map(s=>s.key)),Ud(n)}function Vf(t){return async e=>{let r=t.route.request?.body?await Qg(e,t.route.request.body):{ok:!0,data:{}};if(!r.ok)return e.json({code:"request.invalid",message:r.message},400);let n={param:t.route.request?.params?e.req.valid("param"):{},query:t.route.request?.query?e.req.valid("query"):{},body:t.route.request?.body?r.data:{}},s=Wn.get(e)??e.env,o=await Vg(e,t.route.internalPolicy,s);if(o)return o;let i=await Af(e,{accessLevel:t.route.accessLevel??"public",authScope:t.route.authScope,requirePermissions:t.route.requirePermissions},s);if(i)return i;let a={extensionId:String(e.get("extensionId")??""),projectId:$o(e.get("projectId")),projectEnvKey:bs(e.get("projectEnvKey")),userId:String(e.get("userId")??""),authScope:t.route.authScope,accessKey:String(e.get("accessKey")??""),roles:e.get("roles")??[],regionContext:e.get("regionContext"),requestId:String(e.get("requestId")??""),headers:Object.fromEntries(e.req.raw.headers.entries())};return ht(a,()=>t.handler(e,n))}}async function Qg(t,e){let r;try{r=await t.req.json()}catch{return{ok:!1,message:"Request body must be valid JSON."}}let n=await e.safeParseAsync(r);return n.success?{ok:!0,data:n.data}:{ok:!1,message:n.error.issues.map(s=>s.message).join("; ")}}async function Vg(t,e,r){if(!e?.internalOnly)return null;let n=e.auth??"signed";if(n!=="signed")return t.json({code:"runtime.route_misconfigured",message:`Unsupported internal auth mode "${n}".`},500);let s=e.authSecretBinding?String(r?.[e.authSecretBinding]??"").trim():e.allowCrossEnvironment?ko(r):Nt(r);if(!s)return t.json({code:"runtime.route_misconfigured",message:"Internal signing key is unavailable."},500);let o=await No(t,{secret:s});if(!o.ok)return o.response;let i=Eu(e,o.caller,{projectId:le(t.get("projectId")),projectEnvKey:bs(t.get("projectEnvKey"))});if(i)return t.json(i,403);let a=t.get("extra");return t.set("extra",{...a??{},internalCaller:o.caller,internalSourceRequestId:o.sourceRequestId}),null}function Ec(t){return(t.startsWith("/")?t:`/${t}`).replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function $o(t){return le(t)??Ye}function bs(t){return Y(typeof t=="string"?t:null)}function Wg(t){let e=t?.[ga];return!e||typeof e!="object"||typeof e.fetch!="function"?null:e}var Hg=j.string().regex(/^[a-z][a-z0-9_.-]{0,127}$/u),Jg=j.object({productId:j.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/u),productRelease:j.string().min(1).max(128),deploymentSurface:j.enum(["desktop-preview","app-hot-update","mini-program-release","site-web"]),runtimeVariant:j.enum(["desktop-simulator/web","app-simulator/web","app/ios","app/android","app/harmony","mini-program-simulator/web","mini-program/wechat","site/web"])}).strict(),Zg=j.object({ctxId:j.string().uuid(),identity:j.object({did:j.string().min(1).max(512),uid:j.string().min(1).max(512).nullable(),sessionId:j.string().min(1).max(512)}).strict(),device:j.object({platform:j.enum(["ios","android","harmony","web","desktop"]).optional(),category:j.enum(["phone","tablet","desktop","unknown"]).optional(),model:j.string().max(256).optional(),osName:j.string().max(128).optional(),osVersion:j.string().max(128).optional(),locale:j.string().max(64).optional(),timezone:j.string().max(128).optional()}).strict(),product:j.object({release:j.string().max(128).optional(),runtimeVariant:j.string().max(128).optional()}).strict()}).strict(),Gg=j.object({eventId:j.string().uuid(),eventKey:Hg,occurredAt:j.string().datetime({offset:!0}),properties:j.record(j.unknown()),ctxId:j.string().uuid(),sampling:j.object({settingRevision:j.number().int().positive().nullable(),effectiveRate:j.number().min(0).max(1)}).strict()}).strict(),qo=j.object({source:Jg,deliveryId:j.string().uuid(),memberEventIds:j.array(j.string().uuid()).min(1).max(100),contexts:j.array(Zg).min(1).max(100),events:j.array(Gg).min(1).max(100)}).strict(),Yg=8,Hf=100,Xg=4096;function Jf(t){let e={fields:0},r=(n,s)=>{if(s>Yg)return!1;if(n===null||typeof n=="boolean")return!0;if(typeof n=="number")return Number.isFinite(n);if(typeof n=="string")return n.length<=Xg;if(Array.isArray(n))return n.length<=Hf&&n.every(i=>r(i,s+1));if(!n||typeof n!="object")return!1;let o=Object.entries(n);return e.fields+=o.length,e.fields<=Hf&&o.every(([i,a])=>i.length<=128&&r(a,s+1))};return r(t,0)}function Zf(t){let e=[...t.memberEventIds].sort(),r=t.events.map(o=>o.eventId).sort(),n=t.contexts.map(o=>o.ctxId).sort(),s=[...new Set(t.events.map(o=>o.ctxId))].sort();return!(new Set(e).size!==e.length||new Set(r).size!==r.length||new Set(n).size!==n.length||r.length!==e.length||r.some(o=>!e.includes(o))||n.length!==s.length||n.some((o,i)=>o!==s[i]))}var Le={data:{events:{read:{key:"operation.data.events.read",type:"operation",name:{en:"Data Events Read",zh:"\u5206\u6790\u4E8B\u4EF6\u8BFB\u53D6"},category:"data",stability:"stable"}},eventProperties:{read:{key:"operation.data.event-properties.read",type:"operation",name:{en:"Data Event Properties Read",zh:"\u5206\u6790\u4E8B\u4EF6\u5B8C\u6574\u5C5E\u6027\u8BFB\u53D6"},category:"data",stability:"stable"}},insights:{read:{key:"operation.data.insights.read",type:"operation",name:{en:"Data Insights Read",zh:"\u5206\u6790\u6D1E\u5BDF\u8BFB\u53D6"},category:"data",stability:"stable"}},boards:{manage:{key:"operation.data.boards.manage",type:"operation",name:{en:"Data Boards Manage",zh:"\u5206\u6790\u770B\u677F\u7BA1\u7406"},category:"data",stability:"stable"}},data:{read:{key:"operation.data.data.read",type:"operation",name:{en:"Data Data Read",zh:"\u5206\u6790\u6570\u636E\u6CBB\u7406\u8BFB\u53D6"},category:"data",stability:"stable"}},settings:{read:{key:"operation.data.settings.read",type:"operation",name:{en:"Data Settings Read",zh:"\u5206\u6790\u91C7\u96C6\u8BBE\u7F6E\u8BFB\u53D6"},category:"data",stability:"stable"},manage:{key:"operation.data.settings.manage",type:"operation",name:{en:"Data Settings Manage",zh:"\u5206\u6790\u91C7\u96C6\u8BBE\u7F6E\u7BA1\u7406"},category:"data",stability:"stable"}}}};var Cr=y.object({code:y.string(),message:y.string()}),gt={403:{schema:Cr,description:"\u6CA1\u6709\u8BFB\u53D6\u4EA7\u54C1\u6216\u4E8B\u4EF6\u5B9A\u4E49\u76EE\u5F55\u7684\u6743\u9650\u3002"},502:{schema:Cr,description:"\u4EA7\u54C1\u6216\u4E8B\u4EF6\u5B9A\u4E49\u76EE\u5F55\u6682\u65F6\u4E0D\u53EF\u7528\u3002"},422:{schema:Cr,description:"Data \u67E5\u8BE2\u6216\u7B5B\u9009\u8F93\u5165\u65E0\u6548\u3002"},503:{schema:Cr,description:"Data \u8D44\u6E90\u914D\u7F6E\u6216\u5916\u90E8\u670D\u52A1\u4E0D\u53EF\u7528\uFF0C\u4E0D\u80FD\u8FD4\u56DE\u672C\u5730\u66FF\u4EE3\u7ED3\u679C\u3002"},504:{schema:Cr,description:"Data \u5206\u6790\u8BF7\u6C42\u8D85\u8FC7\u670D\u52A1\u671F\u9650\u3002"},404:{schema:Cr,description:"Data \u8D44\u6E90\u4E0D\u5B58\u5728\u6216\u5DF2\u5220\u9664\u3002"},409:{schema:Cr,description:"Data \u914D\u7F6E\u4FEE\u8BA2\u51B2\u7A81\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u3002"}};var Gf=ae({method:"GET",path:"/admin/events/list",accessLevel:"protected",authScope:"admin",requirePermissions:[Le.data.events.read],request:{query:y.object({limit:y.coerce.number().int().min(1).max(100).default(50),beforeSequence:y.coerce.number().int().positive().optional(),from:y.string().datetime({offset:!0}).optional(),to:y.string().datetime({offset:!0}).optional(),productId:y.string().optional(),productRelease:y.string().optional(),deploymentSurface:y.string().optional(),runtimeVariant:y.string().optional(),eventKey:y.string().optional(),eventId:y.string().uuid().optional()}).strict()},responses:{...gt,200:{schema:y.object({data:y.object({items:y.array(y.object({intakeSequence:y.number().int(),eventId:y.string(),productId:y.string(),productRelease:y.string().nullable(),eventKey:y.string(),occurredAt:y.string(),processedAt:y.string(),did:y.string(),uid:y.string().nullable(),deploymentSurface:y.string(),runtimeVariant:y.string(),effectiveRate:y.number(),settingRevision:y.number().int().nullable(),disposition:y.literal("accepted")})),nextBeforeSequence:y.number().int().nullable()})}),description:"\u8FD4\u56DE\u6700\u8FD1\u7684 canonical event \u4E8B\u5B9E\u4E0E\u6355\u83B7\u65F6\u8EAB\u4EFD\u6458\u8981\u3002"},422:{schema:y.object({code:y.string(),message:y.string()}),description:"\u4E8B\u4EF6\u7B5B\u9009\u53C2\u6570\u65E0\u6548\u3002"}},tags:["admin"]});var Yf=ae({method:"GET",path:"/admin/events/get",accessLevel:"protected",authScope:"admin",requirePermissions:[Le.data.events.read,Le.data.eventProperties.read],request:{query:y.object({productId:y.string().min(1),eventId:y.string().uuid()}).strict()},responses:{...gt,200:{schema:y.object({data:y.object({event:y.object({eventId:y.string(),productId:y.string(),eventKey:y.string(),occurredAt:y.string(),observedAt:y.string(),processedAt:y.string(),context:y.object({ctxId:y.string(),did:y.string(),uid:y.string().nullable(),sessionId:y.string(),device:y.record(y.unknown()),productRelease:y.string().nullable(),deploymentSurface:y.string().nullable(),runtimeVariant:y.string().nullable()}),properties:y.record(y.unknown()),sampling:y.object({effectiveRate:y.number(),settingRevision:y.number().int().nullable()})})})}),description:"\u8FD4\u56DE\u4E00\u4E2A canonical event \u7684\u5B8C\u6574\u5141\u8BB8\u5C5E\u6027\u3002"},404:{schema:y.object({code:y.string(),message:y.string()}),description:"Event \u4E0D\u5B58\u5728\u3002"}},tags:["admin"]});var Xf=ae({method:"GET",path:"/admin/products",accessLevel:"protected",authScope:"admin",requirePermissions:[Le.data.data.read],responses:{...gt,200:{schema:y.object({data:y.object({items:y.array(y.object({productId:y.string(),displayName:y.string(),description:y.string(),registered:y.boolean(),observed:y.boolean()}))})}),description:"\u8FD4\u56DE\u6B63\u5F0F\u4EA7\u54C1\u76EE\u5F55\u548C\u5DF2\u89C2\u6D4B\u672A\u77E5\u4EA7\u54C1\u7684\u5E76\u96C6\uFF0C\u5305\u542B\u9ED8\u8BA4\u8BED\u8A00\u540D\u79F0\u4E0E\u63CF\u8FF0\u3002"}},tags:["admin"]});var ep=ae({method:"GET",path:"/admin/overview",accessLevel:"protected",authScope:"admin",requirePermissions:[Le.data.insights.read,Le.data.data.read],request:{query:y.object({productId:y.string().min(1).optional()}).strict()},responses:{...gt,200:{schema:y.object({data:y.object({eventCount:y.number().int(),registryEventKeyCount:y.number().int(),accessDevices:y.number().int(),accessUsers:y.number().int(),deviceDau:y.number().int(),deviceWau:y.number().int(),deviceMau:y.number().int(),userDau:y.number().int(),userWau:y.number().int(),userMau:y.number().int(),pending:y.number().int(),quarantined:y.number().int(),rejected:y.number().int(),byDeploymentSurface:y.record(y.number().int()),byRuntimeVariant:y.record(y.number().int()),timezone:y.string(),dataThrough:y.object({acceptedThroughSequence:y.number().int(),canonicalizedThroughSequence:y.number().int(),projectedThroughSequence:y.number().int()})})}),description:"\u8FD4\u56DE\u771F\u5B9E Canonical Fact\u3001\u4E3B\u4F53\u3001\u6765\u6E90\u7EF4\u5EA6\u4E0E\u6C34\u4F4D\u6458\u8981\u3002"}},tags:["admin"]});var tp="data";var rp=Jl({extensionId:tp,databaseName:"default",tables:{PreviewDelivery:Et.table("PreviewDelivery",{sequence:Et.id().primaryKey().autoIncrement(),productId:Et.text().notNull(),deliveryId:Et.text().notNull(),receivedAt:Et.text().notNull(),payload:Et.text().notNull()},t=>({indexes:[t.unique("preview_delivery_identity").on("productId","deliveryId")]}))}});var{PreviewDelivery:rt}=rp,np={PreviewDelivery:rt};var Te=class extends Error{constructor(r,n){super(n);this.code=r;this.name="DataDomainError"}};var sp=4320*6e4,ey=5*6e4,ty=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;function ry(t){if(!ty.test(t))throw new Te("data.delivery_id_invalid","Data \u6279\u6B21\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u7684\u5C0F\u5199 UUIDv7\u3002");return Number.parseInt(t.slice(0,8)+t.slice(9,13),16)+sp}function op(t,e){if(!Number.isSafeInteger(e)||e<0)throw new Te("data.delivery_time_invalid","Data \u63A5\u6536\u65F6\u95F4\u65E0\u6548\u3002");let r=ry(t);if(r-sp>e+ey)throw new Te("data.delivery_in_future","Data \u6279\u6B21\u8D77\u70B9\u8D85\u8FC7\u5141\u8BB8\u7684\u65F6\u949F\u504F\u5DEE\u3002");if(e>=r)throw new Te("data.delivery_expired","Data \u56FA\u5B9A\u6279\u6B21\u5DF2\u8D85\u8FC7 72 \u5C0F\u65F6\u91CD\u8BD5\u671F\u9650\u3002")}var sy=[...["platform","category","model","osName","osVersion","locale","timezone"].map(t=>({scope:"device",key:t,type:"string"})),...["productRelease","deploymentSurface","runtimeVariant"].map(t=>({scope:"source",key:t,type:"string"})),...["did","uid"].map(t=>({scope:"identity",key:t,type:"string"})),{scope:"identity",key:"loggedIn",type:"boolean"}];var ak=Object.freeze([Object.freeze({key:"runtime.session.started",displayName:"\u4F1A\u8BDD\u5F00\u59CB",description:"Product Runtime \u5F00\u59CB\u65B0\u7684\u7528\u6237\u4F1A\u8BDD\u3002"}),Object.freeze({key:"runtime.session.engaged",displayName:"\u6709\u6548\u4F1A\u8BDD",description:"\u4F1A\u8BDD\u8FBE\u5230\u6709\u6548\u53C2\u4E0E\u6761\u4EF6\u65F6\u7531 Product Runtime \u8BB0\u5F55\u3002"})]);var _k=900*1e3,Sk=2700*1e3,Ek=10080*60*1e3;var kk=2*1024*1024;var Ct=j.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),kt=Ct.nullable(),Lo=j.string().regex(/^\d{4}-\d{2}-\d{2}$/u),Ic=j.string().datetime({offset:!0}),ap=j.object({projectId:Ct.positive(),productId:j.string().regex(/^[a-z][a-z0-9-]{0,159}$/u)}).strict(),ay=j.object({history:j.enum(["collected","incomplete","unavailable"]),sampling:j.enum(["complete","sampled","unavailable"]),lagging:j.boolean(),coverageStartedAt:Ic.nullable()}).strict(),cp=j.object({cohortDate:Lo,observationDate:Lo,numerator:kt,denominator:kt,rate:j.number().min(0).max(1).nullable(),status:j.enum(["not-started","observing","complete","empty","unavailable"])}).strict(),ip=j.object({date:Lo,coverage:j.enum(["collected","incomplete","unavailable"]),added:kt,dau:kt,wau:kt,d1:cp,sealed:j.boolean()}).strict(),cy=ap.extend({projectName:j.string().min(1).max(500),displayName:j.string().min(1).max(500),kind:j.string().min(1).max(100).nullable(),installedAt:Ct}).strict(),ly=cy.extend({version:j.literal(1),generation:j.string().min(1).max(512),revision:Ct.positive(),timezone:j.string().min(1).max(128),statDate:Lo,computedAt:Ic,dataThrough:j.object({acceptedSequence:Ct,visibleSequence:Ct,committedOffset:Ct}).strict(),quality:ay,totalDevices:kt,added:kt,dau:kt,wau:kt,d1:cp,recent:j.array(ip).max(30),history:j.array(ip).max(30).optional()}).strict(),qk=j.object({version:j.literal(1),reportId:j.string().regex(/^home-v1-[a-f0-9]{64}$/u),source:j.object({projectId:Ct.positive(),environment:j.literal("prod"),generation:j.string().min(1).max(512),revision:Ct.positive()}).strict(),computedAt:Ic,products:j.array(ly).min(1).max(100)}).strict(),Lk=j.object({mode:j.enum(["automatic","custom"]),products:j.array(ap).max(5)}).strict();var lp=ae({method:"POST",path:"/events",accessLevel:"public",clientAudience:"runtime",request:{body:qo},responses:{202:{schema:y.object({data:y.object({deliveryId:y.string().uuid(),status:y.enum(["accepted","duplicate"]),eventCount:y.number().int().positive(),receivedAt:y.string().datetime()}).strict()}),description:"\u56FA\u5B9A\u6279\u6B21\u5DF2\u6301\u4E45\u63A5\u7BA1\uFF0C\u590D\u7528\u9996\u6B21\u63A5\u7BA1\u4FE1\u606F\u3002"},410:{schema:y.object({code:y.string(),message:y.string()}),description:"\u56FA\u5B9A\u6279\u6B21\u8D85\u8FC7 72 \u5C0F\u65F6\u91CD\u8BD5\u671F\u9650\u3002"},413:{schema:y.object({code:y.string(),message:y.string()}),description:"Delivery \u8D85\u8FC7\u5BB9\u91CF\u9650\u5236\u3002"},422:{schema:y.object({code:y.string(),message:y.string()}),description:"Delivery envelope \u65E0\u6548\u3002"},503:{schema:y.object({code:y.string(),message:y.string()}),description:"Data \u6301\u4E45\u63A5\u7BA1\u670D\u52A1\u4E0D\u53EF\u7528\uFF0C\u4F7F\u7528\u539F\u6279\u6B21 ID \u91CD\u8BD5\u3002"},504:{schema:y.object({code:y.string(),message:y.string()}),description:"Data \u670D\u52A1\u8BF7\u6C42\u8D85\u8FC7\u671F\u9650\u3002"}},tags:["events"]});var up=be(lp,async(t,{body:e})=>{let r=JSON.stringify(e);if(new TextEncoder().encode(r).length>256*1024||e.events.some(u=>!Jf(u.properties)))return t.json({code:"data.delivery_too_large",message:"\u4E8B\u4EF6\u6279\u6B21\u8D85\u8FC7\u5BB9\u91CF\u9650\u5236\u3002"},413);if(!Zf(e))return t.json({code:"data.delivery_membership_invalid",message:"\u4E8B\u4EF6\u4E0E\u4E0A\u4E0B\u6587\u4E0D\u5339\u914D\u3002"},422);let n=Date.now();try{op(e.deliveryId,n)}catch(u){if(!(u instanceof Te))throw u;return t.json({code:u.code,message:u.message},u.code==="data.delivery_expired"?410:422)}let s=t.get("db"),{deliveryId:o,source:{productId:i}}=e,a=new Date(n).toISOString(),[c]=await s.insert(rt).values({productId:i,deliveryId:o,payload:r,receivedAt:a}).onConflictDoNothing().returning(),l=c??(await s.select().from(rt).where(Je(Ke(rt.productId,i),Ke(rt.deliveryId,o))).limit(1))[0];if(!l)throw new Error("preview.delivery_missing");return l.payload!==r?t.json({code:"data.delivery_conflict",message:"\u5DF2\u63A5\u6536\u540C\u4E00\u7F16\u53F7\u7684\u5176\u4ED6\u6279\u6B21\u5185\u5BB9\u3002"},422):t.json({data:{deliveryId:o,receivedAt:l.receivedAt,eventCount:e.events.length,status:c?"accepted":"duplicate"}},202)});var uy=ae({method:"GET",path:"/admin/settings",accessLevel:"protected",authScope:"admin",requirePermissions:[Le.data.data.read],responses:{200:{schema:y.object({data:y.object({timezone:y.string(),revision:y.number().int().positive().nullable(),updatedAt:y.number().int().nullable()})}),description:"\u4ED3\u5E93\u6A21\u62DF\u6570\u636E\u7684\u7EDF\u8BA1\u65F6\u533A"}}}),dp=be(uy,async t=>t.json({data:{timezone:"UTC",revision:null,updatedAt:null}},200));var fp=ae({method:"GET",path:"/admin/boards/list",accessLevel:"protected",authScope:"admin",requirePermissions:[Le.data.insights.read],request:{query:y.object({after:y.string().uuid().optional()}).strict()},responses:{...gt,200:{schema:y.object({data:y.object({items:y.array(y.object({id:y.string(),name:y.string(),revision:y.number().int(),updatedAt:y.string()})),nextAfter:y.string().nullable()})}),description:"\u5F53\u524D\u73AF\u5883\u5171\u4EAB\u770B\u677F\u76EE\u5F55\uFF1B\u4E0D\u8FD4\u56DE\u7B5B\u9009\u5B57\u6BB5\u548C\u503C\u3002"}},tags:["admin"]});var dy=be(fp,async t=>t.json({data:{items:[],nextAfter:null}},200));async function jc(t,e){return(await t.select().from(rt).where(e?Ke(rt.productId,e):void 0)).flatMap(n=>{let{events:s,contexts:o,source:i}=qo.parse(JSON.parse(n.payload)),a=new Map(o.map(c=>[c.ctxId,c]));return s.map((c,l)=>{let u=a.get(c.ctxId);if(!u)throw new Error("preview.data_context_missing");let d={intakeSequence:(n.sequence-1)*100+l+1,eventId:c.eventId,eventKey:c.eventKey,occurredAt:c.occurredAt,processedAt:n.receivedAt,...i,did:u.identity.did,uid:u.identity.uid,...c.sampling,disposition:"accepted"},p={eventId:c.eventId,productId:i.productId,eventKey:c.eventKey,occurredAt:c.occurredAt,observedAt:n.receivedAt,processedAt:n.receivedAt,properties:c.properties,sampling:c.sampling,context:{...i,ctxId:u.ctxId,...u.identity,device:u.device}};return{summary:d,detail:p}})}).sort((n,s)=>s.summary.intakeSequence-n.summary.intakeSequence)}var fy=be(Gf,async(t,{query:e})=>{let{limit:r,beforeSequence:n,from:s,to:o,...i}=e,c=(await jc(t.get("db"),e.productId)).map(u=>u.summary).filter(u=>(!n||u.intakeSequence<n)&&(!s||Date.parse(u.occurredAt)>=Date.parse(s))&&(!o||Date.parse(u.occurredAt)<=Date.parse(o))&&Object.entries(i).every(([d,p])=>p===void 0||u[d]===p)),l=c.slice(0,r);return t.json({data:{items:l,nextBeforeSequence:c.length>r?l[r-1].intakeSequence:null}},200)}),py=be(Yf,async(t,{query:e})=>{let n=(await jc(t.get("db"),e.productId)).find(s=>s.detail.eventId===e.eventId)?.detail;return n?t.json({data:{event:n}},200):t.json({code:"data.event_not_found",message:"\u8BE5\u4ED3\u5E93\u6CA1\u6709\u8FD9\u6761\u4E8B\u4EF6\u3002"},404)}),my=be(Xf,async t=>{let r=(await t.get("db").selectDistinct({productId:rt.productId}).from(rt)).map(({productId:n})=>({productId:n,displayName:n,description:"",registered:!1,observed:!0}));return t.json({data:{items:r}},200)}),hy=be(ep,async(t,{query:e})=>{let r=(await jc(t.get("db"),e.productId)).map(a=>a.summary),n=Date.now(),s=(a,c=1/0)=>new Set(r.filter(l=>Date.parse(l.occurredAt)>=n-c*864e5).map(l=>l[a]).filter(Boolean)).size,o=a=>{let c={};for(let l of r)c[l[a]]=(c[l[a]]??0)+1;return c},i=r[0]?.intakeSequence??0;return t.json({data:{eventCount:r.length,registryEventKeyCount:new Set(r.map(a=>a.eventKey)).size,accessDevices:s("did"),accessUsers:s("uid"),deviceDau:s("did",1),deviceWau:s("did",7),deviceMau:s("did",30),userDau:s("uid",1),userWau:s("uid",7),userMau:s("uid",30),pending:0,quarantined:0,rejected:0,byDeploymentSurface:o("deploymentSurface"),byRuntimeVariant:o("runtimeVariant"),timezone:"UTC",dataThrough:{acceptedThroughSequence:i,canonicalizedThroughSequence:i,projectedThroughSequence:i}}},200)}),pp=[dy,up,fy,py,my,hy,dp];var yn=pp,gy=Array.isArray(yn)?yn:yn&&typeof yn=="object"&&Array.isArray(yn.apis)?yn.apis:[],gp={extensionId:"data",name:"\u6570\u636E\u5206\u6790",displayName:"\u6570\u636E\u5206\u6790",description:"\u9762\u5411\u5F53\u524D project/env \u7684\u672C\u5730\u884C\u4E3A\u91C7\u96C6\u3001\u4E8B\u4EF6\u5206\u6790\u4E0E\u6CBB\u7406\u3002"},mp=new WeakMap;function yy(t){let e=t.PLATFORM_EXTENSION_RELEASE;if(typeof e!="string"||!e.trim())throw new Error("Deployed extension requires PLATFORM_EXTENSION_RELEASE.");let r=mp.get(t);if(r&&r.config.version===e)return r;let n={...gp,version:e},s={config:n,app:Wf({config:n,apis:gy,tables:np,cloudCollections:void 0})};return mp.set(t,s),s}var hp=class extends Xs{},by=(function({extensionId:e,resolveLogicalDatabaseObjectName:r,mainProjectId:n}){async function s(a,c){let l=new URL(a.url);if(!l.pathname.startsWith("/__kuafu/database/"))return null;let u=typeof c.PLATFORM_DATABASE_BOOTSTRAP_TOKEN=="string"?c.PLATFORM_DATABASE_BOOTSTRAP_TOKEN.trim():"";if(!u)return Response.json({code:"database.bootstrap_not_configured"},{status:403});if(a.headers.get("x-kuafu-database-bootstrap-token")!==u)return Response.json({code:"database.bootstrap_forbidden"},{status:403});let d=await a.json(),p=o(d.projectId),g=i(d.projectEnvKey??a.headers.get("x-project-env-key")??c.PLATFORM_PROJECT_ENV_KEY),w=typeof d.databaseName=="string"&&d.databaseName.trim()?d.databaseName.trim():"default",b=c.SQL_EXECUTOR;if(!b||typeof b.idFromName!="function"||typeof b.get!="function")return Response.json({code:"database.sql_executor_missing"},{status:500});let E=r({projectId:p,projectEnvKey:g,extensionId:e,databaseName:w}),S=b.get(b.idFromName(E));return l.pathname.endsWith("/apply-migration")?S.fetch("https://sql-executor.local/apply-migration",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({migrationId:d.migrationId,statements:d.statements})}):l.pathname.endsWith("/execute-transaction")?S.fetch("https://sql-executor.local/execute",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"transactionBatch",statements:Array.isArray(d.statements)?d.statements:[]})}):S.fetch("https://sql-executor.local/apply-metadata",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({metadata:d.metadata??d,dataset:d.dataset===void 0?void 0:{extensionId:e,value:d.dataset.value}})})}function o(a){let c=Number(a);return Number.isFinite(c)&&c>0?Math.floor(c):n}function i(a){let c=typeof a=="string"?a.trim().toLowerCase():"";return/^[a-z0-9][a-z0-9_-]{0,62}$/.test(c)?c:"prod"}return s})({extensionId:gp.extensionId,resolveLogicalDatabaseObjectName:It,mainProjectId:Ye}),DD={async fetch(t,e,r){let n=await by(t,e);return n||yy(e).app.fetch(t,e,r)}};export{hp as KuafuSqlExecutorObject,DD as default};
39
+ //# sourceMappingURL=index.js.map