@kuafucloud/developer 0.0.0-stage → 0.1.9-alpha.3

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 (75) 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 +59 -0
  5. package/dist/admin/meta/extension-manifest.json +794 -0
  6. package/dist/facade/index.d.ts +241 -0
  7. package/dist/facade/index.js +11 -0
  8. package/dist/monitor/runtime-services/app/index.js +660 -0
  9. package/dist/monitor/runtime-services/app/service-module.config.json +16 -0
  10. package/dist/monitor/runtime-services/app-simulator/index.js +648 -0
  11. package/dist/monitor/runtime-services/app-simulator/service-module.config.json +12 -0
  12. package/dist/monitor/runtime-services/mini-program/index.js +653 -0
  13. package/dist/monitor/runtime-services/mini-program/service-module.config.json +12 -0
  14. package/dist/monitor/runtime-services/mini-program-simulator/index.js +648 -0
  15. package/dist/monitor/runtime-services/mini-program-simulator/service-module.config.json +12 -0
  16. package/dist/monitor/runtime-services/site/index.js +648 -0
  17. package/dist/monitor/runtime-services/site/service-module.config.json +12 -0
  18. package/dist/public/monitor/index.js +6 -0
  19. package/dist/public/monitor/runtime-services/core/index.js +552 -0
  20. package/dist/public/realtime/host/index.js +4550 -0
  21. package/dist/public/realtime/index.js +3180 -0
  22. package/dist/public/realtime/native-preview-http/index.js +148 -0
  23. package/dist/simulation/artifact/meta/database.json +43 -0
  24. package/dist/simulation/artifact/meta/manifest.json +170 -0
  25. package/dist/simulation/artifact/meta/runtime-meta.json +28 -0
  26. package/dist/simulation/artifact/meta/schema.json +41 -0
  27. package/dist/simulation/artifact/server/worker/index.js +39 -0
  28. package/dist/simulation/artifact/server/worker/monitoring-contract.json +7 -0
  29. package/dist/simulation/index.d.ts +1 -0
  30. package/dist/simulation/index.js +1 -0
  31. package/dist/types/monitor/client/index.d.ts +4 -0
  32. package/dist/types/monitor/runtime-services/app/index.d.ts +4 -0
  33. package/dist/types/monitor/runtime-services/app-simulator/index.d.ts +4 -0
  34. package/dist/types/monitor/runtime-services/core/index.d.ts +1 -0
  35. package/dist/types/monitor/runtime-services/core/monitor-browser-service.d.ts +25 -0
  36. package/dist/types/monitor/runtime-services/core/monitor-mini-program-service.d.ts +25 -0
  37. package/dist/types/monitor/runtime-services/core/monitor-native-service.d.ts +25 -0
  38. package/dist/types/monitor/runtime-services/core/monitor-service.d.ts +35 -0
  39. package/dist/types/monitor/runtime-services/mini-program/index.d.ts +4 -0
  40. package/dist/types/monitor/runtime-services/mini-program-simulator/index.d.ts +4 -0
  41. package/dist/types/monitor/runtime-services/site/index.d.ts +4 -0
  42. package/dist/types/realtime/agent-chat-model.d.ts +216 -0
  43. package/dist/types/realtime/agent-question.d.ts +24 -0
  44. package/dist/types/realtime/developer-realtime.d.ts +158 -0
  45. package/dist/types/realtime/host/index.d.ts +28 -0
  46. package/dist/types/realtime/host-channels.d.ts +52 -0
  47. package/dist/types/realtime/host-connection.d.ts +131 -0
  48. package/dist/types/realtime/native-preview-http/index.d.ts +6 -0
  49. package/dist/types/realtime/native-source-codec.d.ts +21 -0
  50. package/dist/types/realtime/payload-fragments.d.ts +21 -0
  51. package/dist/types/realtime/preview-device.d.ts +9 -0
  52. package/dist/types/realtime/product-preview-cache.d.ts +69 -0
  53. package/dist/types/realtime/product-preview-clients.d.ts +7 -0
  54. package/dist/types/realtime/product-preview-host.d.ts +50 -0
  55. package/dist/types/realtime/product-preview-http-runtime.d.ts +9 -0
  56. package/dist/types/realtime/product-preview-protocol.d.ts +167 -0
  57. package/dist/types/realtime/product-preview-socket-source.d.ts +24 -0
  58. package/dist/types/realtime/product-preview-viewer-http.d.ts +41 -0
  59. package/dist/types/realtime/product-preview-viewer.d.ts +44 -0
  60. package/dist/types/realtime/project-workspaces.d.ts +43 -0
  61. package/dist/types/realtime/viewer/index.d.ts +22 -0
  62. package/dist/types/realtime/websocket-transport.d.ts +12 -0
  63. package/dist/types/realtime/workspace-agent-history.d.ts +46 -0
  64. package/dist/types/realtime/workspace-agent-input.d.ts +38 -0
  65. package/dist/types/realtime/workspace-agent-member.d.ts +15 -0
  66. package/dist/types/realtime/workspace-agent-view.d.ts +22 -0
  67. package/dist/types/realtime/workspace-cache-store.d.ts +38 -0
  68. package/dist/types/realtime/workspace-cache.d.ts +72 -0
  69. package/dist/types/realtime/workspace-chat-stream.d.ts +6 -0
  70. package/dist/types/realtime/workspace-file-view.d.ts +9 -0
  71. package/dist/types/realtime/workspace-status-view.d.ts +8 -0
  72. package/dist/types/realtime/workspace-viewer.d.ts +100 -0
  73. package/extension-manifest.json +457 -0
  74. package/package.json +112 -4
  75. package/README.md +0 -3
@@ -0,0 +1,39 @@
1
+ var Tp=Object.defineProperty;var Cc=(t,e)=>{for(var r in e)Tp(t,r,{get:e[r],enumerable:!0})};import{AsyncLocalStorage as Kp}from"node:async_hooks";import{createHash as zp}from"node:crypto";function $c(t){return Object.freeze({kind:"service",id:Ap(t.id)})}function Ap(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 qy=$c({id:"system.account"});function Nt(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 Uy=4320*6e4,By=256*1024;var hn="global",Rp=Object.freeze({homeRegion:"global",splitRegions:!1});function pt(t=Rp){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")||!Re(e.homeRegion)||typeof e.splitRegions!="boolean")throw new Error("region.project_policy_invalid");return Object.freeze({homeRegion:e.homeRegion,splitRegions:e.splitRegions})}function Re(t){return t==="cn"||t==="global"}function yo(t){let e={status:"unknown",region:null,countryCode:null,source:"unavailable"},{policy:r}=t;if(!Re(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(!Re(t.accountRegion))throw new Error("region.account_region_invalid");return Object.freeze({region:t.accountRegion,source:"account",detection:e})}if(t.anonymousRegion!=null){if(!Re(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(o=>o?.status==="known");if(n){if(!Re(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 zc(t){return typeof t=="string"?qe(t):Array.isArray(t)&&t.length>0&&t.length<=1e3&&t.every(qe)&&new Set(t).size===t.length}function qe(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 qi(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 Me(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 qc(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 o=n[3].replace(/\\/gu,"/");if(/node:|\/(?:node_modules|runtime-core|runtime-shell)\/|@kuafucloud\/(?:extension-kit|product-runtime)/u.test(o))continue;o=o.replace(/^https?:\/\/[^/]+/u,"").replace(/[?#].*$/u,"");let i=(n[1]??n[2]??"").trim();if(e.push(Me(`${i}@${o}:${n[4]}:${n[5]}`,1024)),e.length===8)break}return Object.freeze(e)}function tr(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 Li(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 bo(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 Op(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=bo(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 Di(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 o=gn(n[1]),i=gn(n[2]),s=tr(gn(n[3])),a=r?{hostDeviceId:r[2],sessionId:tr(r[3])}:void 0,c=e?Np({hostDeviceId:e[2],kind:e[3],productId:gn(e[4]),surface:e[5]==="browser"?"browser":"native",...e[5]==="browser"?{}:{platform:e[5].slice(7)}}):void 0;if(r&&(r[1]!==o||i!=="prod")||e&&(e[1]!==o||i!=="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?Op({pathname:u[2],search:t.search}):null,p=u?Li(gn(u[1])):void 0;return{projectId:o,envKey:i,workspaceId:s,runtimePath:d?.runtimePath??`${l}${t.search}`,...a?{remotePreview:a}:{},...c?{remoteProduct:c}:{},...d?{codebaseRuntime:{repositoryId:p,relativePath:d.relativePath}}:{}}}catch{return null}}function Np(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 gn(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 db=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 vo(t){let{allocationId:e,extensionId:r,credential:n,service:o}=t;if(t.namespace!==void 0&&t.namespace!=="tenant"&&t.namespace!=="platform")throw mt();let i=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 mt();let s={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(Cp(l.key))}`,d;try{d=await o.fetch(new Request(`https://storage.internal${i}${u}`,{method:c,headers:{...s,...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(),Xe();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 Ar(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 Ar(l);return await l.body?.cancel(),Mi(l,c)},async get(c,l){let u;if(l?.range){let{offset:p,length:h}=l.range;if(!Number.isSafeInteger(p)||p<0||!Number.isSafeInteger(h)||h<1||!Number.isSafeInteger(p+h))throw mt();u={range:`bytes=${p}-${p+h-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 Ar(d);try{return{object:Mi(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||!qi(c.metadata??{})||typeof c.body=="string"&&new TextEncoder().encode(c.body).length!==c.size||c.body instanceof Uint8Array&&c.body.byteLength!==c.size)throw mt();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 mt();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 Ar(u);await u.body?.cancel();let d=Mi(u,c.key);if(d.size!==c.size)throw Xe();return{status:"written",object:d}},async list(c={}){if(c.prefix&&!qe(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 mt();let l=await a("POST",{list:!0,headers:{"content-type":"application/json"},body:JSON.stringify(c)});if(l.status!==200)throw await Ar(l);let u;try{u=await l.json()}catch{throw Xe()}let d=wo(u);if(!Array.isArray(d.objects)||d.objects.length>(c.limit??100)||d.cursor!==null&&typeof d.cursor!="string")throw Xe();let p=d.objects.map(h=>Lc(h));if(p.some(h=>!h.key.startsWith(c.prefix??""))||new Set(p.map(h=>h.key)).size!==p.length)throw Xe();return{objects:p,cursor:d.cursor}},async delete(c){if(!zc(c))throw mt();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 Ar(l);await l.body?.cancel()}}}function Mi(t,e){let r;try{r=JSON.parse(decodeURIComponent(t.headers.get("x-kuafu-object")??""))}catch{throw Xe()}let n=Lc(r);if(n.key!==e)throw Xe();return n}function Lc(t){let e=wo(t);if(!qe(e.key)||!Number.isSafeInteger(e.size)||Number(e.size)<0||typeof e.etag!="string"||!e.etag||e.contentType!==null&&typeof e.contentType!="string"||!qi(e.metadata)||e.lastModified!==void 0&&(!Number.isSafeInteger(e.lastModified)||Number(e.lastModified)<0))throw Xe();let r;if(e.checksum!==void 0){let n=wo(e.checksum);if(n.algorithm!=="sha256"||typeof n.value!="string"||!/^[a-f0-9]{64}$/u.test(n.value))throw Xe();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 Ar(t){let e={};try{e=wo(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 wo(t){if(!t||typeof t!="object"||Array.isArray(t))throw Xe();return t}function Cp(t){if(!qe(t))throw mt();return t}function mt(){return new W("storage.request_invalid")}function Xe(){return new W("storage.response_invalid")}var Ki="PLATFORM_OBJECT_STORAGE_RUNTIME",$p=["objects","data-raw","monitor-raw","lake"];function Ui(t,e){if(typeof t=="string")try{t=JSON.parse(t)}catch{ht()}let r=xo(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))&&ht();let n=xo(r.regions,["cn","global"]),o={};Object.keys(n).length||ht();for(let[i,s]of Object.entries(n)){Re(i)||ht();let a=xo(s,$p),c={};for(let[l,u]of Object.entries(a)){l!=="objects"&&(i!==hn||!(e.extensionId==="data"&&(l==="data-raw"||l==="lake")||e.extensionId==="developer"&&(l==="monitor-raw"||l==="lake")))&&ht();let d=xo(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))&&ht(),c[l]=Object.freeze({allocationId:d.allocationId,credential:d.credential})}Object.keys(c).length||ht(),o[i]=Object.freeze(c)}return Object.values(o).some(i=>i.objects)||ht(),Object.freeze({schemaVersion:1,projectId:e.projectId,projectEnvKey:e.projectEnvKey,extensionId:e.extensionId,regions:Object.freeze(o)})}function xo(t,e){return(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(r=>!e.includes(r)))&&ht(),t}function ht(){throw new W("storage.runtime_configuration_invalid")}var Dc="(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-alpha\\.(?:0|[1-9]\\d*))?",Nb=new RegExp(`^[a-z][a-z0-9]*(?:-[a-z0-9]+)*/v${Dc}(?:/extension)?$`,"u"),Pb=new RegExp(`^extensions/center/v${Dc}(?:/extension)?$`,"u");function Mc(t){if(!t||typeof t!="object")return"cloudflare";let e=t.KUAFUCLOUD_RUNTIME_PLACEMENT;return e==="local-platform"?e:"cloudflare"}function gt(t){return Mc(t)==="local-platform"}var qp=8e3,Lp=4e3,Uc=1024,Bi=new TextEncoder;function Vi(){let t=qp-Uc,e,r=0,n=0,o=0,i=!1,s=(c,l)=>{let u=Bc(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=Lp;return{recordDroppedError(c,l){!i&&s(c,l)&&r++},recordOutputFailure(c,l){!i&&s(c,l)&&o++},finishDiagnostic(){if(i||(i=!0,!e||!(r||n||o)))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:o});return Bi.encode(c).byteLength<=Uc?c:null},encode(c,l){if(!/^monitor-[0-9a-f]{64}$/u.test(l))return null;let u=Bc(c.source);if(!u||c.schemaVersion!==1)return null;let d=c.kind==="error"?Dp(c,u):c.kind==="trace"?Mp(c,u):null;if(!d||i||!s(u,l))return null;let p=()=>(d.kind==="error"?r++:n++,null),h=d.kind==="trace"?Math.min(t,a):t,w={...d,sourceGrantId:l},b=JSON.stringify(w);for(;Bi.encode(b).byteLength>h;){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 k=d.error.stack.split(`
3
+ `);d.droppedFrames+=1,d.error.stack=k.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 _=Bi.encode(b).byteLength;return t-=_,d.kind==="trace"&&(a-=_),b}}}function Bc(t){if(!t||!et(t.projectId,32)||!et(t.projectEnvKey,128)||!et(t.productId,128)||!et(t.productRelease,128)||!et(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:et(t.userId,128)?t.userId:null}}function Dp(t,e){if(!et(t.eventId,128)||!Vc(t.occurredAt)||!["handled","unhandled"].includes(t.mechanism)||!t.error||!t.context||!Fi(t.traceId)||!Fi(t.spanId))return null;let r=typeof t.error.stack=="string"?t.error.stack:"",n=qc(r),o=n.length?`sha256:${zp("sha256").update(JSON.stringify(n)).digest("hex")}`:void 0,i=r.split(`
5
+ `),s=i.slice(0,12).map(u=>yn(u,256)),a=yn(t.error.message,1024),c=Wc(t.context.tags),l={code:Fc(t.context.code),groupingKey:Fc(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:yn(t.error.name,128),message:a,stack:r?s.join(`
6
+ `):null,...o?{stackDigest:o}:{}},context:l,traceId:t.traceId,spanId:t.spanId,truncated:c.dropped>0||r.length>s.join(`
7
+ `).length||typeof t.error.message=="string"&&t.error.message.length>1024,droppedFrames:Math.max(0,i.length-s.length)}}function Mp(t,e){if(!et(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 o of t.spans.slice(0,100)){if(!et(o.spanId,128)||!Fi(o.parentSpanId)||!Vc(o.startedAt)||!["http","business","sql","rpc"].includes(o.kind)||!["running","finished"].includes(o.state)||!["ok","error"].includes(o.status)||o.durationMs!==null&&(!Number.isFinite(o.durationMs)||o.durationMs<0))return null;let i=Wc(o.attributes);n.push({spanId:o.spanId,parentSpanId:o.parentSpanId,name:yn(o.name,128),kind:o.kind,startedAt:o.startedAt,durationMs:o.durationMs,state:o.state,status:o.status,attributes:i.values,droppedAttributes:(Number.isSafeInteger(o.droppedAttributes)&&o.droppedAttributes>=0?o.droppedAttributes:0)+i.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 yn(t,e){return typeof t=="string"?Me(t,e):""}function Fc(t){return typeof t=="string"&&/^[A-Za-z0-9_.:/-]{1,128}$/u.test(t)?t:void 0}function et(t,e){return typeof t=="string"&&t.length<=e&&/^[A-Za-z0-9_.:+/-]+$/u.test(t)}function Fi(t){return t===null||et(t,128)}function Vc(t){return typeof t=="string"&&t.length<=32&&Number.isFinite(Date.parse(t))}function Wc(t){let e={};if(!t||typeof t!="object"||Array.isArray(t))return{values:e,dropped:0};let r=Object.entries(t);for(let[n,o]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 o=="string"?e[n]=yn(o,128):(typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o))&&(e[n]=o));return{values:e,dropped:r.length-Object.keys(e).length}}var Rr,ko=new Kp,Up=["log","info","debug","warn","error","assert","dir","dirxml","table","trace","count","countReset","time","timeLog","timeEnd","group","groupCollapsed","groupEnd","clear","profile","profileEnd","timeStamp"];function Qc(){if(Rr)return;let t=globalThis.console;Rr=t.info.bind(t);let e=()=>{};for(let r of Up)Object.defineProperty(t,r,{configurable:!0,writable:!0,value:e})}function Hc(t){let e=Vi(),r=()=>ko.getStore()?.encoder??e;return Object.assign(n=>{if(!Rr)return!1;let o=r(),i=o.encode(n,t);if(i===null)return!1;try{return Rr(i),!0}catch{return o.recordOutputFailure(n.source,t),!1}},{recordDroppedError:n=>r().recordDroppedError(n,t)})}async function Jc(t,e){if(ko.getStore())return t();let r={encoder:Vi(),tasks:new Set};return ko.run(r,async()=>{try{return await t()}finally{let n=(async()=>{for(;r.tasks.size;)await Promise.allSettled([...r.tasks]);let o=r.encoder.finishDiagnostic();if(o&&Rr)try{Rr(o)}catch{}})();e?e(n):await n}})}function Gc(t){let e=ko.getStore();return e?(e.tasks.add(t),t.then(()=>{e.tasks.delete(t)},()=>{e.tasks.delete(t)}),!0):!1}Qc();var m=Symbol.for("drizzle:entityKind"),Xw=Symbol.for("drizzle:hasOwnEntityKind");function y(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 M=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 Or=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 je=Symbol.for("drizzle:Name");var _o=class{static[m]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,r){this.reference=()=>{let{name:n,columns:o,foreignColumns:i}=e();return{name:n,columns:o,foreignTable:i[0].table,foreignColumns:i}},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 Wi(e,this)}},Wi=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(),o=r.map(a=>a.name),i=n.map(a=>a.name),s=[this.table[je],...o,n[0].table[je],...i];return e??`${s.join("_")}_fk`}};function Io(t,...e){return t(...e)}function Ji(t,e){return`${t[je]}_${e.join("_")}_unique`}var Qi=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 Hi(e,this.columns,this.nullsNotDistinctConfig,this.name)}},Zc=class{static[m]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new Qi(e,this.name)}},Hi=class{constructor(e,r,n,o){this.table=e,this.columns=r,this.name=o??Ji(this.table,this.columns.map(i=>i.name)),this.nullsNotDistinct=n}static[m]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}};function Yc(t,e,r){for(let n=e;n<t.length;n++){let o=t[n];if(o==="\\"){n++;continue}if(o==='"')return[t.slice(e,n).replace(/\\/g,""),n+1];if(!r&&(o===","||o==="}"))return[t.slice(e,n).replace(/\\/g,""),n]}return[t.slice(e).replace(/\\/g,""),t.length]}function Xc(t,e=0){let r=[],n=e,o=!1;for(;n<t.length;){let i=t[n];if(i===","){(o||n===e)&&r.push(""),o=!0,n++;continue}if(o=!1,i==="\\"){n+=2;continue}if(i==='"'){let[c,l]=Yc(t,n+1,!0);r.push(c),n=l;continue}if(i==="}")return[r,n+1];if(i==="{"){let[c,l]=Xc(t,n+1);r.push(c),n=l;continue}let[s,a]=Yc(t,n,!1);r.push(s),n=a}return[r,n]}function el(t){let[e]=Xc(t,1);return e}function Gi(t){return`{${t.map(e=>Array.isArray(e)?Gi(e):typeof e=="string"?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${e}`).join(",")}}`}var ve=class extends Or{foreignKeyConfigs=[];static[m]="PgColumnBuilder";array(e){return new Yi(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:o})=>Io((i,s)=>{let a=new _o(()=>{let c=i();return{columns:[e],foreignColumns:[c]}});return s.onUpdate&&a.onUpdate(s.onUpdate),s.onDelete&&a.onDelete(s.onDelete),a.build(r)},n,o))}buildExtraConfigColumn(e){return new Zi(e,this.config)}},Z=class extends M{constructor(e,r){r.uniqueName||(r.uniqueName=Ji(e,[r.name])),super(e,r),this.table=e}static[m]="PgColumn"},Zi=class extends Z{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}},tl=class{static[m]="IndexedColumn";constructor(e,r,n,o){this.name=e,this.keyAsName=r,this.type=n,this.indexConfig=o}name;keyAsName;type;indexConfig},Yi=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 Xi(e,this.config,r)}},Xi=class t extends Z{constructor(e,r,n,o){super(e,r),this.baseColumn=n,this.range=o,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=el(e)),e.map(r=>this.baseColumn.mapFromDriverValue(r))}mapToDriverValue(e,r=!1){let n=e.map(o=>o===null?null:y(this.baseColumn,t)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));return r?n:Gi(n)}};var rl=class extends ve{static[m]="PgEnumObjectColumnBuilder";constructor(e,r){super(e,"string","PgEnumObjectColumn"),this.config.enum=r}build(e){return new es(e,this.config)}},es=class extends Z{static[m]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,r){super(e,r),this.enum=r.enum}getSQLType(){return this.enum.enumName}},nl=Symbol.for("drizzle:isPgEnum");function il(t){return!!t&&typeof t=="function"&&nl in t&&t[nl]===!0}var ol=class extends ve{static[m]="PgEnumColumnBuilder";constructor(e,r){super(e,"string","PgEnumColumn"),this.config.enum=r}build(e){return new ts(e,this.config)}},ts=class extends Z{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 V=class{static[m]="Subquery";constructor(e,r,n,o=!1,i=[]){this._={brand:"Subquery",sql:e,selectedFields:r,alias:n,isWith:o,usedTables:i}}},tt=class extends V{static[m]="WithSubquery"};var sl="0.45.2";var rs,ns,ne={startActiveSpan(t,e){return rs?(ns||(ns=rs.trace.getTracer("drizzle-orm",sl)),Io((r,n)=>n.startActiveSpan(t,o=>{try{return e(o)}catch(i){throw o.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{o.end()}}),rs,ns)):e()}};var H=Symbol.for("drizzle:ViewBaseConfig");var rr=Symbol.for("drizzle:Schema"),Nr=Symbol.for("drizzle:Columns"),al=Symbol.for("drizzle:ExtraConfigColumns"),os=Symbol.for("drizzle:OriginalName"),is=Symbol.for("drizzle:BaseName"),bn=Symbol.for("drizzle:IsAlias"),cl=Symbol.for("drizzle:ExtraConfigBuilder"),Bp=Symbol.for("drizzle:IsDrizzleTable"),v=class{static[m]="Table";static Symbol={Name:je,Schema:rr,OriginalName:os,Columns:Nr,ExtraConfigColumns:al,BaseName:is,IsAlias:bn,ExtraConfigBuilder:cl};[je];[os];[rr];[Nr];[al];[is];[bn]=!1;[Bp]=!0;[cl]=void 0;constructor(e,r,n){this[je]=this[os]=e,this[rr]=r,this[is]=n}};function me(t){return t[je]}function yt(t){return`${t[rr]??"public"}.${t[je]}`}var ll=class{static[m]="FakePrimitiveParam"};function ss(t){return t!=null&&typeof t.getSQL=="function"}function Fp(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 I([this])}},I=class t{constructor(e){this.queryChunks=e;for(let r of e)if(y(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=dl;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:o,escapeName:i,escapeParam:s,prepareTyping:a,inlineParams:c,paramStartIndex:l}=n;return Fp(e.map(u=>{if(y(u,fe))return{sql:u.value.join(""),params:[]};if(y(u,wn))return{sql:i(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new fe("(")];for(let[p,h]of u.entries())d.push(h),p<u.length-1&&d.push(new fe(", "));return d.push(new fe(")")),this.buildQueryFromSourceParams(d,n)}if(y(u,t))return this.buildQueryFromSourceParams(u.queryChunks,{...n,inlineParams:c||u.shouldInlineParams});if(y(u,v)){let d=u[v.Symbol.Schema],p=u[v.Symbol.Name];return{sql:d===void 0||u[bn]?i(p):i(d)+"."+i(p),params:[]}}if(y(u,M)){let d=o.getColumnCasing(u);if(r.invokeSource==="indexes")return{sql:i(d),params:[]};let p=u.table[v.Symbol.Schema];return{sql:u.table[bn]||p===void 0?i(u.table[v.Symbol.Name])+"."+i(d):i(p)+"."+i(u.table[v.Symbol.Name])+"."+i(d),params:[]}}if(y(u,he)){let d=u[H].schema,p=u[H].name;return{sql:d===void 0||u[H].isAlias?i(p):i(d)+"."+i(p),params:[]}}if(y(u,xe)){if(y(u.value,bt))return{sql:s(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(y(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:s(l.value++,d),params:[d],typings:p}}return y(u,bt)?{sql:s(l.value++,u),params:[u],typings:["none"]}:y(u,t.Aliased)&&u.fieldAlias!==void 0?{sql:i(u.fieldAlias),params:[]}:y(u,V)?u._.isWith?{sql:i(u._.alias),params:[]}:this.buildQueryFromSourceParams([new fe("("),u._.sql,new fe(") "),new wn(u._.alias)],n):il(u)?u.schema?{sql:i(u.schema)+"."+i(u.enumName),params:[]}:{sql:i(u.enumName),params:[]}:ss(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:s(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}},wn=class{constructor(e){this.value=e}static[m]="Name";brand;getSQL(){return new I([this])}};function ul(t){return typeof t=="object"&&t!==null&&"mapToDriverValue"in t&&typeof t.mapToDriverValue=="function"}var dl={mapFromDriverValue:t=>t},fl={mapToDriverValue:t=>t},Uv={...dl,...fl},xe=class{constructor(e,r=fl){this.value=e,this.encoder=r}static[m]="Param";brand;getSQL(){return new I([this])}};function f(t,...e){let r=[];(e.length>0||t.length>0&&t[0]!=="")&&r.push(new fe(t[0]));for(let[n,o]of e.entries())r.push(o,new fe(t[n+1]));return new I(r)}(t=>{function e(){return new I([])}t.empty=e;function r(c){return new I(c)}t.fromList=r;function n(c){return new I([new fe(c)])}t.raw=n;function o(c,l){let u=[];for(let[d,p]of c.entries())d>0&&l!==void 0&&u.push(l),u.push(p);return new I(u)}t.join=o;function i(c){return new wn(c)}t.identifier=i;function s(c){return new bt(c)}t.placeholder=s;function a(c,l){return new xe(c,l)}t.param=a})(f||(f={}));(t=>{class e{constructor(n,o){this.sql=n,this.fieldAlias=o}static[m]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}t.Aliased=e})(I||(I={}));var bt=class{constructor(e){this.name=e}static[m]="Placeholder";getSQL(){return new I([this])}};function nr(t,e){return t.map(r=>{if(y(r,bt)){if(!(r.name in e))throw new Error(`No value for placeholder "${r.name}" was provided`);return e[r.name]}if(y(r,xe)&&y(r.value,bt)){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 Vp=Symbol.for("drizzle:IsDrizzleView"),he=class{static[m]="View";[H];[Vp]=!0;constructor({name:e,schema:r,selectedFields:n,query:o}){this[H]={name:e,originalName:e,schema:r,selectedFields:n,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new I([this])}};M.prototype.getSQL=function(){return new I([this])};v.prototype.getSQL=function(){return new I([this])};V.prototype.getSQL=function(){return new I([this])};var or=class{constructor(e){this.table=e}static[m]="ColumnAliasProxyHandler";get(e,r){return r==="table"?this.table:e[r]}},Pr=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 o=e[v.Symbol.Columns];if(!o)return o;let i={};return Object.keys(o).map(s=>{i[s]=new Proxy(o[s],new or(new Proxy(e,this)))}),i}let n=e[r];return y(n,M)?new Proxy(n,new or(new Proxy(e,this))):n}},pl=class{constructor(e){this.alias=e}static[m]="RelationTableAliasProxyHandler";get(e,r){return r==="sourceTable"?wt(e.sourceTable,this.alias):e[r]}};function wt(t,e){return new Proxy(t,new Pr(e,!1))}function ge(t,e){return new Proxy(t,new or(new Proxy(t.table,new Pr(e,!1))))}function vn(t,e){return new I.Aliased(Pt(t.sql,e),t.fieldAlias)}function Pt(t,e){return f.join(t.queryChunks.map(r=>y(r,M)?ge(r,e):y(r,I)?Pt(r,e):y(r,I.Aliased)?vn(r,e):r))}function xn(t,e,r){let n={},o=t.reduce((i,{path:s,field:a},c)=>{let l;y(a,M)?l=a:y(a,I)?l=a.decoder:y(a,V)?l=a._.sql.decoder:l=a.sql.decoder;let u=i;for(let[d,p]of s.entries())if(d<s.length-1)p in u||(u[p]={}),u=u[p];else{let h=e[c],w=u[p]=h===null?null:l.mapFromDriverValue(h);if(r&&y(a,M)&&s.length===2){let b=s[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 i},{});if(r&&Object.keys(n).length>0)for(let[i,s]of Object.entries(n))typeof s=="string"&&!r[s]&&(o[i]=null);return o}function ae(t,e){return Object.entries(t).reduce((r,[n,o])=>{if(typeof n!="string")return r;let i=e?[...e,n]:[n];return y(o,M)||y(o,I)||y(o,I.Aliased)||y(o,V)?r.push({path:i,field:o}):y(o,v)?r.push(...ae(o[v.Symbol.Columns],i)):r.push(...ae(o,i)),r},[])}function rt(t,e){let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let[o,i]of r.entries())if(i!==n[o])return!1;return!0}function Ct(t,e){let r=Object.entries(e).filter(([,n])=>n!==void 0).map(([n,o])=>y(o,I)||y(o,M)?[n,o]:[n,new xe(o,t[v.Symbol.Columns][n])]);if(r.length===0)throw new Error("No values to set");return Object.fromEntries(r)}function So(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 Eo(t){return t[v.Symbol.Columns]}function Ce(t){return y(t,V)?t._.alias:y(t,he)?t[H].name:y(t,I)?void 0:t[v.Symbol.IsAlias]?t[v.Symbol.Name]:t[v.Symbol.BaseName]}function nt(t,e){return{name:typeof t=="string"&&t.length>0?t:"",config:typeof t=="object"?t:e}}var as=typeof TextDecoder>"u"?null:new TextDecoder;var jo=class{static[m]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,r){this.reference=()=>{let{name:n,columns:o,foreignColumns:i}=e();return{name:n,columns:o,foreignTable:i[0].table,foreignColumns:i}},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 cs(e,this)}},cs=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(),o=r.map(a=>a.name),i=n.map(a=>a.name),s=[this.table[je],...o,n[0].table[je],...i];return e??`${s.join("_")}_fk`}};function ds(t,e){return`${t[je]}_${e.join("_")}_unique`}var ls=class{constructor(e,r){this.name=r,this.columns=e}static[m]="SQLiteUniqueConstraintBuilder";columns;build(e){return new us(e,this.columns,this.name)}},ml=class{static[m]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new ls(e,this.name)}},us=class{constructor(e,r,n){this.table=e,this.columns=r,this.name=n??ds(this.table,this.columns.map(o=>o.name))}static[m]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}};var ye=class extends Or{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:o})=>((i,s)=>{let a=new jo(()=>{let c=i();return{columns:[e],foreignColumns:[c]}});return s.onUpdate&&a.onUpdate(s.onUpdate),s.onDelete&&a.onDelete(s.onDelete),a.build(r)})(n,o))}},se=class extends M{constructor(e,r){r.uniqueName||(r.uniqueName=ds(e,[r.name])),super(e,r),this.table=e}static[m]="SQLiteColumn"};var fs=class extends ye{static[m]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new ps(e,this.config)}},ps=class extends se{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(as.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}},ms=class extends ye{static[m]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new hs(e,this.config)}},hs=class extends se{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(as.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}},gs=class extends ye{static[m]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new ys(e,this.config)}},ys=class extends se{static[m]="SQLiteBlobBuffer";mapFromDriverValue(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}getSQLType(){return"blob"}};function To(t,e){let{name:r,config:n}=nt(t,e);return n?.mode==="json"?new ms(r):n?.mode==="bigint"?new fs(r):new gs(r)}var bs=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 ws(e,this.config)}},ws=class extends se{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 hl(t){return(e,r)=>{let{name:n,config:o}=nt(e,r);return new bs(n,o,t)}}var kn=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()}},_n=class extends se{static[m]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}},vs=class extends kn{static[m]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new xs(e,this.config)}},xs=class extends _n{static[m]="SQLiteInteger"},ks=class extends kn{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 _s(e,this.config)}},_s=class extends _n{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}},Is=class extends kn{static[m]="SQLiteBooleanBuilder";constructor(e,r){super(e,"boolean","SQLiteBoolean"),this.config.mode=r}build(e){return new Ss(e,this.config)}},Ss=class extends _n{static[m]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}};function In(t,e){let{name:r,config:n}=nt(t,e);return n?.mode==="timestamp"||n?.mode==="timestamp_ms"?new ks(r,n.mode):n?.mode==="boolean"?new Is(r,n.mode):new vs(r)}var Es=class extends ye{static[m]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new js(e,this.config)}},js=class extends se{static[m]="SQLiteNumeric";mapFromDriverValue(e){return typeof e=="string"?e:String(e)}getSQLType(){return"numeric"}},Ts=class extends ye{static[m]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new As(e,this.config)}},As=class extends se{static[m]="SQLiteNumericNumber";mapFromDriverValue(e){return typeof e=="number"?e:Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}},Rs=class extends ye{static[m]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new Os(e,this.config)}},Os=class extends se{static[m]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}};function gl(t,e){let{name:r,config:n}=nt(t,e),o=n?.mode;return o==="number"?new Ts(r):o==="bigint"?new Rs(r):new Es(r)}var Ns=class extends ye{static[m]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new Ps(e,this.config)}},Ps=class extends se{static[m]="SQLiteReal";getSQLType(){return"real"}};function Ao(t){return new Ns(t??"")}var Cs=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 $s(e,this.config)}},$s=class extends se{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})`:""}`}},zs=class extends ye{static[m]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new qs(e,this.config)}},qs=class extends se{static[m]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}};function Sn(t,e={}){let{name:r,config:n}=nt(t,e);return n.mode==="json"?new zs(r):new Cs(r,n)}var K=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 o=(y(e,V)?e._.selectedFields:y(e,he)?e[H].selectedFields:e)[r];if(y(o,I.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let i=o.clone();return i.isSelectionField=!0,i}if(y(o,I)){if(this.config.sqlBehavior==="sql")return o;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 y(o,M)?this.config.alias?new Proxy(o,new or(new Proxy(o.table,new Pr(this.config.alias,this.config.replaceOriginalName??!1)))):o:typeof o!="object"||o===null?o:new Proxy(o,new t(this.config))}};var G=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 yl(){return{blob:To,customType:hl,integer:In,numeric:gl,real:Ao,text:Sn}}var Ls=Symbol.for("drizzle:SQLiteInlineForeignKeys"),ue=class extends v{static[m]="SQLiteTable";static Symbol=Object.assign({},v.Symbol,{InlineForeignKeys:Ls});[v.Symbol.Columns];[Ls]=[];[v.Symbol.ExtraConfigBuilder]=void 0};function Wp(t,e,r,n,o=t){let i=new ue(t,n,o),s=typeof e=="function"?e(yl()):e,a=Object.fromEntries(Object.entries(s).map(([l,u])=>{let d=u;d.setName(l);let p=d.build(i);return i[Ls].push(...d.buildForeignKeys(p,i)),[l,p]})),c=Object.assign(i,a);return c[v.Symbol.Columns]=a,c[v.Symbol.ExtraConfigColumns]=a,r&&(c[ue.Symbol.ExtraConfigBuilder]=r),c}var bl=(t,e,r)=>Wp(t,e,r);var Ro=class{constructor(e,r){this.name=e,this.unique=r}static[m]="SQLiteIndexBuilderOn";on(...e){return new Ds(this.name,e,this.unique)}},Ds=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 Ms(this.config,e)}},Ms=class{static[m]="SQLiteIndex";config;constructor(e,r){this.config={...e,table:r}}};function wl(t){return new Ro(t,!1)}function vl(t){return new Ro(t,!0)}function xl(...t){return t[0].columns?new Oo(t[0].columns,t[0].name):new Oo(t)}var Oo=class{static[m]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,r){this.columns=e,this.name=r}build(e){return new Ks(e,this.columns,this.name)}},Ks=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[ue.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}};function We(t){return y(t,ue)?[`${t[v.Symbol.BaseName]}`]:y(t,V)?t._.usedTables??[]:y(t,I)?t.usedTables??[]:[]}var En=class extends G{constructor(e,r,n,o){super(),this.table=e,this.session=r,this.dialect=n,this.config={table:e,withList:o}}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 K({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[ue.Symbol.Columns]){return this.config.returning=ae(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:We(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 Hp(t){return(t.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,n,o)=>{let i=o===0?n.toLowerCase():`${n[0].toUpperCase()}${n.slice(1)}`;return r+i},"")}function Jp(t){return t}var Cr=class{static[m]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Qp:e==="camelCase"?Hp:Jp}getColumnCasing(e){if(!e.keyAsName)return e.name;let r=e.table[v.Symbol.Schema]??"public",n=e.table[v.Symbol.OriginalName],o=`${r}.${n}.${e.name}`;return this.cache[o]||this.cacheTable(e.table),this.cache[o]}cacheTable(e){let r=e[v.Symbol.Schema]??"public",n=e[v.Symbol.OriginalName],o=`${r}.${n}`;if(!this.cachedTables[o]){for(let i of Object.values(e[v.Symbol.Columns])){let s=`${o}.${i.name}`;this.cache[s]=this.convert(i.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}};var vt=class extends Error{static[m]="DrizzleError";constructor({message:e,cause:r}){super(e),this.name="DrizzleError",this.cause=r}},Te=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)}},$r=class extends vt{static[m]="TransactionRollbackError";constructor(){super({message:"Rollback"})}};var ot=class extends ve{static[m]="PgDateColumnBaseBuilder";defaultNow(){return this.default(f`now()`)}};var kl=class extends ot{static[m]="PgDateBuilder";constructor(e){super(e,"date","PgDate")}build(e){return new jn(e,this.config)}},jn=class extends Z{static[m]="PgDate";getSQLType(){return"date"}mapFromDriverValue(e){return typeof e=="string"?new Date(e):e}mapToDriverValue(e){return e.toISOString()}},_l=class extends ot{static[m]="PgDateStringBuilder";constructor(e){super(e,"string","PgDateString")}build(e){return new Tn(e,this.config)}},Tn=class extends Z{static[m]="PgDateString";getSQLType(){return"date"}mapFromDriverValue(e){return typeof e=="string"?e:e.toISOString().slice(0,-14)}};var Il=class extends ve{static[m]="PgJsonBuilder";constructor(e){super(e,"json","PgJson")}build(e){return new An(e,this.config)}},An=class extends Z{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 Sl=class extends ve{static[m]="PgJsonbBuilder";constructor(e){super(e,"json","PgJsonb")}build(e){return new Rn(e,this.config)}},Rn=class extends Z{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 El=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 On(e,this.config)}},On=class extends Z{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})`}},jl=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 Us(e,this.config)}},Us=class extends Z{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})`}},Tl=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 Bs(e,this.config)}},Bs=class extends Z{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 Al=class extends ot{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 Nn(e,this.config)}},Nn=class extends Z{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 Rl=class extends ot{static[m]="PgTimestampBuilder";constructor(e,r,n){super(e,"date","PgTimestamp"),this.config.withTimezone=r,this.config.precision=n}build(e){return new Pn(e,this.config)}},Pn=class extends Z{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()},Ol=class extends ot{static[m]="PgTimestampStringBuilder";constructor(e,r,n){super(e,"string","PgTimestampString"),this.config.withTimezone=r,this.config.precision=n}build(e){return new Cn(e,this.config)}},Cn=class extends Z{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(),o=n<=0?"+":"-";return`${r}${o}${Math.floor(Math.abs(n)/60).toString().padStart(2,"0")}`}return r}};var Nl=class extends ve{static[m]="PgUUIDBuilder";constructor(e){super(e,"string","PgUUID")}defaultRandom(){return this.default(f`gen_random_uuid()`)}build(e){return new $n(e,this.config)}},$n=class extends Z{static[m]="PgUUID";getSQLType(){return"uuid"}};var Pl=Symbol.for("drizzle:PgInlineForeignKeys"),Cl=Symbol.for("drizzle:EnableRLS"),_e=class extends v{static[m]="PgTable";static Symbol=Object.assign({},v.Symbol,{InlineForeignKeys:Pl,EnableRLS:Cl});[Pl]=[];[Cl]=!1;[v.Symbol.ExtraConfigBuilder]=void 0;[v.Symbol.ExtraConfigColumns]={}};var No=class{static[m]="PgPrimaryKeyBuilder";columns;name;constructor(e,r){this.columns=e,this.name=r}build(e){return new Fs(e,this.columns,this.name)}},Fs=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[_e.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}};function $e(t,e){return ul(e)&&!ss(t)&&!y(t,xe)&&!y(t,bt)&&!y(t,M)&&!y(t,v)&&!y(t,he)?new xe(t,e):t}var it=(t,e)=>f`${t} = ${$e(e,t)}`,$l=(t,e)=>f`${t} <> ${$e(e,t)}`;function xt(...t){let e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?new I(e):new I([new fe("("),f.join(e,new fe(" and ")),new fe(")")])}function Vs(...t){let e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?new I(e):new I([new fe("("),f.join(e,new fe(" or ")),new fe(")")])}function zl(t){return f`not ${t}`}var ql=(t,e)=>f`${t} > ${$e(e,t)}`,Ll=(t,e)=>f`${t} >= ${$e(e,t)}`,Dl=(t,e)=>f`${t} < ${$e(e,t)}`,Ml=(t,e)=>f`${t} <= ${$e(e,t)}`;function Ws(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 Kl(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 Ul(t){return f`${t} is null`}function Bl(t){return f`${t} is not null`}function Fl(t){return f`exists ${t}`}function Vl(t){return f`not exists ${t}`}function Wl(t,e,r){return f`${t} between ${$e(e,t)} and ${$e(r,t)}`}function Ql(t,e,r){return f`${t} not between ${$e(e,t)} and ${$e(r,t)}`}function Hl(t,e){return f`${t} like ${e}`}function Jl(t,e){return f`${t} not like ${e}`}function Gl(t,e){return f`${t} ilike ${e}`}function Zl(t,e){return f`${t} not ilike ${e}`}function Yl(t){return f`${t} asc`}function Qs(t){return f`${t} desc`}var Po=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},Hs=class{constructor(e,r){this.table=e,this.config=r}static[m]="Relations"},st=class t extends Po{constructor(e,r,n,o){super(e,r,n?.relationName),this.config=n,this.isNullable=o}static[m]="One";withFieldName(e){let r=new t(this.sourceTable,this.referencedTable,this.config,this.isNullable);return r.fieldName=e,r}},ir=class t extends Po{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 Co(){return{and:xt,between:Wl,eq:it,exists:Fl,gt:ql,gte:Ll,ilike:Gl,inArray:Ws,isNull:Ul,isNotNull:Bl,like:Hl,lt:Dl,lte:Ml,ne:$l,not:zl,notBetween:Ql,notExists:Vl,notLike:Jl,notIlike:Zl,notInArray:Kl,or:Vs,sql:f}}function $o(){return{sql:f,asc:Yl,desc:Qs}}function zo(t,e){Object.keys(t).length===1&&"default"in t&&!y(t.default,v)&&(t=t.default);let r={},n={},o={};for(let[i,s]of Object.entries(t))if(y(s,v)){let a=yt(s),c=n[a];r[a]=i,o[i]={tsName:i,dbName:s[v.Symbol.Name],schema:s[v.Symbol.Schema],columns:s[v.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let u of Object.values(s[v.Symbol.Columns]))u.primary&&o[i].primaryKey.push(u);let l=s[v.Symbol.ExtraConfigBuilder]?.(s[v.Symbol.ExtraConfigColumns]);if(l)for(let u of Object.values(l))y(u,No)&&o[i].primaryKey.push(...u.columns)}else if(y(s,Hs)){let a=yt(s.table),c=r[a],l=s.config(e(s.table)),u;for(let[d,p]of Object.entries(l))if(c){let h=o[c];h.relations[d]=p,u&&h.primaryKey.push(...u)}else a in n||(n[a]={relations:{},primaryKey:u}),n[a].relations[d]=p}return{tables:o,tableNamesMap:r}}function Gp(t){return function(r,n){return new st(t,r,n,n?.fields.reduce((o,i)=>o&&i.notNull,!0)??!1)}}function Zp(t){return function(r,n){return new ir(t,r,n)}}function qo(t,e,r){if(y(r,st)&&r.config)return{fields:r.config.fields,references:r.config.references};let n=e[yt(r.referencedTable)];if(!n)throw new Error(`Table "${r.referencedTable[v.Symbol.Name]}" not found in schema`);let o=t[n];if(!o)throw new Error(`Table "${n}" not found in schema`);let i=r.sourceTable,s=e[yt(i)];if(!s)throw new Error(`Table "${i[v.Symbol.Name]}" not found in schema`);let a=[];for(let c of Object.values(o.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]&&y(a[0],st)&&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 "${s}.${r.fieldName}"`)}function Lo(t){return{one:Gp(t),many:Zp(t)}}function zr(t,e,r,n,o=i=>i){let i={};for(let[s,a]of n.entries())if(a.isJson){let c=e.relations[a.tsKey],l=r[s],u=typeof l=="string"?JSON.parse(l):l;i[a.tsKey]=y(c,st)?u&&zr(t,t[a.relationTableTsKey],u,a.selection,o):u.map(d=>zr(t,t[a.relationTableTsKey],d,a.selection,o))}else{let c=o(r[s]),l=a.field,u;y(l,M)?u=l:y(l,I)?u=l.decoder:u=l.sql.decoder,i[a.tsKey]=c===null?null:u.mapFromDriverValue(c)}return i}var $t=class extends he{static[m]="SQLiteViewBase"};var sr=class{static[m]="SQLiteDialect";casing;constructor(e){this.casing=new Cr(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,o]of e.entries())r.push(f`${f.identifier(o._.alias)} as (${o._.sql})`),n<e.length-1&&r.push(f`, `);return r.push(f` `),f.join(r)}buildDeleteQuery({table:e,where:r,returning:n,withList:o,limit:i,orderBy:s}){let a=this.buildWithCTE(o),c=n?f` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,l=r?f` where ${r}`:void 0,u=this.buildOrderBy(s),d=this.buildLimit(i);return f`${a}delete from ${e}${l}${c}${u}${d}`}buildUpdateSet(e,r){let n=e[v.Symbol.Columns],o=Object.keys(n).filter(s=>r[s]!==void 0||n[s]?.onUpdateFn!==void 0),i=o.length;return f.join(o.flatMap((s,a)=>{let c=n[s],l=c.onUpdateFn?.(),u=r[s]??(y(l,I)?l:f.param(l,c)),d=f`${f.identifier(this.casing.getColumnCasing(c))} = ${u}`;return a<i-1?[d,f.raw(", ")]:[d]}))}buildUpdateQuery({table:e,set:r,where:n,returning:o,withList:i,joins:s,from:a,limit:c,orderBy:l}){let u=this.buildWithCTE(i),d=this.buildUpdateSet(e,r),p=a&&f.join([f.raw(" from "),this.buildFromTable(a)]),h=this.buildJoins(s),w=o?f` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,b=n?f` where ${n}`:void 0,_=this.buildOrderBy(l),k=this.buildLimit(c);return f`${u}update ${e} set ${d}${p}${h}${b}${w}${_}${k}`}buildSelection(e,{isSingleTable:r=!1}={}){let n=e.length,o=e.flatMap(({field:i},s)=>{let a=[];if(y(i,I.Aliased)&&i.isSelectionField)a.push(f.identifier(i.fieldAlias));else if(y(i,I.Aliased)||y(i,I)){let c=y(i,I.Aliased)?i.sql:i;r?a.push(new I(c.queryChunks.map(l=>y(l,M)?f.identifier(this.casing.getColumnCasing(l)):l))):a.push(c),y(i,I.Aliased)&&a.push(f` as ${f.identifier(i.fieldAlias)}`)}else if(y(i,M)){let c=i.table[v.Symbol.Name];i.columnType==="SQLiteNumericBigInt"?r?a.push(f`cast(${f.identifier(this.casing.getColumnCasing(i))} as text)`):a.push(f`cast(${f.identifier(c)}.${f.identifier(this.casing.getColumnCasing(i))} as text)`):r?a.push(f.identifier(this.casing.getColumnCasing(i))):a.push(f`${f.identifier(c)}.${f.identifier(this.casing.getColumnCasing(i))}`)}else if(y(i,V)){let c=Object.entries(i._.selectedFields);if(c.length===1){let l=c[0][1],u=y(l,I)?l.decoder:y(l,M)?{mapFromDriverValue:d=>l.mapFromDriverValue(d)}:l.sql.decoder;u&&(i._.sql.decoder=u)}a.push(i)}return s<n-1&&a.push(f`, `),a});return f.join(o)}buildJoins(e){if(!e||e.length===0)return;let r=[];if(e)for(let[n,o]of e.entries()){n===0&&r.push(f` `);let i=o.table,s=o.on?f` on ${o.on}`:void 0;if(y(i,ue)){let a=i[ue.Symbol.Name],c=i[ue.Symbol.Schema],l=i[ue.Symbol.OriginalName],u=a===l?void 0:o.alias;r.push(f`${f.raw(o.joinType)} join ${c?f`${f.identifier(c)}.`:void 0}${f.identifier(l)}${u&&f` ${f.identifier(u)}`}${s}`)}else r.push(f`${f.raw(o.joinType)} join ${i}${s}`);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,o]of e.entries())r.push(o),n<e.length-1&&r.push(f`, `);return r.length>0?f` order by ${f.join(r)}`:void 0}buildFromTable(e){return y(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:o,having:i,table:s,joins:a,orderBy:c,groupBy:l,limit:u,offset:d,distinct:p,setOperators:h}){let w=n??ae(r);for(let re of w)if(y(re.field,M)&&me(re.field.table)!==(y(s,V)?s._.alias:y(s,$t)?s[H].name:y(s,I)?void 0:me(s))&&!(J=>a?.some(({alias:Pe})=>Pe===(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,_=this.buildWithCTE(e),k=p?f` distinct`:void 0,C=this.buildSelection(w,{isSingleTable:b}),q=this.buildFromTable(s),O=this.buildJoins(a),X=o?f` where ${o}`:void 0,L=i?f` having ${i}`:void 0,S=[];if(l)for(let[re,J]of l.entries())S.push(J),re<l.length-1&&S.push(f`, `);let A=S.length>0?f` group by ${f.join(S)}`:void 0,Q=this.buildOrderBy(c),ie=this.buildLimit(u),we=d?f` offset ${d}`:void 0,le=f`${_}select${k} ${C} from ${q}${O}${X}${A}${L}${Q}${ie}${we}`;return h.length>0?this.buildSetOperations(le,h):le}buildSetOperations(e,r){let[n,...o]=r;if(!n)throw new Error("Cannot pass undefined values to any set operator");return o.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:n}),o)}buildSetOperationQuery({leftSelect:e,setOperator:{type:r,isAll:n,rightSelect:o,limit:i,orderBy:s,offset:a}}){let c=f`${e.getSQL()} `,l=f`${o.getSQL()}`,u;if(s&&s.length>0){let w=[];for(let b of s)if(y(b,se))w.push(f.identifier(b.name));else if(y(b,I)){for(let _=0;_<b.queryChunks.length;_++){let k=b.queryChunks[_];y(k,se)&&(b.queryChunks[_]=f.identifier(this.casing.getColumnCasing(k)))}w.push(f`${b}`)}else w.push(f`${b}`);u=f` order by ${f.join(w,f`, `)}`}let d=typeof i=="object"||typeof i=="number"&&i>=0?f` limit ${i}`:void 0,p=f.raw(`${r} ${n?"all ":""}`),h=a?f` offset ${a}`:void 0;return f`${c}${p}${l}${u}${d}${h}`}buildInsertQuery({table:e,values:r,onConflict:n,returning:o,withList:i,select:s}){let a=[],c=e[v.Symbol.Columns],l=Object.entries(c).filter(([b,_])=>!_.shouldDisableInsert()),u=l.map(([,b])=>f.identifier(this.casing.getColumnCasing(b)));if(s){let b=r;y(b,I)?a.push(b):a.push(b.getSQL())}else{let b=r;a.push(f.raw("values "));for(let[_,k]of b.entries()){let C=[];for(let[q,O]of l){let X=k[q];if(X===void 0||y(X,xe)&&X.value===void 0){let L;if(O.default!==null&&O.default!==void 0)L=y(O.default,I)?O.default:f.param(O.default,O);else if(O.defaultFn!==void 0){let S=O.defaultFn();L=y(S,I)?S:f.param(S,O)}else if(!O.default&&O.onUpdateFn!==void 0){let S=O.onUpdateFn();L=y(S,I)?S:f.param(S,O)}else L=f`null`;C.push(L)}else C.push(X)}a.push(C),_<b.length-1&&a.push(f`, `)}}let d=this.buildWithCTE(i),p=f.join(a),h=o?f` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,w=n?.length?f.join(n):void 0;return f`${d}insert into ${e} ${u} ${p}${w}${h}`}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:o,tableConfig:i,queryConfig:s,tableAlias:a,nestedQueryRelation:c,joinOn:l}){let u=[],d,p,h=[],w,b=[];if(s===!0)u=Object.entries(i.columns).map(([C,q])=>({dbKey:q.name,tsKey:C,field:ge(q,a),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let k=Object.fromEntries(Object.entries(i.columns).map(([S,A])=>[S,ge(A,a)]));if(s.where){let S=typeof s.where=="function"?s.where(k,Co()):s.where;w=S&&Pt(S,a)}let C=[],q=[];if(s.columns){let S=!1;for(let[A,Q]of Object.entries(s.columns))Q!==void 0&&A in i.columns&&(!S&&Q===!0&&(S=!0),q.push(A));q.length>0&&(q=S?q.filter(A=>s.columns?.[A]===!0):Object.keys(i.columns).filter(A=>!q.includes(A)))}else q=Object.keys(i.columns);for(let S of q){let A=i.columns[S];C.push({tsKey:S,value:A})}let O=[];s.with&&(O=Object.entries(s.with).filter(S=>!!S[1]).map(([S,A])=>({tsKey:S,queryConfig:A,relation:i.relations[S]})));let X;if(s.extras){X=typeof s.extras=="function"?s.extras(k,{sql:f}):s.extras;for(let[S,A]of Object.entries(X))C.push({tsKey:S,value:vn(A,a)})}for(let{tsKey:S,value:A}of C)u.push({dbKey:y(A,I.Aliased)?A.fieldAlias:i.columns[S].name,tsKey:S,field:y(A,M)?ge(A,a):A,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof s.orderBy=="function"?s.orderBy(k,$o()):s.orderBy??[];Array.isArray(L)||(L=[L]),h=L.map(S=>y(S,M)?ge(S,a):Pt(S,a)),d=s.limit,p=s.offset;for(let{tsKey:S,queryConfig:A,relation:Q}of O){let ie=qo(r,n,Q),we=yt(Q.referencedTable),le=n[we],re=`${a}_${S}`,J=xt(...ie.fields.map(($i,zi)=>it(ge(ie.references[zi],re),ge($i,a)))),Pe=this.buildRelationalQuery({fullSchema:e,schema:r,tableNamesMap:n,table:e[le],tableConfig:r[le],queryConfig:y(Q,st)?A===!0?{limit:1}:{...A,limit:1}:A,tableAlias:re,joinOn:J,nestedQueryRelation:Q}),mn=f`(${Pe.sql})`.as(S);u.push({dbKey:S,tsKey:S,field:mn,relationTableTsKey:le,isJson:!0,selection:Pe.selection})}}if(u.length===0)throw new vt({message:`No fields selected for table "${i.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 _;if(w=xt(l,w),c){let k=f`json_array(${f.join(u.map(({field:O})=>y(O,se)?f.identifier(this.casing.getColumnCasing(O)):y(O,I.Aliased)?O.sql:O),f`, `)})`;y(c,ir)&&(k=f`coalesce(json_group_array(${k}), json_array())`);let C=[{dbKey:"data",tsKey:"data",field:k.as("data"),isJson:!0,relationTableTsKey:i.tsName,selection:u}];d!==void 0||p!==void 0||h.length>0?(_=this.buildSelectQuery({table:wt(o,a),fields:{},fieldsFlat:[{path:[],field:f.raw("*")}],where:w,limit:d,offset:p,orderBy:h,setOperators:[]}),w=void 0,d=void 0,p=void 0,h=void 0):_=wt(o,a),_=this.buildSelectQuery({table:y(_,ue)?_:new V(_,{},a),fields:{},fieldsFlat:C.map(({field:O})=>({path:[],field:y(O,M)?ge(O,a):O})),joins:b,where:w,limit:d,offset:p,orderBy:h,setOperators:[]})}else _=this.buildSelectQuery({table:wt(o,a),fields:{},fieldsFlat:u.map(({field:k})=>({path:[],field:y(k,M)?ge(k,a):k})),joins:b,where:w,limit:d,offset:p,orderBy:h,setOperators:[]});return{tableTsKey:i.tsName,sql:_,selection:u}}},Do=class extends sr{static[m]="SQLiteSyncDialect";migrate(e,r,n){let o=n===void 0||typeof n=="string"?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",i=f`
9
+ CREATE TABLE IF NOT EXISTS ${f.identifier(o)} (
10
+ id SERIAL PRIMARY KEY,
11
+ hash text NOT NULL,
12
+ created_at numeric
13
+ )
14
+ `;r.run(i);let a=r.values(f`SELECT id, hash, created_at FROM ${f.identifier(o)} 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(o)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}r.run(f`COMMIT`)}catch(c){throw r.run(f`ROLLBACK`),c}}},Mo=class extends sr{static[m]="SQLiteAsyncDialect";async migrate(e,r,n){let o=n===void 0||typeof n=="string"?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",i=f`
15
+ CREATE TABLE IF NOT EXISTS ${f.identifier(o)} (
16
+ id SERIAL PRIMARY KEY,
17
+ hash text NOT NULL,
18
+ created_at numeric
19
+ )
20
+ `;await r.run(i);let a=(await r.values(f`SELECT id, hash, created_at FROM ${f.identifier(o)} 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(o)} ("hash", "created_at") VALUES(${l.hash}, ${l.folderMillis})`)}})}};var qr=class{static[m]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}};var Ke=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:y(e,V)?n=Object.fromEntries(Object.keys(e._.selectedFields).map(o=>[o,e[o]])):y(e,$t)?n=e[H].selectedFields:y(e,I)?n={}:n=Eo(e),new Ko({table:e,fields:n,isPartialSelect:r,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}},Js=class extends qr{static[m]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:r,isPartialSelect:n,session:o,dialect:i,withList:s,distinct:a}){super(),this.config={withList:s,table:e,fields:{...r},distinct:a,setOperators:[]},this.isPartialSelect=n,this.session=o,this.dialect=i,this._={selectedFields:r,config:this.config},this.tableName=Ce(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{};for(let c of We(e))this.usedTables.add(c)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(r,n)=>{let o=this.tableName,i=Ce(r);for(let s of We(r))this.usedTables.add(s);if(typeof i=="string"&&this.config.joins?.some(s=>s.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"&&!y(r,I))){let s=y(r,V)?r._.selectedFields:y(r,he)?r[H].selectedFields:r[v.Symbol.Columns];this.config.fields[i]=s}if(typeof n=="function"&&(n=n(new Proxy(this.config.fields,new K({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:n,table:r,joinType:e,alias:i}),typeof i=="string")switch(e){case"left":{this.joinsNotNullableMap[i]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([s])=>[s,!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(([s])=>[s,!1])),this.joinsNotNullableMap[i]=!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 o=typeof n=="function"?n(Yp()):n;if(!rt(this.getSelectedFields(),o.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:o}),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 K({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new K({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 K({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 K({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(...We(this.config.table)),this.config.joins)for(let n of this.config.joins)r.push(...We(n.table));return new Proxy(new V(this.getSQL(),this.config.fields,e,!1,[...new Set(r)]),new K({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new K({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}},Ko=class extends Js{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=ae(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()}};So(Ko,[G]);function Uo(t,e){return(r,n,...o)=>{let i=[n,...o].map(s=>({type:t,isAll:e,rightSelect:s}));for(let s of i)if(!rt(r.getSelectedFields(),s.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(i)}}var Yp=()=>({union:Xp,unionAll:em,intersect:tm,except:rm}),Xp=Uo("union",!1),em=Uo("union",!0),tm=Uo("intersect",!1),rm=Uo("except",!1);var Lr=class{static[m]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=y(e,sr)?e:void 0,this.dialectConfig=y(e,sr)?void 0:e}$with=(e,r)=>{let n=this;return{as:i=>(typeof i=="function"&&(i=i(n)),new Proxy(new tt(i.getSQL(),r??("getSelectedFields"in i?i.getSelectedFields()??{}:{}),e,!0),new K({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...e){let r=this;function n(i){return new Ke({fields:i??void 0,session:void 0,dialect:r.getDialect(),withList:e})}function o(i){return new Ke({fields:i??void 0,session:void 0,dialect:r.getDialect(),withList:e,distinct:!0})}return{select:n,selectDistinct:o}}select(e){return new Ke({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Ke({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||(this.dialect=new Do(this.dialectConfig)),this.dialect}};var zn=class{constructor(e,r,n,o){this.table=e,this.session=r,this.dialect=n,this.withList=o}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 o={},i=this.table[v.Symbol.Columns];for(let s of Object.keys(n)){let a=n[s];o[s]=y(a,I)?a:new xe(a,i[s])}return o});return new Bo(this.table,r,this.session,this.dialect,this.withList)}select(e){let r=typeof e=="function"?e(new Lr):e;if(!y(r,I)&&!rt(this.table[Nr],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 Bo(this.table,r,this.session,this.dialect,this.withList,!0)}},Bo=class extends G{constructor(e,r,n,o,i,s){super(),this.session=n,this.dialect=o,this.config={table:e,values:r,withList:i,select:s}}static[m]="SQLiteInsert";config;returning(e=this.config.table[ue.Symbol.Columns]){return this.config.returning=ae(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,o=e.setWhere?f` where ${e.setWhere}`:void 0,i=Array.isArray(e.target)?f`${e.target}`:f`${[e.target]}`,s=this.dialect.buildUpdateSet(this.config.table,Ct(this.config.table,e.set));return this.config.onConflict.push(f` on conflict ${i}${n} do update set ${s}${r}${o}`),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:We(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 qn=class{constructor(e,r,n,o){this.table=e,this.session=r,this.dialect=n,this.withList=o}static[m]="SQLiteUpdateBuilder";set(e){return new Gs(this.table,Ct(this.table,e),this.session,this.dialect,this.withList)}},Gs=class extends G{constructor(e,r,n,o,i){super(),this.session=n,this.dialect=o,this.config={set:r,table:e,withList:i,joins:[]}}static[m]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(r,n)=>{let o=Ce(r);if(typeof o=="string"&&this.config.joins.some(i=>i.alias===o))throw new Error(`Alias "${o}" is already used in this query`);if(typeof n=="function"){let i=this.config.from?y(r,ue)?r[v.Symbol.Columns]:y(r,V)?r._.selectedFields:y(r,$t)?r[H].selectedFields:void 0:void 0;n=n(new Proxy(this.config.table[v.Symbol.Columns],new K({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),i&&new Proxy(i,new K({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:n,table:r,joinType:e,alias:o}),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 K({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[ue.Symbol.Columns]){return this.config.returning=ae(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:We(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 Fo=class t extends I{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 Vo=class{constructor(e,r,n,o,i,s,a,c){this.mode=e,this.fullSchema=r,this.schema=n,this.tableNamesMap=o,this.table=i,this.tableConfig=s,this.dialect=a,this.session=c}static[m]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new Wo(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many"):new Ln(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many")}findFirst(e){return this.mode==="sync"?new Wo(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Ln(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}},Ln=class extends G{constructor(e,r,n,o,i,s,a,c,l){super(),this.fullSchema=e,this.schema=r,this.tableNamesMap=n,this.table=o,this.tableConfig=i,this.dialect=s,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,(o,i)=>{let s=o.map(a=>zr(this.schema,this.tableConfig,a,r.selection,i));return this.mode==="first"?s[0]:s})}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()}},Wo=class extends Ln{static[m]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}};var ar=class extends G{constructor(e,r,n,o,i){super(),this.execute=e,this.getSQL=r,this.dialect=o,this.mapBatchResult=i,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 Dr=class{constructor(e,r,n,o){this.resultKind=e,this.dialect=r,this.session=n,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let i=this.query;if(this._.schema)for(let[s,a]of Object.entries(this._.schema))i[s]=new Vo(e,o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[s],a,r,n);this.$cache={invalidate:async s=>{}}}static[m]="BaseSQLiteDatabase";query;$with=(e,r)=>{let n=this;return{as:i=>(typeof i=="function"&&(i=i(new Lr(n.dialect))),new Proxy(new tt(i.getSQL(),r??("getSelectedFields"in i?i.getSelectedFields()??{}:{}),e,!0),new K({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(e,r){return new Fo({source:e,filters:r,session:this.session})}with(...e){let r=this;function n(c){return new Ke({fields:c??void 0,session:r.session,dialect:r.dialect,withList:e})}function o(c){return new Ke({fields:c??void 0,session:r.session,dialect:r.dialect,withList:e,distinct:!0})}function i(c){return new qn(c,r.session,r.dialect,e)}function s(c){return new zn(c,r.session,r.dialect,e)}function a(c){return new En(c,r.session,r.dialect,e)}return{select:n,selectDistinct:o,update:i,insert:s,delete:a}}select(e){return new Ke({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Ke({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new qn(e,this.session,this.dialect)}$cache;insert(e){return new zn(e,this.session,this.dialect)}delete(e){return new En(e,this.session,this.dialect)}run(e){let r=typeof e=="string"?f.raw(e):e.getSQL();return this.resultKind==="async"?new ar(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 ar(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 ar(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 ar(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 Zs=class{static[m]="Cache"},at=class extends Zs{strategy(){return"all"}static[m]="NoopCache";async get(e){}async put(e,r,n,o){}async onMutate(e){}};async function Mr(t,e){let r=`${t}-${JSON.stringify(e)}`,o=new TextEncoder().encode(r),i=await crypto.subtle.digest("SHA-256",o);return[...new Uint8Array(i)].map(c=>c.toString(16).padStart(2,"0")).join("")}var Ys=class extends G{constructor(e){super(),this.resultCb=e}static[m]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}},Qo=class{constructor(e,r,n,o,i,s){this.mode=e,this.executeMethod=r,this.query=n,this.cache=o,this.queryMetadata=i,this.cacheConfig=s,o&&o.strategy()==="all"&&s===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||y(this.cache,at)||this.queryMetadata===void 0)try{return await n()}catch(o){throw new Te(e,r,o)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await n()}catch(o){throw new Te(e,r,o)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[o]=await Promise.all([n(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return o}catch(o){throw new Te(e,r,o)}if(!this.cacheConfig)try{return await n()}catch(o){throw new Te(e,r,o)}if(this.queryMetadata.type==="select"){let o=await this.cache.get(this.cacheConfig.tag??await Mr(e,r),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(o===void 0){let i;try{i=await n()}catch(s){throw new Te(e,r,s)}return await this.cache.put(this.cacheConfig.tag??await Mr(e,r),i,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),i}return o}try{return await n()}catch(o){throw new Te(e,r,o)}}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 Ys(()=>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)}}},Ho=class{constructor(e){this.dialect=e}static[m]="SQLiteSession";prepareOneTimeQuery(e,r,n,o,i,s,a){return this.prepareQuery(e,r,n,o,i,s,a)}run(e){let r=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(r,void 0,"run",!1).run()}catch(n){throw new vt({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")}},Jo=class extends Dr{constructor(e,r,n,o,i=0){super(e,r,n,o),this.schema=o,this.nestedIndex=i}static[m]="SQLiteTransaction";rollback(){throw new $r}};var Xs=class{static[m]="ConsoleLogWriter";write(e){console.log(e)}},Kr=class{static[m]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new Xs}logQuery(e,r){let n=r.map(i=>{try{return JSON.stringify(i)}catch{return String(i)}}),o=n.length?` -- params: [${n.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}},Ur=class{static[m]="NoopLogger";logQuery(){}};var ea=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})}},ta=class{index(e){return new Go("index",e)}unique(e){return new Go("unique",e)}},Go=class{kind;name;constructor(e,r){this.kind=e,this.name=r}on(...e){return{kind:this.kind,name:this.name,columns:e}}},cr={id:t=>kt("id",t).notNull(),int:t=>kt("int",t),bigint:t=>kt("bigint",t),text:t=>kt("text",t),boolean:t=>kt("boolean",t),real:t=>kt("real",t),blob:t=>kt("blob",t),json:t=>kt("json",t),timestampMs:t=>kt("timestampMs",t),table:um},sI=cr.timestampMs("created_at").notNull().defaultNow(),aI=cr.timestampMs("updated_at").notNull().defaultNow();function Xl(t){let e=eu(t.databaseName),r=Object.fromEntries(Object.entries(t.tables).map(([o,i])=>[o,{logicalName:i.logicalName,physicalName:tu({extensionId:t.extensionId,databaseName:e,tableName:i.logicalName}),columns:i.columns,indexes:i.indexes,primaryKey:i.primaryKey}])),n={extensionId:t.extensionId,databaseName:e,tables:r};return Object.assign(n,im(r))}function eu(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 nm(t){return`${t.extensionId}_${eu(t.databaseName)}`}function tu(t){return`${nm(t)}_${t.tableName}`}function ra(t){return t.config}function na(t,e){return e.config.name??om(t)}function om(t){return t.replace(/([a-z0-9])([A-Z])/gu,"$1_$2").replace(/[-\s]+/gu,"_").toLowerCase()}function kt(t,e){return new ea({kind:t,name:e,nullable:!0,primaryKey:!1,autoIncrement:!1,unique:!1})}function im(t){return Object.fromEntries(Object.entries(t).map(([e,r])=>[e,sm(r)]))}function sm(t){let e=Object.fromEntries(Object.entries(t.columns).map(([r,n])=>[r,am(r,n)]));return bl(t.physicalName,e,r=>{let n=t.primaryKey?.map(i=>r[i]),o=t.indexes.map(i=>{let s=i.columns.map(c=>r[c]);return(i.kind==="unique"?vl(i.name):wl(i.name)).on(s[0],...s.slice(1))});return n?.length?[xl({columns:[n[0],...n.slice(1)]}),...o]:o})}function am(t,e){let r=ra(e),n=na(t,e),o=cm(n,r);return r.primaryKey?o=r.autoIncrement?o.primaryKey({autoIncrement:!0}):o.primaryKey():r.nullable||(o=o.notNull()),r.unique&&(o=o.unique()),r.default&&(o=o.default(lm(r.default))),o}function cm(t,e){switch(e.kind){case"id":case"int":case"bigint":case"timestampMs":return In(t,{mode:"number"});case"boolean":return In(t,{mode:"boolean"});case"real":return Ao(t);case"blob":return To(t,{mode:"buffer"});case"json":return Sn(t,{mode:"json"});case"text":return Sn(t)}}function lm(t){return t.kind==="now"?f`(cast(strftime('%s','now') as integer) * 1000)`:t.kind==="emptyJson"?{}:t.value}function um(t,e,r){let n=r?.(new ta),o=n?.primaryKey;if(o&&(o.length===0||new Set(o).size!==o.length||Object.values(e).some(i=>i.config.primaryKey)||o.some(i=>!e[i]||e[i].config.nullable||e[i].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:o}}var Zo=class extends Ho{constructor(e,r,n,o,i={}){super(r),this.client=e,this.schema=n,this.batchCLient=o,this.logger=i.logger??new Ur,this.cache=i.cache??new at}static[m]="SQLiteRemoteSession";logger;cache;prepareQuery(e,r,n,o,i,s,a){return new ia(this.client,e,this.logger,this.cache,s,a,r,n,o,i)}async batch(e){let r=[],n=[];for(let i of e){let s=i._prepare(),a=s.getQuery();r.push(s),n.push({sql:a.sql,params:a.params,method:a.method})}return(await this.batchCLient(n)).map((i,s)=>r[s].mapResult(i,!0))}async transaction(e,r){let n=new oa("async",this.dialect,this,this.schema);await this.run(f.raw(`begin${r?.behavior?" "+r.behavior:""}`));try{let o=await e(n);return await this.run(f`commit`),o}catch(o){throw await this.run(f`rollback`),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}},oa=class t extends Jo{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 o=await e(n);return await this.session.run(f.raw(`release savepoint ${r}`)),o}catch(o){throw await this.session.run(f.raw(`rollback to savepoint ${r}`)),o}}},ia=class extends Qo{constructor(e,r,n,o,i,s,a,c,l,u){super("async",c,r,o,i,s),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=nr(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=>xn(this.fields,n,this.joinsNotNullableMap))}async all(e){let{query:r,logger:n,client:o}=this,i=nr(r.params,e??{});n.logQuery(r.sql,i);let{rows:s}=await this.queryWithCache(r.sql,i,async()=>await o(r.sql,i,"all"));return this.mapAllResult(s)}async get(e){let{query:r,logger:n,client:o}=this,i=nr(r.params,e??{});n.logQuery(r.sql,i);let s=await this.queryWithCache(r.sql,i,async()=>await o(r.sql,i,"get"));return this.mapGetResult(s.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]):xn(this.fields,n,this.joinsNotNullableMap)}async values(e){let r=nr(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 sa=class extends Dr{static[m]="SqliteRemoteDatabase";async batch(e){return this.session.batch(e)}};function ru(t,e,r){let n=new Mo({casing:r?.casing}),o,i,s,a={};e&&(typeof e=="function"?(s=e,a=r??{}):(s=void 0,a=e),a.logger===!0?o=new Kr:a.logger!==!1&&(o=a.logger,i=a.cache));let c;if(a.schema){let d=zo(a.schema,Lo);c={fullSchema:a.schema,schema:d.tables,tableNamesMap:d.tableNamesMap}}let l=new Zo(t,n,c,s,{logger:o,cache:i}),u=new sa("async",n,l,c);return u.$cache=i,u.$cache&&(u.$cache.invalidate=i?.onMutate),u}function nu(t,e){return ru(async(r,n,o)=>{let i=o==="run"?"run":"values",a=(await t.execute({type:"query",statement:{sql:r,params:n,method:i}})).rows;return{rows:o==="get"?a[0]:a}},async r=>(await t.execute({type:"transactionBatch",statements:r.map(o=>({sql:o.sql,params:o.params,method:o.method==="run"?"run":"values"}))})).results.map((o,i)=>({rows:r[i]?.method==="get"?o.rows[0]:o.rows})),e)}var Dn=Object.freeze({bytes:16*1024*1024,entries:256,rows:5e4,fieldBytes:1024*1024,depth:64}),iu=new TextEncoder;function dm(t){let e=new Set,r=0,n=i=>{if(r+=iu.encode(i).byteLength,r>Dn.bytes)throw new Error("Dataset \u8D85\u51FA\u6587\u4EF6\u5927\u5C0F\u9650\u5236\u3002");return i};function o(i,s){if(s>Dn.depth)throw new Error("Dataset \u5D4C\u5957\u8FC7\u6DF1\u3002");if(i===null||typeof i=="boolean"||typeof i=="string"||typeof i=="number"&&Number.isFinite(i))return n(JSON.stringify(i));if(!i||typeof i!="object")throw new Error("Dataset \u53EA\u80FD\u5305\u542B\u7EAF JSON \u503C\u3002");if(e.has(i))throw new Error("Dataset \u4E0D\u5141\u8BB8\u5FAA\u73AF\u5F15\u7528\u3002");if(!Array.isArray(i)&&Object.getPrototypeOf(i)!==Object.prototype&&Object.getPrototypeOf(i)!==null)throw new Error("Dataset \u4E0D\u5141\u8BB8 class\u3001Date \u6216\u5176\u5B83\u5B9E\u4F8B\u3002");let a=Object.getOwnPropertyDescriptors(i);if(Object.getOwnPropertySymbols(i).length||Object.entries(a).some(([c,l])=>(!Array.isArray(i)||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(i);try{if(Array.isArray(i)){if(Object.keys(i).length!==i.length||Object.keys(i).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,i.length-1))),`[${Array.from({length:i.length},(l,u)=>o(a[String(u)].value,s+1)).join(",")}]`}let c=Object.keys(a).sort();return n("{}"+",".repeat(Math.max(0,c.length-1))),`{${c.map(l=>`${n(JSON.stringify(l)+":")}${o(a[l].value,s+1)}`).join(",")}}`}finally{e.delete(i)}}return o(t,0)}function su(t,e){let r=aa(JSON.parse(dm(t)),"Dataset");if(ou(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>Dn.entries)throw new Error("Dataset entries \u65E0\u6548\u6216\u8D85\u9650\u3002");let n=new Map(Object.values(e.metadata.tables??{}).map(i=>[i.tableName,i])),o=0;for(let i of r.entries){let s=aa(i,"Dataset entry");ou(s,["tableName","rows"]);let a=typeof s.tableName=="string"?n.get(s.tableName):void 0;if(!a?.columns)throw new Error("Dataset \u5F15\u7528\u4E86\u672A\u77E5\u8868\u3002");if(!Array.isArray(s.rows)||(o+=s.rows.length)>Dn.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 s.rows){let p=aa(d,"Dataset row");for(let h of Object.keys(p)){if(!Object.hasOwn(c,h))throw new Error(`Dataset \u672A\u77E5\u5B57\u6BB5\uFF1A${h}`);if(iu.encode(JSON.stringify(p[h])).byteLength>Dn.fieldBytes)throw new Error(`Dataset \u5B57\u6BB5\u8D85\u9650\uFF1A${h}`);fm(p[h],c[h],h)}for(let[h,w]of Object.entries(c)){if(u.includes(h)&&(!Object.hasOwn(p,h)||p[h]===null))throw new Error(`Dataset \u7F3A\u5931\u7A33\u5B9A\u4E3B\u952E\uFF1A${h}`);if(!Object.hasOwn(p,h)&&w.notNull&&w.default===void 0)throw new Error(`Dataset \u7F3A\u5931\u5FC5\u586B\u5B57\u6BB5\uFF1A${h}`)}}}return r}function fm(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 aa(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} \u5FC5\u987B\u662F\u5BF9\u8C61\u3002`);return t}function ou(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 cu(t,e,r={}){let n=lu(e),o=0;for(let a of n.values()){let c=mm(a);c&&(await t.execute({type:"query",statement:{sql:c,method:"run"}}),await gm(t,a),await ym(t,a),o+=1)}for(let a of e.sqliteMigrations??[])await t.execute({type:"applyMigration",migrationId:a.id,statements:a.statements});let i=await vm(t,pm(e),n),s=r.dataset?await Sm(t,e,r.dataset):0;return{tablesEnsured:o,bootstrapRows:i,datasetRows:s}}function lu(t){let e=new Map;for(let r of Object.values(t.tables??{})){let n=ct(r?.tableName);n&&e.set(n,r)}return e}function pm(t){return Array.isArray(t.bootstrap)?t.bootstrap:Array.isArray(t.install)?t.install:[]}function mm(t){let e=ct(t.tableName);if(!e||!t.columns||typeof t.columns!="object")return"";let r=Object.values(t.columns).map(n=>uu(n)).filter(Boolean);return r.length===0?"":(hm(r,t),`CREATE TABLE IF NOT EXISTS "${Qe(e)}" (${r.join(", ")});`)}function hm(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(o=>o.name===n&&o.notNull)))throw new Error(`Invalid composite primary key for ${e.tableName}.`);t.push(`PRIMARY KEY (${e.primaryKey.map(n=>`"${Qe(n)}"`).join(", ")})`)}async function gm(t,e){let r=ct(e.tableName);if(!r||!e.columns||typeof e.columns!="object")return;let n=await t.execute({type:"query",statement:{sql:`PRAGMA table_info("${Qe(r)}")`,method:"all"}}),o=new Set((Array.isArray(n.rows)?n.rows:[]).flatMap(i=>Array.isArray(i)?typeof i[1]=="string"?[i[1]]:[]:i&&typeof i=="object"&&"name"in i&&typeof i.name=="string"?[i.name]:[]));for(let i of Object.values(e.columns)){let s=ct(i.name);if(!s||o.has(s))continue;if(i.primary||i.primaryKey||i.autoIncrement||i.unique)throw new Error(`Cannot safely add constrained SQLite column ${r}.${s} from metadata; use an explicit migration.`);if(i.notNull&&!du(i))throw new Error(`Cannot safely add NOT NULL SQLite column ${r}.${s} without a default; use an explicit migration.`);let a=uu(i);a&&await t.execute({type:"query",statement:{sql:`ALTER TABLE "${Qe(r)}" ADD COLUMN ${a};`,method:"run"}})}}async function ym(t,e){let r=ct(e.tableName);if(r)for(let n of e.indexes??[]){let o=bm(r,n);o&&await t.execute({type:"query",statement:{sql:o,method:"run"}})}}function bm(t,e){let r=ct(e.name),n=wm(e.columns);return!r||n.length===0?"":["CREATE",e.unique===!0?"UNIQUE INDEX IF NOT EXISTS":"INDEX IF NOT EXISTS",`"${Qe(r)}"`,"ON",`"${Qe(t)}"`,`(${n.map(o=>`"${Qe(o)}"`).join(", ")});`].join(" ")}function wm(t){return Array.isArray(t)?t.map(e=>ct(e)).filter(e=>!!e):[]}function uu(t){let e=ct(t.name);if(!e)return"";let r=_m(t.columnType),n=!!(t.primary||t.primaryKey),o=[`"${Qe(e)}"`,r];t.notNull&&!n&&o.push("NOT NULL"),n&&o.push(t.autoIncrement&&r==="INTEGER"?"PRIMARY KEY AUTOINCREMENT":"PRIMARY KEY"),t.unique&&!n&&o.push("UNIQUE");let i=du(t);return i&&o.push(i),o.join(" ")}function du(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 ${au(e.value)}`:`DEFAULT ${au(e)}`}function au(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 vm(t,e,r){let n=0;for(let o of e){let i=ct(o.tableName),s=Array.isArray(o.rows)?o.rows:[];if(!i||s.length===0)continue;let a=r.get(i);if(a)for(let c of s)n+=await xm(t,i,a,c)}return n}async function xm(t,e,r,n){let o=km(r),i=Object.keys(n).map(a=>{let c=o.get(a)??o.get(`@name:${a}`);return c?{columnName:c,value:Im(n[a])}:null}).filter(a=>a!==null);if(i.length===0)return 0;await t.execute({type:"query",statement:{sql:[`INSERT OR IGNORE INTO "${Qe(e)}"`,`(${i.map(a=>`"${Qe(a.columnName)}"`).join(", ")})`,`VALUES (${i.map(()=>"?").join(", ")});`].join(" "),params:i.map(a=>a.value),method:"run"}});let s=await t.execute({type:"query",statement:{sql:"SELECT changes() AS changes",method:"get"}});return Number(s.rows&&s.rows.changes)||0}function km(t){let e=new Map;for(let[r,n]of Object.entries(t.columns??{})){let o=ct(n.name);o&&(e.set(r,o),e.set(`@name:${o}`,o))}return e}function _m(t){return t==="SQLiteInteger"||t==="SQLiteBoolean"||t==="SQLiteTimestamp"?"INTEGER":t==="SQLiteReal"?"REAL":t==="SQLiteBlob"?"BLOB":"TEXT"}function Im(t){return t instanceof Date?t.valueOf():typeof t=="boolean"?t?1:0:t&&typeof t=="object"?JSON.stringify(t):t}function ct(t){return String(t??"").trim()}function Qe(t){return t.replaceAll('"','""')}async function Sm(t,e,r){let n=Em(e,r,"sqlite");return n.length?(await t.execute({type:"transactionBatch",statements:n.map(s=>({...s,method:"all"}))})).results.reduce((s,a)=>s+(Array.isArray(a.rows)?a.rows.length:0),0):0}function Em(t,e,r){let n=su(e.value,{extensionId:e.extensionId,metadata:t}),o=lu(t),i=s=>`"${Qe(s)}"`;return n.entries.flatMap(s=>{let a=o.get(s.tableName),c=a.columns,l=a.primaryKey?.length?a.primaryKey:Object.values(c).filter(u=>u.primary||u.primaryKey).map(u=>u.name);return s.rows.map(u=>{let d=Object.keys(u);return{sql:`INSERT INTO ${i(s.tableName)} (${d.map(p=>i(c[p].name)).join(", ")}) VALUES (${d.map((p,h)=>r==="sqlite"?"?":`$${h+1}`).join(", ")}) ON CONFLICT (${l.map(i).join(", ")}) DO NOTHING RETURNING 1;`,params:d.map(p=>{let h=u[p];return h===null?null:c[p].dataType==="json"?JSON.stringify(h):r==="sqlite"&&typeof h=="boolean"?Number(h):h})}})})}var Br="SQL_EXECUTOR";function jm(t){return{async execute(e){return pu(t,e)}}}function Mn(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 Yo=class{state;constructor(e){this.state=e}async fetch(e){let r=e.clone();try{let n=await Am(e),o=await pu(this.state,n);return Response.json(o)}catch(n){return console.error("Durable Object SQL executor request failed.",{requestType:await Tm(r),error:n instanceof Error?n.message:String(n)}),Response.json({error:n instanceof Error?n.message:String(n)},{status:500})}}};async function Tm(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 pu(t,e){return e.type==="query"?ca(t.storage.sql,e.statement):e.type==="batch"?{results:e.statements.map(r=>ca(t.storage.sql,r))}:e.type==="transactionBatch"?fu(t,()=>({results:e.statements.map(r=>ca(t.storage.sql,r))})):e.type==="applyMigration"?fu(t,()=>{if(Om(t.storage.sql),Nm(t.storage.sql,e.migrationId))return{rowsAffected:0};for(let r of e.statements)t.storage.sql.exec(r);return Pm(t.storage.sql,e.migrationId),{rowsAffected:0}}):e.type==="applyMetadata"?await cu(jm(t),e.metadata,{dataset:e.dataset}):{statements:[]}}async function Am(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 fu(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 ca(t,e){let r=t.exec(e.sql,...e.params??[]),n=e.method??"run";return n==="values"?{rows:Cm(r.raw?.())}:n==="get"?{rows:mu(r)}:n==="all"?{rows:r.toArray?.()??[]}:{rows:[]}}function mu(t){try{return t.one?.()}catch(e){if(Rm(e))return;throw e}}function Rm(t){return t instanceof Error&&t.message.toLowerCase().includes("no results")}function Om(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 Nm(t,e){return!!mu(t.exec('SELECT id FROM "__kuafu_sql_migrations" WHERE id = ? LIMIT 1',e))}function Pm(t,e){t.exec('INSERT OR IGNORE INTO "__kuafu_sql_migrations" (id, applied_at) VALUES (?, ?)',e,Date.now())}function Cm(t){return t?Array.isArray(t)?t:"toArray"in t?t.toArray():Array.from(t):[]}var Fr=class extends he{static[m]="PgViewBase"};var zt=class{static[m]="PgDialect";casing;constructor(e){this.casing=new Cr(e?.casing)}async migrate(e,r,n){let o=typeof n=="string"?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",i=typeof n=="string"?"drizzle":n.migrationsSchema??"drizzle",s=f`
26
+ CREATE TABLE IF NOT EXISTS ${f.identifier(i)}.${f.identifier(o)} (
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(i)}`),await r.execute(s);let c=(await r.all(f`select id, hash, created_at from ${f.identifier(i)}.${f.identifier(o)} 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(i)}.${f.identifier(o)} ("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,o]of e.entries())r.push(f`${f.identifier(o._.alias)} as (${o._.sql})`),n<e.length-1&&r.push(f`, `);return r.push(f` `),f.join(r)}buildDeleteQuery({table:e,where:r,returning:n,withList:o}){let i=this.buildWithCTE(o),s=n?f` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,a=r?f` where ${r}`:void 0;return f`${i}delete from ${e}${a}${s}`}buildUpdateSet(e,r){let n=e[v.Symbol.Columns],o=Object.keys(n).filter(s=>r[s]!==void 0||n[s]?.onUpdateFn!==void 0),i=o.length;return f.join(o.flatMap((s,a)=>{let c=n[s],l=c.onUpdateFn?.(),u=r[s]??(y(l,I)?l:f.param(l,c)),d=f`${f.identifier(this.casing.getColumnCasing(c))} = ${u}`;return a<i-1?[d,f.raw(", ")]:[d]}))}buildUpdateQuery({table:e,set:r,where:n,returning:o,withList:i,from:s,joins:a}){let c=this.buildWithCTE(i),l=e[_e.Symbol.Name],u=e[_e.Symbol.Schema],d=e[_e.Symbol.OriginalName],p=l===d?void 0:l,h=f`${u?f`${f.identifier(u)}.`:void 0}${f.identifier(d)}${p&&f` ${f.identifier(p)}`}`,w=this.buildUpdateSet(e,r),b=s&&f.join([f.raw(" from "),this.buildFromTable(s)]),_=this.buildJoins(a),k=o?f` returning ${this.buildSelection(o,{isSingleTable:!s})}`:void 0,C=n?f` where ${n}`:void 0;return f`${c}update ${h} set ${w}${b}${_}${C}${k}`}buildSelection(e,{isSingleTable:r=!1}={}){let n=e.length,o=e.flatMap(({field:i},s)=>{let a=[];if(y(i,I.Aliased)&&i.isSelectionField)a.push(f.identifier(i.fieldAlias));else if(y(i,I.Aliased)||y(i,I)){let c=y(i,I.Aliased)?i.sql:i;r?a.push(new I(c.queryChunks.map(l=>y(l,Z)?f.identifier(this.casing.getColumnCasing(l)):l))):a.push(c),y(i,I.Aliased)&&a.push(f` as ${f.identifier(i.fieldAlias)}`)}else if(y(i,M))r?a.push(f.identifier(this.casing.getColumnCasing(i))):a.push(i);else if(y(i,V)){let c=Object.entries(i._.selectedFields);if(c.length===1){let l=c[0][1],u=y(l,I)?l.decoder:y(l,M)?{mapFromDriverValue:d=>l.mapFromDriverValue(d)}:l.sql.decoder;u&&(i._.sql.decoder=u)}a.push(i)}return s<n-1&&a.push(f`, `),a});return f.join(o)}buildJoins(e){if(!e||e.length===0)return;let r=[];for(let[n,o]of e.entries()){n===0&&r.push(f` `);let i=o.table,s=o.lateral?f` lateral`:void 0,a=o.on?f` on ${o.on}`:void 0;if(y(i,_e)){let c=i[_e.Symbol.Name],l=i[_e.Symbol.Schema],u=i[_e.Symbol.OriginalName],d=c===u?void 0:o.alias;r.push(f`${f.raw(o.joinType)} join${s} ${l?f`${f.identifier(l)}.`:void 0}${f.identifier(u)}${d&&f` ${f.identifier(d)}`}${a}`)}else if(y(i,he)){let c=i[H].name,l=i[H].schema,u=i[H].originalName,d=c===u?void 0:o.alias;r.push(f`${f.raw(o.joinType)} join${s} ${l?f`${f.identifier(l)}.`:void 0}${f.identifier(u)}${d&&f` ${f.identifier(d)}`}${a}`)}else r.push(f`${f.raw(o.joinType)} join${s} ${i}${a}`);n<e.length-1&&r.push(f` `)}return f.join(r)}buildFromTable(e){if(y(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:o,having:i,table:s,joins:a,orderBy:c,groupBy:l,limit:u,offset:d,lockingClause:p,distinct:h,setOperators:w}){let b=n??ae(r);for(let J of b)if(y(J.field,M)&&me(J.field.table)!==(y(s,V)?s._.alias:y(s,Fr)?s[H].name:y(s,I)?void 0:me(s))&&!(Pe=>a?.some(({alias:mn})=>mn===(Pe[v.Symbol.IsAlias]?me(Pe):Pe[v.Symbol.BaseName])))(J.field.table)){let Pe=me(J.field.table);throw new Error(`Your "${J.path.join("->")}" field references a column "${Pe}"."${J.field.name}", but the table "${Pe}" is not part of the query! Did you forget to join it?`)}let _=!a||a.length===0,k=this.buildWithCTE(e),C;h&&(C=h===!0?f` distinct`:f` distinct on (${f.join(h.on,f`, `)})`);let q=this.buildSelection(b,{isSingleTable:_}),O=this.buildFromTable(s),X=this.buildJoins(a),L=o?f` where ${o}`:void 0,S=i?f` having ${i}`:void 0,A;c&&c.length>0&&(A=f` order by ${f.join(c,f`, `)}`);let Q;l&&l.length>0&&(Q=f` group by ${f.join(l,f`, `)}`);let ie=typeof u=="object"||typeof u=="number"&&u>=0?f` limit ${u}`:void 0,we=d?f` offset ${d}`:void 0,le=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`),le.append(J)}let re=f`${k}select${C} ${q} from ${O}${X}${L}${Q}${S}${A}${ie}${we}${le}`;return w.length>0?this.buildSetOperations(re,w):re}buildSetOperations(e,r){let[n,...o]=r;if(!n)throw new Error("Cannot pass undefined values to any set operator");return o.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:n}),o)}buildSetOperationQuery({leftSelect:e,setOperator:{type:r,isAll:n,rightSelect:o,limit:i,orderBy:s,offset:a}}){let c=f`(${e.getSQL()}) `,l=f`(${o.getSQL()})`,u;if(s&&s.length>0){let w=[];for(let b of s)if(y(b,Z))w.push(f.identifier(b.name));else if(y(b,I)){for(let _=0;_<b.queryChunks.length;_++){let k=b.queryChunks[_];y(k,Z)&&(b.queryChunks[_]=f.identifier(k.name))}w.push(f`${b}`)}else w.push(f`${b}`);u=f` order by ${f.join(w,f`, `)} `}let d=typeof i=="object"||typeof i=="number"&&i>=0?f` limit ${i}`:void 0,p=f.raw(`${r} ${n?"all ":""}`),h=a?f` offset ${a}`:void 0;return f`${c}${p}${l}${u}${d}${h}`}buildInsertQuery({table:e,values:r,onConflict:n,returning:o,withList:i,select:s,overridingSystemValue_:a}){let c=[],l=e[v.Symbol.Columns],u=Object.entries(l).filter(([k,C])=>!C.shouldDisableInsert()),d=u.map(([,k])=>f.identifier(this.casing.getColumnCasing(k)));if(s){let k=r;y(k,I)?c.push(k):c.push(k.getSQL())}else{let k=r;c.push(f.raw("values "));for(let[C,q]of k.entries()){let O=[];for(let[X,L]of u){let S=q[X];if(S===void 0||y(S,xe)&&S.value===void 0)if(L.defaultFn!==void 0){let A=L.defaultFn(),Q=y(A,I)?A:f.param(A,L);O.push(Q)}else if(!L.default&&L.onUpdateFn!==void 0){let A=L.onUpdateFn(),Q=y(A,I)?A:f.param(A,L);O.push(Q)}else O.push(f`default`);else O.push(S)}c.push(O),C<k.length-1&&c.push(f`, `)}}let p=this.buildWithCTE(i),h=f.join(c),w=o?f` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,b=n?f` on conflict ${n}`:void 0,_=a===!0?f`overriding system value `:void 0;return f`${p}insert into ${e} ${d} ${_}${h}${b}${w}`}buildRefreshMaterializedViewQuery({view:e,concurrently:r,withNoData:n}){let o=r?f` concurrently`:void 0,i=n?f` with no data`:void 0;return f`refresh materialized view${o} ${e}${i}`}prepareTyping(e){return y(e,Rn)||y(e,An)?"json":y(e,On)?"decimal":y(e,Nn)?"time":y(e,Pn)||y(e,Cn)?"timestamp":y(e,jn)||y(e,Tn)?"date":y(e,$n)?"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:o,tableConfig:i,queryConfig:s,tableAlias:a,nestedQueryRelation:c,joinOn:l}){let u=[],d,p,h=[],w,b=[];if(s===!0)u=Object.entries(i.columns).map(([C,q])=>({dbKey:q.name,tsKey:C,field:ge(q,a),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let k=Object.fromEntries(Object.entries(i.columns).map(([S,A])=>[S,ge(A,a)]));if(s.where){let S=typeof s.where=="function"?s.where(k,Co()):s.where;w=S&&Pt(S,a)}let C=[],q=[];if(s.columns){let S=!1;for(let[A,Q]of Object.entries(s.columns))Q!==void 0&&A in i.columns&&(!S&&Q===!0&&(S=!0),q.push(A));q.length>0&&(q=S?q.filter(A=>s.columns?.[A]===!0):Object.keys(i.columns).filter(A=>!q.includes(A)))}else q=Object.keys(i.columns);for(let S of q){let A=i.columns[S];C.push({tsKey:S,value:A})}let O=[];s.with&&(O=Object.entries(s.with).filter(S=>!!S[1]).map(([S,A])=>({tsKey:S,queryConfig:A,relation:i.relations[S]})));let X;if(s.extras){X=typeof s.extras=="function"?s.extras(k,{sql:f}):s.extras;for(let[S,A]of Object.entries(X))C.push({tsKey:S,value:vn(A,a)})}for(let{tsKey:S,value:A}of C)u.push({dbKey:y(A,I.Aliased)?A.fieldAlias:i.columns[S].name,tsKey:S,field:y(A,M)?ge(A,a):A,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof s.orderBy=="function"?s.orderBy(k,$o()):s.orderBy??[];Array.isArray(L)||(L=[L]),h=L.map(S=>y(S,M)?ge(S,a):Pt(S,a)),d=s.limit,p=s.offset;for(let{tsKey:S,queryConfig:A,relation:Q}of O){let ie=qo(r,n,Q),we=yt(Q.referencedTable),le=n[we],re=`${a}_${S}`,J=xt(...ie.fields.map(($i,zi)=>it(ge(ie.references[zi],re),ge($i,a)))),Pe=this.buildRelationalQueryWithoutPK({fullSchema:e,schema:r,tableNamesMap:n,table:e[le],tableConfig:r[le],queryConfig:y(Q,st)?A===!0?{limit:1}:{...A,limit:1}:A,tableAlias:re,joinOn:J,nestedQueryRelation:Q}),mn=f`${f.identifier(re)}.${f.identifier("data")}`.as(S);b.push({on:f`true`,table:new V(Pe.sql,{},re),alias:re,joinType:"left",lateral:!0}),u.push({dbKey:S,tsKey:S,field:mn,relationTableTsKey:le,isJson:!0,selection:Pe.selection})}}if(u.length===0)throw new vt({message:`No fields selected for table "${i.tsName}" ("${a}")`});let _;if(w=xt(l,w),c){let k=f`json_build_array(${f.join(u.map(({field:O,tsKey:X,isJson:L})=>L?f`${f.identifier(`${a}_${X}`)}.${f.identifier("data")}`:y(O,I.Aliased)?O.sql:O),f`, `)})`;y(c,ir)&&(k=f`coalesce(json_agg(${k}${h.length>0?f` order by ${f.join(h,f`, `)}`:void 0}), '[]'::json)`);let C=[{dbKey:"data",tsKey:"data",field:k.as("data"),isJson:!0,relationTableTsKey:i.tsName,selection:u}];d!==void 0||p!==void 0||h.length>0?(_=this.buildSelectQuery({table:wt(o,a),fields:{},fieldsFlat:[{path:[],field:f.raw("*")}],where:w,limit:d,offset:p,orderBy:h,setOperators:[]}),w=void 0,d=void 0,p=void 0,h=[]):_=wt(o,a),_=this.buildSelectQuery({table:y(_,_e)?_:new V(_,{},a),fields:{},fieldsFlat:C.map(({field:O})=>({path:[],field:y(O,M)?ge(O,a):O})),joins:b,where:w,limit:d,offset:p,orderBy:h,setOperators:[]})}else _=this.buildSelectQuery({table:wt(o,a),fields:{},fieldsFlat:u.map(({field:k})=>({path:[],field:y(k,M)?ge(k,a):k})),joins:b,where:w,limit:d,offset:p,orderBy:h,setOperators:[]});return{tableTsKey:i.tsName,sql:_,selection:u}}};var Ae=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,o;return this.fields?o=this.fields:y(n,V)?o=Object.fromEntries(Object.keys(n._.selectedFields).map(i=>[i,n[i]])):y(n,Fr)?o=n[H].selectedFields:y(n,I)?o={}:o=Eo(n),new Xo({table:n,fields:o,isPartialSelect:r,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}},la=class extends qr{static[m]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:r,isPartialSelect:n,session:o,dialect:i,withList:s,distinct:a}){super(),this.config={withList:s,table:e,fields:{...r},distinct:a,setOperators:[]},this.isPartialSelect=n,this.session=o,this.dialect=i,this._={selectedFields:r,config:this.config},this.tableName=Ce(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,r){return(n,o)=>{let i=this.tableName,s=Ce(n);for(let a of He(n))this.usedTables.add(a);if(typeof s=="string"&&this.config.joins?.some(a=>a.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof i=="string"&&(this.config.fields={[i]:this.config.fields}),typeof s=="string"&&!y(n,I))){let a=y(n,V)?n._.selectedFields:y(n,he)?n[H].selectedFields:n[v.Symbol.Columns];this.config.fields[s]=a}if(typeof o=="function"&&(o=o(new Proxy(this.config.fields,new K({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:o,table:n,joinType:e,alias:s,lateral:r}),typeof s=="string")switch(e){case"left":{this.joinsNotNullableMap[s]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[s]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[s]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[s]=!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 o=typeof n=="function"?n($m()):n;if(!rt(this.getSelectedFields(),o.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:o}),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 K({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new K({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 K({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 K({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(...He(this.config.table)),this.config.joins)for(let n of this.config.joins)r.push(...He(n.table));return new Proxy(new V(this.getSQL(),this.config.fields,e,!1,[...new Set(r)]),new K({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new K({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}},Xo=class extends la{static[m]="PgSelect";_prepare(e){let{session:r,config:n,dialect:o,joinsNotNullableMap:i,authToken:s,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=ae(l),d=r.prepareQuery(o.sqlToQuery(this.getSQL()),u,e,!0,void 0,{type:"select",tables:[...c]},a);return d.joinsNotNullableMap=i,d.setToken(s)})}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))};So(Xo,[G]);function Vr(t,e){return(r,n,...o)=>{let i=[n,...o].map(s=>({type:t,isAll:e,rightSelect:s}));for(let s of i)if(!rt(r.getSelectedFields(),s.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(i)}}var $m=()=>({union:zm,unionAll:qm,intersect:Lm,intersectAll:Dm,except:Mm,exceptAll:Km}),zm=Vr("union",!1),qm=Vr("union",!0),Lm=Vr("intersect",!1),Dm=Vr("intersect",!0),Mm=Vr("except",!1),Km=Vr("except",!0);var Wr=class{static[m]="PgQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=y(e,zt)?e:void 0,this.dialectConfig=y(e,zt)?void 0:e}$with=(e,r)=>{let n=this;return{as:i=>(typeof i=="function"&&(i=i(n)),new Proxy(new tt(i.getSQL(),r??("getSelectedFields"in i?i.getSelectedFields()??{}:{}),e,!0),new K({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...e){let r=this;function n(s){return new Ae({fields:s??void 0,session:void 0,dialect:r.getDialect(),withList:e})}function o(s){return new Ae({fields:s??void 0,session:void 0,dialect:r.getDialect(),distinct:!0})}function i(s,a){return new Ae({fields:a??void 0,session:void 0,dialect:r.getDialect(),distinct:{on:s}})}return{select:n,selectDistinct:o,selectDistinctOn:i}}select(e){return new Ae({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Ae({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(e,r){return new Ae({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 He(t){return y(t,_e)?[t[rr]?`${t[rr]}.${t[v.Symbol.BaseName]}`:t[v.Symbol.BaseName]]:y(t,V)?t._.usedTables??[]:y(t,I)?t.usedTables??[]:[]}var Kn=class extends G{constructor(e,r,n,o){super(),this.session=r,this.dialect=n,this.config={table:e,withList:o}}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=ae(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:He(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 K({alias:me(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var Un=class{constructor(e,r,n,o,i){this.table=e,this.session=r,this.dialect=n,this.withList=o,this.overridingSystemValue_=i}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 o={},i=this.table[v.Symbol.Columns];for(let s of Object.keys(n)){let a=n[s];o[s]=y(a,I)?a:new xe(a,i[s])}return o});return new ei(this.table,r,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(e){let r=typeof e=="function"?e(new Wr):e;if(!y(r,I)&&!rt(this.table[Nr],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 ei(this.table,r,this.session,this.dialect,this.withList,!0)}},ei=class extends G{constructor(e,r,n,o,i,s,a){super(),this.session=n,this.dialect=o,this.config={table:e,values:r,withList:i,select:s,overridingSystemValue_:a}}static[m]="PgInsert";config;cacheConfig;returning(e=this.config.table[v.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=ae(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(o=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(o))).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,o=e.setWhere?f` where ${e.setWhere}`:void 0,i=this.dialect.buildUpdateSet(this.config.table,Ct(this.config.table,e.set)),s="";return s=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(s)})${n} do update set ${i}${r}${o}`,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:He(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 K({alias:me(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var ti=class extends G{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 Bn=class{constructor(e,r,n,o){this.table=e,this.session=r,this.dialect=n,this.withList=o}static[m]="PgUpdateBuilder";authToken;setToken(e){return this.authToken=e,this}set(e){return new ua(this.table,Ct(this.table,e),this.session,this.dialect,this.withList).setToken(this.authToken)}},ua=class extends G{constructor(e,r,n,o,i){super(),this.session=n,this.dialect=o,this.config={set:r,table:e,withList:i,joins:[]},this.tableName=Ce(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}static[m]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(e){let r=e,n=Ce(r);return typeof n=="string"&&(this.joinsNotNullableMap[n]=!0),this.config.from=r,this}getTableLikeFields(e){return y(e,_e)?e[v.Symbol.Columns]:y(e,V)?e._.selectedFields:e[H].selectedFields}createJoin(e){return(r,n)=>{let o=Ce(r);if(typeof o=="string"&&this.config.joins.some(i=>i.alias===o))throw new Error(`Alias "${o}" is already used in this query`);if(typeof n=="function"){let i=this.config.from&&!y(this.config.from,I)?this.getTableLikeFields(this.config.from):void 0;n=n(new Proxy(this.config.table[v.Symbol.Columns],new K({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),i&&new Proxy(i,new K({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(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"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");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=Ce(this.config.from);if(typeof r=="string"&&this.config.from&&!y(this.config.from,I)){let n=this.getTableLikeFields(this.config.from);e[r]=n}for(let n of this.config.joins){let o=Ce(n.table);if(typeof o=="string"&&!y(n.table,I)){let i=this.getTableLikeFields(n.table);e[o]=i}}}return this.config.returningFields=e,this.config.returning=ae(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:He(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 K({alias:me(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var ri=class t extends I{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 ni=class{constructor(e,r,n,o,i,s,a){this.fullSchema=e,this.schema=r,this.tableNamesMap=n,this.table=o,this.tableConfig=i,this.dialect=s,this.session=a}static[m]="PgRelationalQueryBuilder";findMany(e){return new oi(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many")}findFirst(e){return new oi(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}},oi=class extends G{constructor(e,r,n,o,i,s,a,c,l){super(),this.fullSchema=e,this.schema=r,this.tableNamesMap=n,this.table=o,this.tableConfig=i,this.dialect=s,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,(o,i)=>{let s=o.map(a=>zr(this.schema,this.tableConfig,a,r.selection,i));return this.mode==="first"?s[0]:s})})}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 ii=class extends G{constructor(e,r,n,o){super(),this.execute=e,this.sql=r,this.query=n,this.mapBatchResult=o}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 Qr=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[o,i]of Object.entries(this._.schema))this.query[o]=new ni(n.fullSchema,this._.schema,this._.tableNamesMap,n.fullSchema[o],i,e,r);this.$cache={invalidate:async o=>{}}}static[m]="PgDatabase";query;$with=(e,r)=>{let n=this;return{as:i=>(typeof i=="function"&&(i=i(new Wr(n.dialect))),new Proxy(new tt(i.getSQL(),r??("getSelectedFields"in i?i.getSelectedFields()??{}:{}),e,!0),new K({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(e,r){return new ri({source:e,filters:r,session:this.session})}$cache;with(...e){let r=this;function n(l){return new Ae({fields:l??void 0,session:r.session,dialect:r.dialect,withList:e})}function o(l){return new Ae({fields:l??void 0,session:r.session,dialect:r.dialect,withList:e,distinct:!0})}function i(l,u){return new Ae({fields:u??void 0,session:r.session,dialect:r.dialect,withList:e,distinct:{on:l}})}function s(l){return new Bn(l,r.session,r.dialect,e)}function a(l){return new Un(l,r.session,r.dialect,e)}function c(l){return new Kn(l,r.session,r.dialect,e)}return{select:n,selectDistinct:o,selectDistinctOn:i,update:s,insert:a,delete:c}}select(e){return new Ae({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Ae({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(e,r){return new Ae({fields:r??void 0,session:this.session,dialect:this.dialect,distinct:{on:e}})}update(e){return new Bn(e,this.session,this.dialect)}insert(e){return new Un(e,this.session,this.dialect)}delete(e){return new Kn(e,this.session,this.dialect)}refreshMaterializedView(e){return new ti(e,this.session,this.dialect)}authToken;execute(e){let r=typeof e=="string"?f.raw(e):e.getSQL(),n=this.dialect.sqlToQuery(r),o=this.session.prepareQuery(n,void 0,void 0,!1);return new ii(()=>o.execute(void 0,this.authToken),r,n,i=>o.mapResult(i,!0))}transaction(e,r){return this.session.transaction(e,r)}};var si=class{constructor(e,r,n,o){this.query=e,this.cache=r,this.queryMetadata=n,this.cacheConfig=o,r&&r.strategy()==="all"&&o===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||y(this.cache,at)||this.queryMetadata===void 0)try{return await n()}catch(o){throw new Te(e,r,o)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await n()}catch(o){throw new Te(e,r,o)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[o]=await Promise.all([n(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return o}catch(o){throw new Te(e,r,o)}if(!this.cacheConfig)try{return await n()}catch(o){throw new Te(e,r,o)}if(this.queryMetadata.type==="select"){let o=await this.cache.get(this.cacheConfig.tag??await Mr(e,r),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(o===void 0){let i;try{i=await n()}catch(s){throw new Te(e,r,s)}return await this.cache.put(this.cacheConfig.tag??await Mr(e,r),i,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),i}return o}try{return await n()}catch(o){throw new Te(e,r,o)}}},ai=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)}},ci=class extends Qr{constructor(e,r,n,o=0){super(e,r,n),this.schema=n,this.nestedIndex=o}static[m]="PgTransaction";rollback(){throw new $r}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 li=class extends ai{constructor(e,r,n,o={}){super(r),this.client=e,this.schema=n,this.logger=o.logger??new Ur,this.cache=o.cache??new at}static[m]="PgRemoteSession";logger;cache;prepareQuery(e,r,n,o,i,s,a){return new da(this.client,e.sql,e.params,e.typings,this.logger,this.cache,s,a,r,o,i)}async transaction(e,r){throw new Error("Transactions are not supported by the Postgres Proxy driver")}},hu=class extends ci{static[m]="PgProxyTransaction";async transaction(e){throw new Error("Transactions are not supported by the Postgres Proxy driver")}},da=class extends si{constructor(e,r,n,o,i,s,a,c,l,u,d){super({sql:r,params:n},s,a,c),this.client=e,this.queryString=r,this.params=n,this.typings=o,this.logger=i,this.fields=l,this._isResponseInArrayMode=u,this.customResultMapper=d}static[m]="PgProxyPreparedQuery";async execute(e={}){return ne.startActiveSpan("drizzle.execute",async r=>{let n=nr(this.params,e),{fields:o,client:i,queryString:s,joinsNotNullableMap:a,customResultMapper:c,logger:l,typings:u}=this;if(r?.setAttributes({"drizzle.query.text":s,"drizzle.query.params":JSON.stringify(n)}),l.logQuery(s,n),!o&&!c)return ne.startActiveSpan("drizzle.driver.execute",async()=>{let{rows:p}=await this.queryWithCache(s,n,async()=>await i(s,n,"execute",u));return p});let d=await ne.startActiveSpan("drizzle.driver.execute",async()=>{r?.setAttributes({"drizzle.query.text":s,"drizzle.query.params":JSON.stringify(n)});let{rows:p}=await this.queryWithCache(s,n,async()=>await i(s,n,"all",u));return p});return ne.startActiveSpan("drizzle.mapResponse",()=>c?c(d):d.map(p=>xn(o,p,a)))})}async all(){}isResponseInArrayMode(){return this._isResponseInArrayMode}};var fa=class extends Qr{static[m]="PgRemoteDatabase"};function gu(t,e={},r=()=>new zt({casing:e.casing})){let n=r(),o;e.logger===!0?o=new Kr:e.logger!==!1&&(o=e.logger);let i;if(e.schema){let c=zo(e.schema,Lo);i={fullSchema:e.schema,schema:c.tables,tableNamesMap:c.tableNamesMap}}let s=new li(t,n,i,{logger:o,cache:e.cache}),a=new fa(n,s,i);return a.$cache=e.cache,a.$cache&&(a.$cache.invalidate=e.cache?.onMutate),a}var pa="POSTGRES_EXECUTOR";function yu(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 o=await n.json();if(!Array.isArray(o.results)||o.results.length!==r.length)throw new Error("PostgreSQL transaction batch returned invalid results.");return o.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 o=await n.text();throw new Error(`PostgreSQL executor request failed: status=${n.status} body=${o}`)}return await n.json()}}}function bu(t,e){let r=gu(async(o,i,s,a)=>({rows:(await t.execute({sql:o,params:i,method:s,typings:a})).rows}),e);return Object.assign(r,{async executeAtomicWrites(o){if(!t.transactionBatch)throw new Error("PostgreSQL executor requires transactionBatch for atomic writes.");let i=o.map(s=>({...s.toSQL(),method:"execute"}));await t.transactionBatch(i)}})}var Um=0xffffffffffffn,Bm=0x0fffn,Fm=0x3fffffffffffffffn;function wu(t){let e=t instanceof Date?t.getTime():t??Date.now(),r=BigInt(e);if(r<0n||r>Um)throw new RangeError(`Unsupported UUIDv7 timestamp: ${e}`);let n=Vm(),o=new Uint8Array(10);n.getRandomValues(o);let i=(BigInt(o[0])<<8n|BigInt(o[1]))&Bm,s=Wm(o.slice(2))&Fm,a=r<<80n|0x7n<<76n|i<<64n|0x2n<<62n|s;return Qm(a.toString(16).padStart(32,"0"))}function Vm(){let t=globalThis.crypto;if(!t?.getRandomValues)throw new Error("crypto.getRandomValues is required to create IDs.");return t}function Wm(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 Je=1e4,Zm=1,ui="prod";var Ym=/^\/local\/project\/[^/]+\/env\/[^/]+\/repo\/[^/]+\/(?:main|DEV\d{6,})(?=\/|$)/u;function Xm(t){let e=Di({pathname:t,search:""});if(e){let r=e.remotePreview||e.remoteProduct?t.slice(0,t.indexOf("/local/project/")):"",n=t.slice(r.length),o=n.match(/^\/local\/project\/[^/]+\/env\/[^/]+\/workspace\/[^/]+/u)[0],i=e.codebaseRuntime?n.slice(o.length).match(/^\/repo\/[^/]+\/codebases\/~[^/]+(?=\/|$)/u)[0]:"";return`${r}${o}${i}`}return t.match(Ym)?.[0]}function xu(t){let e=Xm(t),r=e?t.slice(e.length)||"/":t,n=r.match(/^\/api\/project\/([^/]+)\/env\/([^/]+)\/ext\/([^/]+)(?:\/(.*))?$/u);if(n){let s=ce(decodeURIComponent(n[1])),a=Y(decodeURIComponent(n[2]??""));return s===null?void 0:{kind:"api",projectId:s,projectEnvKey:a,extensionId:decodeURIComponent(n[3]),remainder:n[4]?`/${n[4]}`:"/"}}let o=r.match(/^\/project\/([^/]+)\/env\/([^/]+)\/ext\/([^/]+)(?:\/(.*))?$/u);if(o){let s=ce(decodeURIComponent(o[1])),a=Y(decodeURIComponent(o[2]??""));return s===null?void 0:{kind:"page",projectId:s,projectEnvKey:a,extensionId:decodeURIComponent(o[3]),remainder:o[4]?`/${o[4]}`:"/"}}let i=r.match(/^\/assets\/project\/([^/]+)\/env\/([^/]+)\/ext\/([^/]+)(?:\/(.*))?$/u);if(i){let s=ce(decodeURIComponent(i[1])),a=Y(decodeURIComponent(i[2]??""));return s===null?void 0:{kind:"asset",projectId:s,projectEnvKey:a,extensionId:decodeURIComponent(i[3]),remainder:i[4]?`/${i[4]}`:"/"}}return eh(r)}function ce(t){if(typeof t=="number")return vu(t)?t:null;if(typeof t!="string"||!t.trim())return null;let e=Number(t);return vu(e)?e:null}function vu(t){return typeof t=="number"&&Number.isInteger(t)&&t>=Zm}function Hr(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:ui}function qt(t){return encodeURIComponent(Y(t))}function eh(t){let e=t.match(/^\/api\/project\/([^/]+)\/ext\/([^/]+)(?:\/(.*))?$/u);if(e)return ma({kind:"api",encodedProjectId:e[1],encodedExtensionId:e[2],rawRemainder:e[3]});let r=t.match(/^\/project\/([^/]+)\/ext\/([^/]+)(?:\/(.*))?$/u);if(r)return ma({kind:"page",encodedProjectId:r[1],encodedExtensionId:r[2],rawRemainder:r[3]});let n=t.match(/^\/assets\/project\/([^/]+)\/ext\/([^/]+)(?:\/(.*))?$/u);if(n)return ma({kind:"asset",encodedProjectId:n[1],encodedExtensionId:n[2],rawRemainder:n[3]})}function ma(t){let e=ce(decodeURIComponent(t.encodedProjectId??""));if(!(e===null||!t.encodedExtensionId))return{kind:t.kind,projectId:e,projectEnvKey:ui,extensionId:decodeURIComponent(t.encodedExtensionId),remainder:t.rawRemainder?`/${t.rawRemainder}`:"/"}}var ku=Symbol.for("@kuafucloud/extension-kit:internal-bindings"),_u=Symbol.for("@kuafucloud/extension-kit:internal-extension-invoker"),Fn=globalThis[ku]??(globalThis[ku]=new WeakMap),di=globalThis[_u]??(globalThis[_u]=new WeakMap);function Iu(t,e,r){let n=Object.freeze({...e});di.set(t,o=>{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,o)})}function _t(t){return[t.projectId,Y(t.projectEnvKey),t.extensionId.trim(),t.databaseName.trim()].join("__")}function Jr(t){let e=t?.[Br];return!e||typeof e!="object"||typeof e.idFromName!="function"||typeof e.get!="function"?null:e}function ha(t){return Y(t.projectEnvKey)!==ui?"do":(typeof t.env?.KUAFUCLOUD_DATABASE_BACKEND=="string"?t.env.KUAFUCLOUD_DATABASE_BACKEND.trim().toLowerCase():"")==="postgres"?"postgres":"do"}var th="kuafu-sql-executor-v1";async function Su(t){let e=t.env,r=Jr(e);if(!r)return{body:{code:"runtime.sql_executor_not_configured",message:`Durable Object binding ${Br} is missing.`},status:503};try{let n=_t({...t.resolveScope(),extensionId:t.extensionId,databaseName:"default"}),i=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"}})}),s=await i.json().catch(()=>null);if(!i.ok||!s||!("rows"in s))throw new Error(`SQL Executor returned ${i.status}.`);return{body:{data:{status:"healthy",extensionId:t.extensionId,executorContract:th}},status:200}}catch(n){return{body:{code:"runtime.sql_executor_unhealthy",message:n instanceof Error?n.message:String(n)},status:503}}}var Eu=new Set(["system","im","center","developer","data"]),rh=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 nh(t){return!t||typeof t!="object"?{}:Object.freeze(Object.fromEntries(Object.entries(t).filter(([e])=>!rh.has(e))))}function ga(t,e){return Eu.has(t)?e&&typeof e=="object"?e:{}:nh(e)}function ju(t){return Eu.has(t)}function Tu(t,e,r){let n=r.projectId,o=r.projectEnvKey;if(t.allowCrossEnvironment!==!0&&e.projectEnvKey!==o)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 s=e.extensionId,a=t.allowedCallerExtensions??[];if(a.length>0&&!a.includes(s))return{code:"runtime.internal_forbidden",message:`Internal caller extension "${s}" 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 de(t){return Object.freeze({...t})}function be(t,e){return{route:t,handler:e}}function Qn(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 o=0,n=Object.getOwnPropertySymbols(t);o<n.length;o++)e.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(t,n[o])&&(r[n[o]]=t[n[o]]);return r}function U(t,e){var r;return((r=t?._def)===null||r===void 0?void 0:r.typeName)===e}function ih(t){return"_def"in t}function Vn(t,e){let r=t.ZodType.prototype[e];t.ZodType.prototype[e]=function(...n){let o=r.apply(this,n);return o._def.openapi=this._def.openapi,o}}function yi(t){if(typeof t.ZodType.prototype.openapi<"u")return;t.ZodType.prototype.openapi=function(o,i){var s,a,c,l,u,d;let p=typeof o=="string"?i:o,h=p??{},{param:w}=h,b=Qn(h,["param"]),_=Object.assign(Object.assign({},(s=this._def.openapi)===null||s===void 0?void 0:s._internal),typeof o=="string"?{refId:o}:void 0),k=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),C=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(_).length>0?{_internal:_}:void 0),Object.keys(k).length>0?{metadata:k}:void 0)}));if(U(this,"ZodObject")){let q=this.extend;C.extend=function(...O){var X,L,S,A,Q,ie,we;let le=q.apply(this,O);return le._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=(S=this._def.openapi)===null||S===void 0?void 0:S._internal)===null||A===void 0?void 0:A.refId,schema:this}:(ie=(Q=this._def.openapi)===null||Q===void 0?void 0:Q._internal)===null||ie===void 0?void 0:ie.extendedFrom},metadata:(we=le._def.openapi)===null||we===void 0?void 0:we.metadata},le}}return C},Vn(t,"optional"),Vn(t,"nullable"),Vn(t,"default"),Vn(t,"transform"),Vn(t,"refine");let e=t.ZodObject.prototype.deepPartial;t.ZodObject.prototype.deepPartial=function(){let o=this._def.shape(),i=e.apply(this),s=i._def.shape();return Object.entries(s).forEach(([a,c])=>{var l,u;c._def.openapi=(u=(l=o[a])===null||l===void 0?void 0:l._def)===null||u===void 0?void 0:u.openapi}),i._def.openapi=void 0,i};let r=t.ZodObject.prototype.pick;t.ZodObject.prototype.pick=function(...o){let i=r.apply(this,o);return i._def.openapi=void 0,i};let n=t.ZodObject.prototype.omit;t.ZodObject.prototype.omit=function(...o){let i=n.apply(this,o);return i._def.openapi=void 0,i}}function fi(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=>fi(t[n],e[n]))}var ya=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(i=>fi(i,e))||n.push(e)}contains(e){let r=this.hashCodeOf(e),n=this.buckets.get(r);return n?n.some(o=>fi(o,e)):!1}values(){return[...this.buckets.values()].flat()}stats(){let e=0,r=0,n=0;for(let i of this.buckets.values())e+=1,r+=i.length,i.length>1&&(n+=1);let o=e/r;return{totalBuckets:e,collisions:n,totalValues:r,hashEffectiveness:o}}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,o]of Object.entries(e))r^=this.hashCodeOf(n)+this.hashCodeOf(o??"");return r}};function Hn(t){return t===void 0}function Jn(t,e){let r={};return Object.entries(t).forEach(([n,o])=>{r[n]=e(o)}),r}function sh(t,e){let r={};return Object.entries(t).forEach(([n,o])=>{e.some(i=>i===n)||(r[n]=o)}),r}function Gr(t,e){let r={};return Object.entries(t).forEach(([n,o])=>{e(o,n)||(r[n]=o)}),r}function Au(t){return t.filter(e=>!Hn(e))}var ba=fi;function ah(t){let e=new ya;return t.forEach(r=>e.put(r)),[...e.values()]}function Ru(t){return typeof t=="string"}var pi=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(o=>o.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,o,i;let s=this.schemaWithRefId(e,r),a=(n=s._def.openapi)===null||n===void 0?void 0:n.metadata,c=s.openapi(Object.assign(Object.assign({},a),{param:Object.assign(Object.assign({},a?.param),{name:(i=(o=a?.param)===null||o===void 0?void 0:o.name)!==null&&i!==void 0?i: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)}},Zr=class{constructor(e){this.message=e}},lr=class extends Zr{constructor(e,r){super(e),this.data=r}},Yr=class extends Zr{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 Wn(t,e){try{return t()}catch(r){throw r instanceof Yr?new Yr(Object.assign(Object.assign({},r.data),e)):r}}var wa=class extends Zr{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),o=e._def.openapi?e._def.openapi:n._def.openapi,i=(r=e.description)!==null&&r!==void 0?r:n.description;return{_internal:o?._internal,metadata:Object.assign({description:i},o?.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 o=this.unwrapChained(e),i=e._def.openapi?e._def.openapi:o._def.openapi,s=(r=e.description)!==null&&r!==void 0?r:o.description;return{_internal:i?._internal,metadata:Object.assign(Object.assign({},i?.metadata),{param:Object.assign({description:s},(n=i?.metadata)===null||n===void 0?void 0:n.param)})}}static buildSchemaMetadata(e){return Gr(sh(e,["param"]),Hn)}static buildParameterMetadata(e){return Gr(e,Hn)}static applySchemaMetadata(e,r){return Gr(Object.assign(Object.assign({},e),this.buildSchemaMetadata(r)),Hn)}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&&U(e,r)?e:U(e,"ZodOptional")||U(e,"ZodNullable")||U(e,"ZodBranded")?this.unwrapUntil(e.unwrap(),r):U(e,"ZodDefault")||U(e,"ZodReadonly")?this.unwrapUntil(e._def.innerType,r):U(e,"ZodEffects")?this.unwrapUntil(e._def.schema,r):U(e,"ZodPipeline")?this.unwrapUntil(e._def.in,r):r?void 0:e}static isOptionalSchema(e){return e.isOptional()}},va=class{transform(e,r,n){var o,i;let s=e._def.type;return Object.assign(Object.assign({},r("array")),{items:n(s),minItems:(o=e._def.minLength)===null||o===void 0?void 0:o.value,maxItems:(i=e._def.maxLength)===null||i===void 0?void 0:i.value})}},xa=class{transform(e){return Object.assign(Object.assign({},e("string")),{pattern:"^d+$"})}},ka=class{transform(e,r,n,o,i){let s=[...e.options.values()],a=s.map(o);return r?{oneOf:n(a,r)}:{oneOf:a,discriminator:this.mapDiscriminator(s,e.discriminator,i)}}mapDiscriminator(e,r,n){if(e.some(i=>ee.getRefId(i)===void 0))return;let o={};return e.forEach(i=>{var s;let a=ee.getRefId(i),c=(s=i.shape)===null||s===void 0?void 0:s[r];if(U(c,"ZodEnum")||U(c,"ZodNativeEnum")){Object.values(c.enum).filter(Ru).forEach(d=>{o[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`);o[l]=n(a)}),{propertyName:r,mapping:o}}},_a=class{transform(e,r){return Object.assign(Object.assign({},r("string")),{enum:e._def.values})}},Ia=class{transform(e,r,n,o){let s={allOf:this.flattenIntersectionTypes(e).map(o)};return r?{anyOf:n([s],r)}:s}flattenIntersectionTypes(e){if(!U(e,"ZodIntersection"))return[e];let r=this.flattenIntersectionTypes(e._def.left),n=this.flattenIntersectionTypes(e._def.right);return[...r,...n]}},Sa=class{transform(e,r){return Object.assign(Object.assign({},r(typeof e._def.value)),{enum:[e._def.value]})}};function ch(t){let r=Object.keys(t).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=r.filter(i=>typeof i=="number").length,o=n===0?"string":n===r.length?"numeric":"mixed";return{values:r,type:o}}var Ea=class{transform(e,r){let{type:n,values:o}=ch(e._def.values);if(n==="mixed")throw new Zr("Enum has mixed string and number values, please specify the OpenAPI type manually");return Object.assign(Object.assign({},r(n==="numeric"?"integer":"string")),{enum:o})}},ja=class{transform(e,r,n){return Object.assign(Object.assign({},r(e.isInt?"integer":"number")),n(e._def.checks))}},Ta=class{transform(e,r,n,o){var i;let s=(i=ee.getInternalMetadata(e))===null||i===void 0?void 0:i.extendedFrom,a=this.requiredKeysOf(e),c=Jn(e._def.shape(),o);if(!s)return Object.assign(Object.assign(Object.assign(Object.assign({},n("object")),{properties:c,default:r}),a.length>0?{required:a}:{}),this.generateAdditionalProperties(e,o));let l=s.schema;o(l);let u=this.requiredKeysOf(l),d=Jn(l?._def.shape(),o),p=Object.fromEntries(Object.entries(c).filter(([b,_])=>!ba(d[b],_))),h=a.filter(b=>!u.includes(b)),w=Object.assign(Object.assign(Object.assign(Object.assign({},n("object")),{default:r,properties:p}),h.length>0?{required:h}:{}),this.generateAdditionalProperties(e,o));return{allOf:[{$ref:`#/components/schemas/${s.refId}`},w]}}generateAdditionalProperties(e,r){let n=e._def.unknownKeys,o=e._def.catchall;return U(o,"ZodNever")?n==="strict"?{additionalProperties:!1}:{}:{additionalProperties:r(o)}}requiredKeysOf(e){return Object.entries(e._def.shape()).filter(([r,n])=>!ee.isOptionalSchema(n)).map(([r,n])=>r)}},Aa=class{transform(e,r,n){let o=e._def.valueType,i=e._def.keyType,s=n(o);if(U(i,"ZodEnum")||U(i,"ZodNativeEnum")){let c=Object.values(i.enum).filter(Ru).reduce((l,u)=>Object.assign(Object.assign({},l),{[u]:s}),{});return Object.assign(Object.assign({},r("object")),{properties:c})}return Object.assign(Object.assign({},r("object")),{additionalProperties:s})}},Ra=class{transform(e,r){var n,o,i;let s=this.getZodStringCheck(e,"regex"),a=(n=this.getZodStringCheck(e,"length"))===null||n===void 0?void 0:n.value,c=Number.isFinite(e.minLength)&&(o=e.minLength)!==null&&o!==void 0?o:void 0,l=Number.isFinite(e.maxLength)&&(i=e.maxLength)!==null&&i!==void 0?i:void 0;return Object.assign(Object.assign({},r("string")),{minLength:a??c,maxLength:a??l,format:this.mapStringFormat(e),pattern:s?.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)}},Oa=class{constructor(e){this.versionSpecifics=e}transform(e,r,n){let{items:o}=e._def,i=o.map(n);return Object.assign(Object.assign({},r("array")),this.versionSpecifics.mapTupleItems(i))}},Na=class{transform(e,r,n){let i=this.flattenUnionTypes(e).map(s=>{let a=this.unwrapNullable(s);return n(a)});return{anyOf:r(i)}}flattenUnionTypes(e){return U(e,"ZodUnion")?e._def.options.flatMap(n=>this.flattenUnionTypes(n)):[e]}unwrapNullable(e){return U(e,"ZodNullable")?this.unwrapNullable(e.unwrap()):e}},Pa=class{constructor(e){this.versionSpecifics=e,this.objectTransformer=new Ta,this.stringTransformer=new Ra,this.numberTransformer=new ja,this.bigIntTransformer=new xa,this.literalTransformer=new Sa,this.enumTransformer=new _a,this.nativeEnumTransformer=new Ea,this.arrayTransformer=new va,this.unionTransformer=new Na,this.discriminatedUnionTransformer=new ka,this.intersectionTransformer=new Ia,this.recordTransformer=new Aa,this.tupleTransformer=new Oa(e)}transform(e,r,n,o,i){if(U(e,"ZodNull"))return this.versionSpecifics.nullType;if(U(e,"ZodUnknown")||U(e,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,r);if(U(e,"ZodObject"))return this.objectTransformer.transform(e,i,a=>this.versionSpecifics.mapNullableType(a,r),n);let s=this.transformSchemaWithoutDefault(e,r,n,o);return Object.assign(Object.assign({},s),{default:i})}transformSchemaWithoutDefault(e,r,n,o){if(U(e,"ZodUnknown")||U(e,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,r);if(U(e,"ZodString"))return this.stringTransformer.transform(e,s=>this.versionSpecifics.mapNullableType(s,r));if(U(e,"ZodNumber"))return this.numberTransformer.transform(e,s=>this.versionSpecifics.mapNullableType(s,r),s=>this.versionSpecifics.getNumberChecks(s));if(U(e,"ZodBigInt"))return this.bigIntTransformer.transform(s=>this.versionSpecifics.mapNullableType(s,r));if(U(e,"ZodBoolean"))return this.versionSpecifics.mapNullableType("boolean",r);if(U(e,"ZodLiteral"))return this.literalTransformer.transform(e,s=>this.versionSpecifics.mapNullableType(s,r));if(U(e,"ZodEnum"))return this.enumTransformer.transform(e,s=>this.versionSpecifics.mapNullableType(s,r));if(U(e,"ZodNativeEnum"))return this.nativeEnumTransformer.transform(e,s=>this.versionSpecifics.mapNullableType(s,r));if(U(e,"ZodArray"))return this.arrayTransformer.transform(e,s=>this.versionSpecifics.mapNullableType(s,r),n);if(U(e,"ZodTuple"))return this.tupleTransformer.transform(e,s=>this.versionSpecifics.mapNullableType(s,r),n);if(U(e,"ZodUnion"))return this.unionTransformer.transform(e,s=>this.versionSpecifics.mapNullableOfArray(s,r),n);if(U(e,"ZodDiscriminatedUnion"))return this.discriminatedUnionTransformer.transform(e,r,s=>this.versionSpecifics.mapNullableOfArray(s,r),n,o);if(U(e,"ZodIntersection"))return this.intersectionTransformer.transform(e,r,s=>this.versionSpecifics.mapNullableOfArray(s,r),n);if(U(e,"ZodRecord"))return this.recordTransformer.transform(e,s=>this.versionSpecifics.mapNullableType(s,r),n);if(U(e,"ZodDate"))return this.versionSpecifics.mapNullableType("string",r);let i=ee.getRefId(e);throw new wa({currentSchema:e._def,schemaName:i})}},mi=class{constructor(e,r){this.definitions=e,this.versionSpecifics=r,this.schemaRefs={},this.paramRefs={},this.pathRefs={},this.rawComponents=[],this.openApiTransformer=new Pa(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:o,name:i,component:s})=>{var a;(a=n[o])!==null&&a!==void 0||(n[o]={}),n[o][i]=s}),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 o=e.findIndex(s=>s===r.type),i=e.findIndex(s=>s===n.type);return o-i})}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,o,i,s,a;let c=(n=e?.metadata)===null||n===void 0?void 0:n.param,l=!((o=e?._internal)===null||o===void 0)&&o.refId?this.paramRefs[(i=e._internal)===null||i===void 0?void 0:i.refId]:void 0;if(!(!(!((s=e?._internal)===null||s===void 0)&&s.refId)||!l)){if(c&&l.in!==c.in||r?.in&&l.in!==r.in)throw new lr(`Conflicting location for parameter ${l.name}`,{key:"in",values:Au([l.in,r?.in,c?.in])});if(c&&l.name!==c.name||r?.name&&l.name!==r?.name)throw new lr("Conflicting names for parameter",{key:"name",values:Au([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 o=ee.getMetadata(e),i=(n=o?.metadata)===null||n===void 0?void 0:n.param,s=this.getParameterRef(o,{in:r});if(s)return[s];if(U(e,"ZodObject")){let a=e._def.shape();return Object.entries(a).map(([l,u])=>{var d,p;let h=ee.getMetadata(u),w=this.getParameterRef(h,{in:r,name:l});if(w)return w;let b=(d=h?.metadata)===null||d===void 0?void 0:d.param;if(b?.name&&b.name!==l)throw new lr("Conflicting names for parameter",{key:"name",values:[l,b.name]});if(b?.in&&b.in!==r)throw new lr(`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(i?.in&&i.in!==r)throw new lr(`Conflicting location for parameter ${i.name}`,{key:"in",values:[r,i.in]});return[this.generateParameter(e.openapi({param:{in:r}}))]}generateSimpleParameter(e){var r;let n=ee.getParamMetadata(e),o=(r=n?.metadata)===null||r===void 0?void 0:r.param,i=!ee.isOptionalSchema(e)&&!e.isNullable(),s=this.generateSchemaWithRef(e);return Object.assign({schema:s,required:i},o?ee.buildParameterMetadata(o):{})}generateParameter(e){var r;let n=ee.getMetadata(e),o=(r=n?.metadata)===null||r===void 0?void 0:r.param,i=o?.name,s=o?.in;if(!i)throw new Yr({missingField:"name"});if(!s)throw new Yr({missingField:"in",paramName:i});let a=this.generateSimpleParameter(e);return Object.assign(Object.assign({},a),{in:s,name:i})}generateSchemaWithMetadata(e){var r;let n=ee.unwrapChained(e),o=ee.getMetadata(e),i=ee.getDefaultValue(e),s=!((r=o?.metadata)===null||r===void 0)&&r.type?{type:o?.metadata.type}:this.toOpenAPISchema(n,e.isNullable(),i);return o?.metadata?ee.applySchemaMetadata(s,o.metadata):Gr(s,Hn)}constructReferencedOpenAPISchema(e){var r;let n=ee.getMetadata(e),o=ee.unwrapChained(e),i=ee.getDefaultValue(e),s=e.isNullable();return!((r=n?.metadata)===null||r===void 0)&&r.type?this.versionSpecifics.mapNullableType(n.metadata.type,s):this.toOpenAPISchema(o,s,i)}generateSimpleSchema(e){var r;let n=ee.getMetadata(e),o=ee.getRefId(e);if(!o||!this.schemaRefs[o])return this.generateSchemaWithMetadata(e);let i=this.schemaRefs[o],s={$ref:this.generateSchemaRef(o)},a=Gr(ee.buildSchemaMetadata((r=n?.metadata)!==null&&r!==void 0?r:{}),(u,d)=>u===void 0||ba(u,i[d]));if(a.type)return{allOf:[s,a]};let c=Gr(this.constructReferencedOpenAPISchema(e),(u,d)=>u===void 0||ba(u,i[d])),l=ee.applySchemaMetadata(c,a);return Object.keys(l).length>0?{allOf:[s,l]}:s}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=Qn(e,["content"]),o=this.getBodyContent(r);return Object.assign(Object.assign({},n),{content:o})}getParameters(e){if(!e)return[];let{headers:r}=e,n=this.cleanParameter(e.query),o=this.cleanParameter(e.params),i=this.cleanParameter(e.cookies),s=Wn(()=>n?this.generateInlineParameters(n,"query"):[],{location:"query"}),a=Wn(()=>o?this.generateInlineParameters(o,"path"):[],{location:"path"}),c=Wn(()=>i?this.generateInlineParameters(i,"cookie"):[],{location:"cookie"}),l=Wn(()=>{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,...s,...l,...c]}cleanParameter(e){if(e)return U(e,"ZodEffects")?this.cleanParameter(e._def.schema):e}generatePath(e){let{method:r,path:n,request:o,responses:i}=e,s=Qn(e,["method","path","request","responses"]),a=Jn(i,d=>this.getResponse(d)),c=Wn(()=>this.getParameters(o),{route:`${r} ${n}`}),l=this.getRequestBody(o?.body);return{[r]:Object.assign(Object.assign(Object.assign(Object.assign({},s),c.length>0?{parameters:[...s.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,o=Qn(e,["content","headers"]),i=r?{content:this.getBodyContent(r)}:{};if(!n)return Object.assign(Object.assign({},o),i);let s=U(n,"ZodObject")?this.getResponseHeaders(n):n;return Object.assign(Object.assign(Object.assign({},o),{headers:s}),i)}isReferenceObject(e){return"$ref"in e}getResponseHeaders(e){let r=e._def.shape();return Jn(r,o=>this.generateSimpleParameter(o))}getBodyContent(e){return Jn(e,r=>{if(!r||!ih(r.schema))return r;let{schema:n}=r,o=Qn(r,["schema"]),i=this.generateSchemaWithRef(n);return Object.assign({schema:i},o)})}toOpenAPISchema(e,r,n){return this.openApiTransformer.transform(e,r,o=>this.generateSchemaWithRef(o),o=>this.generateSchemaRef(o),n)}},Ca=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=ah(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{}}}))}},hi=class{constructor(e){let r=new Ca;this.generator=new mi(e,r)}generateDocument(e){let r=this.generator.generateDocumentData();return Object.assign(Object.assign({},e),r)}generateComponents(){return this.generator.generateComponents()}},$a=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 lh(t){return"type"in t&&t.type==="webhook"}var gi=class{constructor(e){this.definitions=e,this.webhookRefs={};let r=new $a;this.generator=new mi(this.definitions,r)}generateDocument(e){let r=this.generator.generateDocumentData();return this.definitions.filter(lh).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 qa=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Ou=t=>{let{groups:e,path:r}=uh(t),n=qa(r);return dh(n,e)},uh=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},dh=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let o=t.length-1;o>=0;o--)if(t[o].includes(n)){t[o]=t[o].replace(n,e[r][1]);break}}return t},bi={},Nu=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return bi[n]||(r[2]?bi[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:bi[n]=[t,r[1],!0]),bi[n]}return null},Xr=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},fh=t=>Xr(t,decodeURI),La=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o===37){let i=e.indexOf("?",n),s=e.indexOf("#",n),a=i===-1?s===-1?void 0:s:s===-1?i:Math.min(i,s),c=e.slice(r,a);return fh(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var Pu=t=>{let e=La(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},Ue=(t,e,...r)=>(r.length&&(e=Ue(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),wi=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let i=o.replace("?","");n+="/"+i,r.push(n)}else n+="/"+o}),r.filter((o,i,s)=>s.indexOf(o)===i)},za=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?Xr(t,Gn):t):t,Cu=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let s=t.indexOf("?",8);if(s===-1)return;for(t.startsWith(e,s+1)||(s=t.indexOf(`&${e}`,s+1));s!==-1;){let a=t.charCodeAt(s+e.length+1);if(a===61){let c=s+e.length+2,l=t.indexOf("&",c);return za(t.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";s=t.indexOf(`&${e}`,s+1)}if(n=/[%+]/.test(t),!n)return}let o={};n??=/[%+]/.test(t);let i=t.indexOf("?",8);for(;i!==-1;){let s=t.indexOf("&",i+1),a=t.indexOf("=",i);a>s&&s!==-1&&(a=-1);let c=t.slice(i+1,a===-1?s===-1?void 0:s:a);if(n&&(c=za(c)),i=s,c==="")continue;let l;a===-1?l="":(l=t.slice(a+1,s===-1?void 0:s),n&&(l=za(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return e?o[e]:o},$u=Cu,zu=(t,e)=>Cu(t,e,!0),Gn=decodeURIComponent;var ph=/^[\w!#$%&'*.^`|~+-]+$/,mh=/^[ !#-:<-[\]-~]*$/,qu=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)},Da=(t,e)=>{if(e&&t.indexOf(e)===-1)return{};let r=t.split(";"),n=Object.create(null);for(let o of r){let i=o.indexOf("=");if(i===-1)continue;let s=qu(o.substring(0,i));if(e&&e!==s||!ph.test(s)||s in n)continue;let a=qu(o.substring(i+1));if(a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),mh.test(a)&&(n[s]=a.indexOf("%")!==-1?Xr(a,Gn):a,e))break}return n};var Lu=(t,e,r)=>{let n=t.req.raw.headers.get("Cookie");if(typeof e=="string"){if(!n)return;let i=e;return r==="secure"?i="__Secure-"+e:r==="host"&&(i="__Host-"+e),Da(n,i)[i]}return n?Da(n):{}};var Lt=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 hh=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,gh=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,yh=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Ma=(t,e)=>async(r,n)=>{let o={},i=r.req.header("Content-Type");switch(t){case"json":if(!i||!hh.test(i))break;try{o=await r.req.json()}catch{let a="Malformed JSON in request body";throw new Lt(400,{message:a})}break;case"form":{if(!i||!(gh.test(i)||yh.test(i)))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,i),r.req.bodyCache.formData=a}catch(l){let u="Malformed FormData request.";throw u+=l instanceof Error?` ${l.message}`:` ${String(l)}`,new Lt(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}),o=c;break}case"query":o=Object.fromEntries(Object.entries(r.req.queries()).map(([a,c])=>c.length===1?[a,c[0]]:[a,c]));break;case"param":o=r.req.param();break;case"header":o=r.req.header();break;case"cookie":o=Lu(r);break}let s=await e(o,r);return s instanceof Response?s:(r.req.addValidatedData(t,s),await n())};var ur=(t,e,r)=>Ma(t,async(n,o)=>{let i=await e.safeParseAsync(n);if(r){let s=await r({data:n,...i,target:t},o);if(s){if(s instanceof Response)return s;if("response"in s)return s.response}}return i.success?i.data:o.json(i,400)});var Ka=(t,e,r)=>(n,o)=>{let i=-1;return s(0);async function s(a){if(a<=i)throw new Error("next() called multiple times");i=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],n.req.routeIndex=a):u=a===t.length&&o||void 0,u)try{c=await u(n,()=>s(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 Mu=Symbol();var Ku=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,i=(t instanceof vi?t.raw.headers:t.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?bh(t,{all:r,dot:n}):{}};async function bh(t,e){let r=await t.formData();return r?wh(r,e):{}}function wh(t,e){let r=Object.create(null);return t.forEach((n,o)=>{e.all||o.endsWith("[]")?vh(r,o,n):r[o]=n}),e.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(xh(r,n,o),delete r[n])}),r}var vh=(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},xh=(t,e,r)=>{if(/(?:^|\.)__proto__\./.test(e))return;let n=t,o=e.split(".");o.forEach((i,s)=>{s===o.length-1?n[i]=r:((!n[i]||typeof n[i]!="object"||Array.isArray(n[i])||n[i]instanceof File)&&(n[i]=Object.create(null)),n=n[i])})};var Uu=t=>Xr(t,Gn),vi=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.#i()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#o(e);return r&&/\%/.test(r)?Uu(r):r}#i(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?Uu(n):n)}return t}#o(t){return this.#e[1]?this.#e[1][t]:t}query(t){return $u(this.url,t)}queries(t){return zu(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 Ku(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let o=Object.keys(e)[0];return o?e[o].then(i=>(o==="json"&&(i=JSON.stringify(i)),new Response(i)[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[Mu](){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 Bu={Stringify:1,BeforeStream:2,Stream:3},kh=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var Ua=async(t,e,r,n,o)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let i=t.callbacks;if(!i?.length)return Promise.resolve(t);o?o[0]+=t:o=[t];let s=Promise.all(i.map(a=>a({phase:e,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>Ua(c,e,!1,n,o))).then(()=>o[0]));return r?kh(await s,i):s};var _h="text/plain; charset=UTF-8",Ba=(t,e)=>({"Content-Type":t,...e}),Zn=(t,e)=>new Response(t,e),Fa=class{#t;#e;env={};#r;finalized=!1;error;#i;#o;#n;#u;#c;#l;#a;#d;#f;constructor(t,e){this.#t=t,e&&(this.#o=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#f=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new vi(this.#t,this.#f,this.#d),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=Zn(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=Zn(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 o of n)t.headers.append("set-cookie",o)}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=Zn(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.#i=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):{}}#s(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let i=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[s,a]of i)s.toLowerCase()==="set-cookie"?n.append(s,a):n.set(s,a)}if(r)for(let[i,s]of Object.entries(r))if(typeof s=="string")n.set(i,s);else{n.delete(i);for(let a of s)n.append(i,a)}let o=typeof e=="number"?e:e?.status??this.#i;return Zn(t,{status:o,headers:n})}newResponse=(...t)=>this.#s(...t);body=(t,e,r)=>this.#s(t,e,r);text=(t,e,r)=>!this.#a&&!this.#i&&!e&&!r&&!this.finalized?new Response(t):this.#s(t,e,Ba(_h,r));json=(t,e,r)=>this.#s(JSON.stringify(t),e,Ba("application/json",r));html=(t,e,r)=>{let n=o=>this.#s(o,e,Ba("text/html; charset=UTF-8",r));return typeof t=="object"?Ua(t,Bu.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??=()=>Zn(),this.#l(this))};var oe="ALL",Fu="all",Vu=["get","post","put","delete","options","patch"],xi="Can not add a route since the matcher is already built.",ki=class extends Error{};var Wu="__COMPOSED_HANDLER";var Ih=t=>t.text("404 Not Found",404),Qu=(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)},Hu=class Ju{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Vu,Fu].forEach(i=>{this[i]=(s,...a)=>(typeof s=="string"?this.#t=s:this.#i(i,this.#t,s),a.forEach(c=>{this.#i(i,this.#t,c)}),this)}),this.on=(i,s,...a)=>{for(let c of[s].flat()){this.#t=c;for(let l of[i].flat())a.map(u=>{this.#i(l.toUpperCase(),this.#t,u)})}return this},this.use=(i,...s)=>(typeof i=="string"?this.#t=i:(this.#t="*",s.unshift(i)),s.forEach(a=>{this.#i(oe,this.#t,a)}),this);let{strict:n,...o}=e;Object.assign(this,o),this.getPath=n??!0?e.getPath??La:Pu}#e(){let e=new Ju({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=Ih;errorHandler=Qu;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let i;r.errorHandler===Qu?i=o.handler:(i=async(s,a)=>(await Ka([],r.errorHandler)(s,()=>o.handler(s,a))).res,i[Wu]=o.handler),n.#i(o.method,o.path,i,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=Ue(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,r,n){let o,i;n&&(typeof n=="function"?i=n:(i=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let s=i?c=>{let l=i(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=Ue(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(o(c.req.raw),...s(c));if(u)return u;await l()};return this.#i(oe,Ue(e,"*"),a),this}#i(e,r,n,o){e=e.toUpperCase(),r=Ue(this._basePath,r);let i={basePath:o!==void 0?Ue(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,i]),this.routes.push(i)}#o(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#n(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(e,r,n,"GET")))();let i=this.getPath(e,{env:n}),s=this.router.match(o,i),a=new Fa(e,{path:i,matchResult:s,env:n,executionCtx:r,notFoundHandler:this.#r});if(s[0].length===1){let l;try{l=s[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=Ka(s[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.#o(l,a)}})()}fetch=(e,...r)=>this.#n(e,r[1],r[0],e.method);request=(e,r,n,o)=>e instanceof Request?this.fetch(r?new Request(e,r):e,n,o):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${Ue("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var _i=[];function Va(t,e){let r=this.buildAllMatchers(),n=((o,i)=>{let s=r[o]||r[oe],a=s[2][i];if(a)return a;let c=i.match(s[0]);if(!c)return[[],_i];let l=c.indexOf("",1);return[s[1][l],c]});return this.match=n,n(t,e)}var Ii="[^/]+",Yn=".*",Xn="(?:|/.*)",dr=Symbol(),Sh=new Set(".\\+*[^]$()");function Eh(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===Yn||t===Xn?1:e===Yn||e===Xn?-1:t===Ii?1:e===Ii?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Gu=class Wa{#t;#e;#r=Object.create(null);insert(e,r,n,o,i){if(e.length===0){if(this.#t!==void 0)throw dr;if(i)return;this.#t=r;return}let[s,...a]=e,c=s==="*"?a.length===0?["","",Yn]:["","",Ii]:s==="/*"?["","",Xn]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||Ii;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw dr;if(l=this.#r[d],!l){if(Object.keys(this.#r).some(p=>p!==Yn&&p!==Xn))throw dr;if(i)return;l=this.#r[d]=new Wa,u!==""&&(l.#e=o.varIndex++)}!i&&u!==""&&n.push([u,l.#e])}else if(l=this.#r[s],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==Yn&&u!==Xn))throw dr;if(i)return;l=this.#r[s]=new Wa}l.insert(a,r,n,o,i)}buildRegExpStr(){let r=Object.keys(this.#r).sort(Eh).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:Sh.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var Zu=class{#t={varIndex:0};#e=new Gu;insert(t,e,r){let n=[],o=[];for(let s=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let l=`@\\${s}`;return o[s]=[l,c],s++,a=!0,l}),!a)break}let i=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let s=o.length-1;s>=0;s--){let[a]=o[s];for(let c=i.length-1;c>=0;c--)if(i[c].indexOf(a)!==-1){i[c]=i[c].replace(a,o[s][1]);break}}return this.#e.insert(i,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,(o,i,s)=>i!==void 0?(r[++e]=Number(i),"$()"):(s!==void 0&&(n[Number(s)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var jh=[/^$/,[],Object.create(null)],Yu=Object.create(null);function Xu(t){return Yu[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function Th(){Yu=Object.create(null)}function Ah(t){let e=new Zu,r=[];if(t.length===0)return jh;let n=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[d,p])=>l?1:d?-1:u.length-p.length),o=Object.create(null);for(let l=0,u=-1,d=n.length;l<d;l++){let[p,h,w]=n[l];p?o[h]=[w.map(([_])=>[_,Object.create(null)]),_i]:u++;let b;try{b=e.insert(h,u,p)}catch(_){throw _===dr?new ki(h):_}p||(r[u]=w.map(([_,k])=>{let C=Object.create(null);for(k-=1;k>=0;k--){let[q,O]=b[k];C[q]=O}return[_,C]}))}let[i,s,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 h=r[l][d]?.[1];if(!h)continue;let w=Object.keys(h);for(let b=0,_=w.length;b<_;b++)h[w[b]]=a[h[w[b]]]}let c=[];for(let l in s)c[l]=r[s[l]];return[i,c,o]}function en(t,e){if(t){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(Xu(r).test(e))return[...t[r]]}}var Si=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[oe]:Object.create(null)},this.#e={[oe]:Object.create(null)}}add(t,e,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(xi);n[t]||[n,o].forEach(a=>{a[t]=Object.create(null),Object.keys(a[oe]).forEach(c=>{a[t][c]=[...a[oe][c]]})}),e==="/*"&&(e="*");let i=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=Xu(e);t===oe?Object.keys(n).forEach(c=>{n[c][e]||=en(n[c],e)||en(n[oe],e)||[]}):n[t][e]||=en(n[t],e)||en(n[oe],e)||[],Object.keys(n).forEach(c=>{(t===oe||t===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,i])})}),Object.keys(o).forEach(c=>{(t===oe||t===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,i]))});return}let s=wi(e)||[e];for(let a=0,c=s.length;a<c;a++){let l=s[a];Object.keys(o).forEach(u=>{(t===oe||t===u)&&(o[u][l]||=[...en(n[u],l)||en(n[oe],l)||[]],o[u][l].push([r,i-c+a+1]))})}}match=Va;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,Th(),t}#r(t){let e=[],r=t===oe;return[this.#t,this.#e].forEach(n=>{let o=n[t]?Object.keys(n[t]).map(i=>[i,n[t][i]]):[];o.length!==0?(r||=!0,e.push(...o)):t!==oe&&e.push(...Object.keys(n[oe]).map(i=>[i,n[oe][i]]))}),r?Ah(e):null}};var Qa=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(xi);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,i=0,s;for(;i<o;i++){let a=r[i];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);s=a.match(t,e)}catch(c){if(c instanceof ki)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(i===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,s}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var eo=Object.create(null),Rh=t=>{for(let e in t)return!0;return!1},ed=class td{#t;#e;#r;#i=0;#o=eo;constructor(e,r,n){if(this.#e=n||Object.create(null),this.#t=[],e&&r){let o=Object.create(null);o[e]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(e,r,n){this.#i=++this.#i;let o=this,i=Ou(r),s=[];for(let a=0,c=i.length;a<c;a++){let l=i[a],u=i[a+1],d=Nu(l,u),p=Array.isArray(d)?d[0]:l;if(p in o.#e){o=o.#e[p],d&&s.push(d[1]);continue}o.#e[p]=new td,d&&(o.#r.push(d),s.push(d[1])),o=o.#e[p]}return o.#t.push({[e]:{handler:n,possibleKeys:s.filter((a,c,l)=>l.indexOf(a)===c),score:this.#i}}),o}#n(e,r,n,o,i){for(let s=0,a=r.#t.length;s<a;s++){let c=r.#t[s],l=c[n]||c[oe],u={};if(l!==void 0&&(l.params=Object.create(null),e.push(l),o!==eo||i&&i!==eo))for(let d=0,p=l.possibleKeys.length;d<p;d++){let h=l.possibleKeys[d],w=u[l.score];l.params[h]=i?.[h]&&!w?i[h]:o[h]??i?.[h],u[l.score]=!0}}}search(e,r){let n=[];this.#o=eo;let i=[this],s=qa(r),a=[],c=s.length,l=null;for(let u=0;u<c;u++){let d=s[u],p=u===c-1,h=[];for(let b=0,_=i.length;b<_;b++){let k=i[b],C=k.#e[d];C&&(C.#o=k.#o,p?(C.#e["*"]&&this.#n(n,C.#e["*"],e,k.#o),this.#n(n,C,e,k.#o)):h.push(C));for(let q=0,O=k.#r.length;q<O;q++){let X=k.#r[q],L=k.#o===eo?{}:{...k.#o};if(X==="*"){let we=k.#e["*"];we&&(this.#n(n,we,e,k.#o),we.#o=L,h.push(we));continue}let[S,A,Q]=X;if(!d&&!(Q instanceof RegExp))continue;let ie=k.#e[S];if(Q 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+=s[J].length+1}let we=r.substring(l[u]),le=Q.exec(we);if(le){if(L[A]=le[0],this.#n(n,ie,e,k.#o,L),Rh(ie.#e)){ie.#o=L;let re=le[0].match(/\//)?.length??0;(a[re]||=[]).push(ie)}continue}}(Q===!0||Q.test(d))&&(L[A]=d,p?(this.#n(n,ie,e,L,k.#o),ie.#e["*"]&&this.#n(n,ie.#e["*"],e,L,k.#o)):(ie.#o=L,h.push(ie)))}}let w=a.shift();i=w?h.concat(w):h}return n.length>1&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var Ha=class{name="TrieRouter";#t;constructor(){this.#t=new ed}add(t,e,r){let n=wi(e);if(n){for(let o=0,i=n.length;o<i;o++)this.#t.insert(t,n[o],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}};var Ja=class extends Hu{constructor(t={}){super(t),this.router=t.router??new Qa({routers:[new Si,new Ha]})}};var g={};Cc(g,{BRAND:()=>dd,DIRTY:()=>Dt,EMPTY_PATH:()=>id,INVALID:()=>P,NEVER:()=>Kd,OK:()=>Ie,ParseStatus:()=>ke,Schema:()=>z,ZodAny:()=>jt,ZodArray:()=>dt,ZodBigInt:()=>Kt,ZodBoolean:()=>Ut,ZodBranded:()=>nn,ZodCatch:()=>Xt,ZodDate:()=>Bt,ZodDefault:()=>Yt,ZodDiscriminatedUnion:()=>no,ZodEffects:()=>De,ZodEnum:()=>Gt,ZodError:()=>Oe,ZodFirstPartyTypeKind:()=>$,ZodFunction:()=>io,ZodIntersection:()=>Qt,ZodIssueCode:()=>x,ZodLazy:()=>Ht,ZodLiteral:()=>Jt,ZodMap:()=>gr,ZodNaN:()=>br,ZodNativeEnum:()=>Zt,ZodNever:()=>Fe,ZodNull:()=>Vt,ZodNullable:()=>Ye,ZodNumber:()=>Mt,ZodObject:()=>Ne,ZodOptional:()=>Le,ZodParsedType:()=>T,ZodPipeline:()=>on,ZodPromise:()=>Tt,ZodReadonly:()=>er,ZodRecord:()=>oo,ZodSchema:()=>z,ZodSet:()=>yr,ZodString:()=>Et,ZodSymbol:()=>mr,ZodTransformer:()=>De,ZodTuple:()=>Ze,ZodType:()=>z,ZodUndefined:()=>Ft,ZodUnion:()=>Wt,ZodUnknown:()=>ut,ZodVoid:()=>hr,addIssueToContext:()=>E,any:()=>vd,array:()=>ze,bigint:()=>hd,boolean:()=>ec,coerce:()=>Md,custom:()=>Xa,date:()=>gd,datetimeRegex:()=>Ya,default:()=>Xh,defaultErrorMap:()=>lt,discriminatedUnion:()=>cn,effect:()=>Nd,enum:()=>Ve,function:()=>Td,getErrorMap:()=>fr,getParsedType:()=>Ge,instanceof:()=>pd,intersection:()=>Id,isAborted:()=>to,isAsync:()=>pr,isDirty:()=>ro,isValid:()=>It,late:()=>fd,lazy:()=>Ad,literal:()=>Se,makeIssue:()=>tn,map:()=>Ed,nan:()=>md,nativeEnum:()=>Rd,never:()=>xd,null:()=>wd,nullable:()=>Cd,number:()=>pe,object:()=>B,objectUtil:()=>Ei,oboolean:()=>Dd,onumber:()=>Ld,optional:()=>Pd,ostring:()=>qd,pipeline:()=>zd,preprocess:()=>$d,promise:()=>Od,quotelessJson:()=>rd,record:()=>wr,set:()=>jd,setErrorMap:()=>od,strictObject:()=>_d,string:()=>N,symbol:()=>yd,transformer:()=>Nd,tuple:()=>Sd,undefined:()=>bd,union:()=>an,unknown:()=>sn,util:()=>F,void:()=>kd,z:()=>j});var j={};Cc(j,{BRAND:()=>dd,DIRTY:()=>Dt,EMPTY_PATH:()=>id,INVALID:()=>P,NEVER:()=>Kd,OK:()=>Ie,ParseStatus:()=>ke,Schema:()=>z,ZodAny:()=>jt,ZodArray:()=>dt,ZodBigInt:()=>Kt,ZodBoolean:()=>Ut,ZodBranded:()=>nn,ZodCatch:()=>Xt,ZodDate:()=>Bt,ZodDefault:()=>Yt,ZodDiscriminatedUnion:()=>no,ZodEffects:()=>De,ZodEnum:()=>Gt,ZodError:()=>Oe,ZodFirstPartyTypeKind:()=>$,ZodFunction:()=>io,ZodIntersection:()=>Qt,ZodIssueCode:()=>x,ZodLazy:()=>Ht,ZodLiteral:()=>Jt,ZodMap:()=>gr,ZodNaN:()=>br,ZodNativeEnum:()=>Zt,ZodNever:()=>Fe,ZodNull:()=>Vt,ZodNullable:()=>Ye,ZodNumber:()=>Mt,ZodObject:()=>Ne,ZodOptional:()=>Le,ZodParsedType:()=>T,ZodPipeline:()=>on,ZodPromise:()=>Tt,ZodReadonly:()=>er,ZodRecord:()=>oo,ZodSchema:()=>z,ZodSet:()=>yr,ZodString:()=>Et,ZodSymbol:()=>mr,ZodTransformer:()=>De,ZodTuple:()=>Ze,ZodType:()=>z,ZodUndefined:()=>Ft,ZodUnion:()=>Wt,ZodUnknown:()=>ut,ZodVoid:()=>hr,addIssueToContext:()=>E,any:()=>vd,array:()=>ze,bigint:()=>hd,boolean:()=>ec,coerce:()=>Md,custom:()=>Xa,date:()=>gd,datetimeRegex:()=>Ya,defaultErrorMap:()=>lt,discriminatedUnion:()=>cn,effect:()=>Nd,enum:()=>Ve,function:()=>Td,getErrorMap:()=>fr,getParsedType:()=>Ge,instanceof:()=>pd,intersection:()=>Id,isAborted:()=>to,isAsync:()=>pr,isDirty:()=>ro,isValid:()=>It,late:()=>fd,lazy:()=>Ad,literal:()=>Se,makeIssue:()=>tn,map:()=>Ed,nan:()=>md,nativeEnum:()=>Rd,never:()=>xd,null:()=>wd,nullable:()=>Cd,number:()=>pe,object:()=>B,objectUtil:()=>Ei,oboolean:()=>Dd,onumber:()=>Ld,optional:()=>Pd,ostring:()=>qd,pipeline:()=>zd,preprocess:()=>$d,promise:()=>Od,quotelessJson:()=>rd,record:()=>wr,set:()=>jd,setErrorMap:()=>od,strictObject:()=>_d,string:()=>N,symbol:()=>yd,transformer:()=>Nd,tuple:()=>Sd,undefined:()=>bd,union:()=>an,unknown:()=>sn,util:()=>F,void:()=>kd});var F;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let i={};for(let s of o)i[s]=s;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of i)s[a]=o[a];return t.objectValues(s)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},t.find=(o,i)=>{for(let s of o)if(i(s))return s},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(F||(F={}));var Ei;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ei||(Ei={}));var T=F.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ge=t=>{switch(typeof t){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(t)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":return Array.isArray(t)?T.array:t===null?T.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?T.promise:typeof Map<"u"&&t instanceof Map?T.map:typeof Set<"u"&&t instanceof Set?T.set:typeof Date<"u"&&t instanceof Date?T.date:T.object;default:return T.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"]),rd=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Oe=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(i){return i.message},n={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let l=s.path[c];c===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(s))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(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 o of this.issues)if(o.path.length>0){let i=o.path[0];r[i]=r[i]||[],r[i].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Oe.create=t=>new Oe(t);var Oh=(t,e)=>{let r;switch(t.code){case x.invalid_type:t.received===T.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}},lt=Oh;var nd=lt;function od(t){nd=t}function fr(){return nd}var tn=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,i=[...r,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(s,{data:e,defaultError:a}).message;return{...o,path:i,message:a}},id=[];function E(t,e){let r=fr(),n=tn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===lt?void 0:lt].filter(o=>!!o)});t.common.issues.push(n)}var ke=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 o of r){if(o.status==="aborted")return P;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let i=await o.key,s=await o.value;n.push({key:i,value:s})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return P;i.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(n[i.value]=s.value)}return{status:e.value,value:n}}},P=Object.freeze({status:"aborted"}),Dt=t=>({status:"dirty",value:t}),Ie=t=>({status:"valid",value:t}),to=t=>t.status==="aborted",ro=t=>t.status==="dirty",It=t=>t.status==="valid",pr=t=>typeof Promise<"u"&&t instanceof Promise;var R;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(R||(R={}));var Be=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}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}},sd=(t,e)=>{if(It(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 Oe(t.common.issues);return this._error=r,this._error}}};function D(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=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:o}:{errorMap:(s,a)=>{let{message:c}=t;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var z=class{get description(){return this._def.description}_getType(e){return Ge(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ge(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ke,ctx:{common:e.parent.common,data:e.data,parsedType:Ge(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(pr(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:Ge(e)},o=this._parseSync({data:e,path:n.path,parent:n});return sd(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ge(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return It(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=>It(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:Ge(e)},o=this._parse({data:e,path:n.path,parent:n}),i=await(pr(o)?o:Promise.resolve(o));return sd(n,i)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,i)=>{let s=e(o),a=()=>i.addIssue({code:x.custom,...n(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new De({schema:this,typeName:$.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 Le.create(this,this._def)}nullable(){return Ye.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return dt.create(this)}promise(){return Tt.create(this,this._def)}or(e){return Wt.create([this,e],this._def)}and(e){return Qt.create(this,e,this._def)}transform(e){return new De({...D(this._def),schema:this,typeName:$.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Yt({...D(this._def),innerType:this,defaultValue:r,typeName:$.ZodDefault})}brand(){return new nn({typeName:$.ZodBranded,type:this,...D(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Xt({...D(this._def),innerType:this,catchValue:r,typeName:$.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return on.create(this,e)}readonly(){return er.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Nh=/^c[^\s-]{8,}$/i,Ph=/^[0-9a-z]+$/,Ch=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$h=/^[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,zh=/^[a-z0-9_-]{21}$/i,qh=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Lh=/^[-+]?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)?)??$/,Dh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Mh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ga,Kh=/^(?:(?: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])$/,Uh=/^(?:(?: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])$/,Bh=/^(([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]))$/,Fh=/^(([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])$/,Vh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Wh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,cd="((\\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(`^${cd}$`);function ld(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 Hh(t){return new RegExp(`^${ld(t)}$`)}function Ya(t){let e=`${cd}T${ld(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 Jh(t,e){return!!((e==="v4"||!e)&&Kh.test(t)||(e==="v6"||!e)&&Bh.test(t))}function Gh(t,e){if(!qh.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,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Zh(t,e){return!!((e==="v4"||!e)&&Uh.test(t)||(e==="v6"||!e)&&Fh.test(t))}var Et=class t extends z{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==T.string){let i=this._getOrReturnCtx(e);return E(i,{code:x.invalid_type,expected:T.string,received:i.parsedType}),P}let n=new ke,o;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:x.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:x.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;(s||a)&&(o=this._getOrReturnCtx(e,o),s?E(o,{code:x.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&E(o,{code:x.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Dh.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"email",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Ga||(Ga=new RegExp(Mh,"u")),Ga.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"emoji",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")$h.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"uuid",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")zh.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"nanoid",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Nh.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Ph.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid2",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Ch.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ulid",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),E(o,{validation:"url",code:x.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"regex",code:x.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),E(o,{code:x.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:x.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:x.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Ya(i).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:x.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Qh.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:x.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Hh(i).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:x.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Lh.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"duration",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Jh(e.data,i.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ip",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Gh(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"jwt",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Zh(e.data,i.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cidr",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Vh.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Wh.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64url",code:x.invalid_string,message:i.message}),n.dirty()):F.assertNever(i);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:x.invalid_string,...R.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...R.errToObj(e)})}url(e){return this._addCheck({kind:"url",...R.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...R.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...R.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...R.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...R.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...R.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...R.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...R.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...R.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...R.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...R.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...R.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,...R.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,...R.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...R.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...R.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...R.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...R.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...R.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...R.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...R.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...R.errToObj(r)})}nonempty(e){return this.min(1,R.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}};Et.create=t=>new Et({checks:[],typeName:$.ZodString,coerce:t?.coerce??!1,...D(t)});function Yh(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(t.toFixed(o).replace(".","")),s=Number.parseInt(e.toFixed(o).replace(".",""));return i%s/10**o}var Mt=class t extends z{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)!==T.number){let i=this._getOrReturnCtx(e);return E(i,{code:x.invalid_type,expected:T.number,received:i.parsedType}),P}let n,o=new ke;for(let i of this._def.checks)i.kind==="int"?F.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:x.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:x.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:x.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?Yh(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),E(n,{code:x.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:x.not_finite,message:i.message}),o.dirty()):F.assertNever(i);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,R.toString(r))}gt(e,r){return this.setLimit("min",e,!1,R.toString(r))}lte(e,r){return this.setLimit("max",e,!0,R.toString(r))}lt(e,r){return this.setLimit("max",e,!1,R.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:R.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:R.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:R.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.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)}};Mt.create=t=>new Mt({checks:[],typeName:$.ZodNumber,coerce:t?.coerce||!1,...D(t)});var Kt=class t extends z{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)!==T.bigint)return this._getInvalidInput(e);let n,o=new ke;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:x.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:x.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),E(n,{code:x.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):F.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return E(r,{code:x.invalid_type,expected:T.bigint,received:r.parsedType}),P}gte(e,r){return this.setLimit("min",e,!0,R.toString(r))}gt(e,r){return this.setLimit("min",e,!1,R.toString(r))}lte(e,r){return this.setLimit("max",e,!0,R.toString(r))}lt(e,r){return this.setLimit("max",e,!1,R.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:R.toString(o)}]})}_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:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:R.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}};Kt.create=t=>new Kt({checks:[],typeName:$.ZodBigInt,coerce:t?.coerce??!1,...D(t)});var Ut=class extends z{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==T.boolean){let n=this._getOrReturnCtx(e);return E(n,{code:x.invalid_type,expected:T.boolean,received:n.parsedType}),P}return Ie(e.data)}};Ut.create=t=>new Ut({typeName:$.ZodBoolean,coerce:t?.coerce||!1,...D(t)});var Bt=class t extends z{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==T.date){let i=this._getOrReturnCtx(e);return E(i,{code:x.invalid_type,expected:T.date,received:i.parsedType}),P}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return E(i,{code:x.invalid_date}),P}let n=new ke,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:x.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:x.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):F.assertNever(i);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:R.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:R.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}};Bt.create=t=>new Bt({checks:[],coerce:t?.coerce||!1,typeName:$.ZodDate,...D(t)});var mr=class extends z{_parse(e){if(this._getType(e)!==T.symbol){let n=this._getOrReturnCtx(e);return E(n,{code:x.invalid_type,expected:T.symbol,received:n.parsedType}),P}return Ie(e.data)}};mr.create=t=>new mr({typeName:$.ZodSymbol,...D(t)});var Ft=class extends z{_parse(e){if(this._getType(e)!==T.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:x.invalid_type,expected:T.undefined,received:n.parsedType}),P}return Ie(e.data)}};Ft.create=t=>new Ft({typeName:$.ZodUndefined,...D(t)});var Vt=class extends z{_parse(e){if(this._getType(e)!==T.null){let n=this._getOrReturnCtx(e);return E(n,{code:x.invalid_type,expected:T.null,received:n.parsedType}),P}return Ie(e.data)}};Vt.create=t=>new Vt({typeName:$.ZodNull,...D(t)});var jt=class extends z{constructor(){super(...arguments),this._any=!0}_parse(e){return Ie(e.data)}};jt.create=t=>new jt({typeName:$.ZodAny,...D(t)});var ut=class extends z{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ie(e.data)}};ut.create=t=>new ut({typeName:$.ZodUnknown,...D(t)});var Fe=class extends z{_parse(e){let r=this._getOrReturnCtx(e);return E(r,{code:x.invalid_type,expected:T.never,received:r.parsedType}),P}};Fe.create=t=>new Fe({typeName:$.ZodNever,...D(t)});var hr=class extends z{_parse(e){if(this._getType(e)!==T.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:x.invalid_type,expected:T.void,received:n.parsedType}),P}return Ie(e.data)}};hr.create=t=>new hr({typeName:$.ZodVoid,...D(t)});var dt=class t extends z{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==T.array)return E(r,{code:x.invalid_type,expected:T.array,received:r.parsedType}),P;if(o.exactLength!==null){let s=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(s||a)&&(E(r,{code:s?x.too_big:x.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(E(r,{code:x.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(E(r,{code:x.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>o.type._parseAsync(new Be(r,s,r.path,a)))).then(s=>ke.mergeArray(n,s));let i=[...r.data].map((s,a)=>o.type._parseSync(new Be(r,s,r.path,a)));return ke.mergeArray(n,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:R.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:R.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:R.toString(r)}})}nonempty(e){return this.min(1,e)}};dt.create=(t,e)=>new dt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...D(e)});function rn(t){if(t instanceof Ne){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Le.create(rn(n))}return new Ne({...t._def,shape:()=>e})}else return t instanceof dt?new dt({...t._def,type:rn(t.element)}):t instanceof Le?Le.create(rn(t.unwrap())):t instanceof Ye?Ye.create(rn(t.unwrap())):t instanceof Ze?Ze.create(t.items.map(e=>rn(e))):t}var Ne=class t extends z{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)!==T.object){let l=this._getOrReturnCtx(e);return E(l,{code:x.invalid_type,expected:T.object,received:l.parsedType}),P}let{status:n,ctx:o}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Fe&&this._def.unknownKeys==="strip"))for(let l in o.data)s.includes(l)||a.push(l);let c=[];for(let l of s){let u=i[l],d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Be(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Fe){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(E(o,{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=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Be(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.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=>ke.mergeObjectSync(n,l)):ke.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return R.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:R.errToObj(e).message??o}:{message:o}}}:{}})}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:$.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 rn(this)}partial(e){let r={};for(let n of F.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.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 i=this.shape[n];for(;i instanceof Le;)i=i._def.innerType;r[n]=i}return new t({...this._def,shape:()=>r})}keyof(){return ud(F.objectKeys(this.shape))}};Ne.create=(t,e)=>new Ne({shape:()=>t,unknownKeys:"strip",catchall:Fe.create(),typeName:$.ZodObject,...D(e)});Ne.strictCreate=(t,e)=>new Ne({shape:()=>t,unknownKeys:"strict",catchall:Fe.create(),typeName:$.ZodObject,...D(e)});Ne.lazycreate=(t,e)=>new Ne({shape:t,unknownKeys:"strip",catchall:Fe.create(),typeName:$.ZodObject,...D(e)});var Wt=class extends z{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new Oe(a.ctx.common.issues));return E(r,{code:x.invalid_union,unionErrors:s}),P}if(r.common.async)return Promise.all(n.map(async i=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(o);{let i,s=[];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"&&!i&&(i={result:u,ctx:l}),l.common.issues.length&&s.push(l.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(c=>new Oe(c));return E(r,{code:x.invalid_union,unionErrors:a}),P}}get options(){return this._def.options}};Wt.create=(t,e)=>new Wt({options:t,typeName:$.ZodUnion,...D(e)});var St=t=>t instanceof Ht?St(t.schema):t instanceof De?St(t.innerType()):t instanceof Jt?[t.value]:t instanceof Gt?t.options:t instanceof Zt?F.objectValues(t.enum):t instanceof Yt?St(t._def.innerType):t instanceof Ft?[void 0]:t instanceof Vt?[null]:t instanceof Le?[void 0,...St(t.unwrap())]:t instanceof Ye?[null,...St(t.unwrap())]:t instanceof nn||t instanceof er?St(t.unwrap()):t instanceof Xt?St(t._def.innerType):[],no=class t extends z{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==T.object)return E(r,{code:x.invalid_type,expected:T.object,received:r.parsedType}),P;let n=this.discriminator,o=r.data[n],i=this.optionsMap.get(o);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(E(r,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),P)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let i of r){let s=St(i.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,i)}}return new t({typeName:$.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...D(n)})}};function Za(t,e){let r=Ge(t),n=Ge(e);if(t===e)return{valid:!0,data:t};if(r===T.object&&n===T.object){let o=F.objectKeys(e),i=F.objectKeys(t).filter(a=>o.indexOf(a)!==-1),s={...t,...e};for(let a of i){let c=Za(t[a],e[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===T.array&&n===T.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<t.length;i++){let s=t[i],a=e[i],c=Za(s,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===T.date&&n===T.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Qt=class extends z{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(i,s)=>{if(to(i)||to(s))return P;let a=Za(i.value,s.value);return a.valid?((ro(i)||ro(s))&&r.dirty(),{status:r.value,value:a.data}):(E(n,{code:x.invalid_intersection_types}),P)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Qt.create=(t,e,r)=>new Qt({left:t,right:e,typeName:$.ZodIntersection,...D(r)});var Ze=class t extends z{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==T.array)return E(n,{code:x.invalid_type,expected:T.array,received:n.parsedType}),P;if(n.data.length<this._def.items.length)return E(n,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;!this._def.rest&&n.data.length>this._def.items.length&&(E(n,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Be(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(i).then(s=>ke.mergeArray(r,s)):ke.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ze.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ze({items:t,typeName:$.ZodTuple,rest:null,...D(e)})};var oo=class t extends z{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!==T.object)return E(n,{code:x.invalid_type,expected:T.object,received:n.parsedType}),P;let o=[],i=this._def.keyType,s=this._def.valueType;for(let a in n.data)o.push({key:i._parse(new Be(n,a,n.path,a)),value:s._parse(new Be(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ke.mergeObjectAsync(r,o):ke.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof z?new t({keyType:e,valueType:r,typeName:$.ZodRecord,...D(n)}):new t({keyType:Et.create(),valueType:e,typeName:$.ZodRecord,...D(r)})}},gr=class extends z{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!==T.map)return E(n,{code:x.invalid_type,expected:T.map,received:n.parsedType}),P;let o=this._def.keyType,i=this._def.valueType,s=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new Be(n,a,n.path,[l,"key"])),value:i._parse(new Be(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return P;(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 s){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return P;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};gr.create=(t,e,r)=>new gr({valueType:e,keyType:t,typeName:$.ZodMap,...D(r)});var yr=class t extends z{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==T.set)return E(n,{code:x.invalid_type,expected:T.set,received:n.parsedType}),P;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(E(n,{code:x.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(E(n,{code:x.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let i=this._def.valueType;function s(c){let l=new Set;for(let u of c){if(u.status==="aborted")return P;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>i._parse(new Be(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:R.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:R.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};yr.create=(t,e)=>new yr({valueType:t,minSize:null,maxSize:null,typeName:$.ZodSet,...D(e)});var io=class t extends z{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==T.function)return E(r,{code:x.invalid_type,expected:T.function,received:r.parsedType}),P;function n(a,c){return tn({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fr(),lt].filter(l=>!!l),issueData:{code:x.invalid_arguments,argumentsError:c}})}function o(a,c){return tn({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fr(),lt].filter(l=>!!l),issueData:{code:x.invalid_return_type,returnTypeError:c}})}let i={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof Tt){let a=this;return Ie(async function(...c){let l=new Oe([]),u=await a._def.args.parseAsync(c,i).catch(h=>{throw l.addIssue(n(c,h)),l}),d=await Reflect.apply(s,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(h=>{throw l.addIssue(o(d,h)),l})})}else{let a=this;return Ie(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new Oe([n(c,l.error)]);let u=Reflect.apply(s,this,l.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new Oe([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Ze.create(e).rest(ut.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||Ze.create([]).rest(ut.create()),returns:r||ut.create(),typeName:$.ZodFunction,...D(n)})}},Ht=class extends z{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})}};Ht.create=(t,e)=>new Ht({getter:t,typeName:$.ZodLazy,...D(e)});var Jt=class extends z{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return E(r,{received:r.data,code:x.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:e.data}}get value(){return this._def.value}};Jt.create=(t,e)=>new Jt({value:t,typeName:$.ZodLiteral,...D(e)});function ud(t,e){return new Gt({values:t,typeName:$.ZodEnum,...D(e)})}var Gt=class t extends z{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{expected:F.joinValues(n),received:r.parsedType,code:x.invalid_type}),P}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 E(r,{received:r.data,code:x.invalid_enum_value,options:n}),P}return Ie(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})}};Gt.create=ud;var Zt=class extends z{_parse(e){let r=F.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==T.string&&n.parsedType!==T.number){let o=F.objectValues(r);return E(n,{expected:F.joinValues(o),received:n.parsedType,code:x.invalid_type}),P}if(this._cache||(this._cache=new Set(F.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=F.objectValues(r);return E(n,{received:n.data,code:x.invalid_enum_value,options:o}),P}return Ie(e.data)}get enum(){return this._def.values}};Zt.create=(t,e)=>new Zt({values:t,typeName:$.ZodNativeEnum,...D(e)});var Tt=class extends z{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==T.promise&&r.common.async===!1)return E(r,{code:x.invalid_type,expected:T.promise,received:r.parsedType}),P;let n=r.parsedType===T.promise?r.data:Promise.resolve(r.data);return Ie(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Tt.create=(t,e)=>new Tt({type:t,typeName:$.ZodPromise,...D(e)});var De=class extends z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:s=>{E(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let s=o.transform(n.data,i);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return P;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?P:c.status==="dirty"?Dt(c.value):r.value==="dirty"?Dt(c.value):c});{if(r.value==="aborted")return P;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?P:a.status==="dirty"?Dt(a.value):r.value==="dirty"?Dt(a.value):a}}if(o.type==="refinement"){let s=a=>{let c=o.refinement(a,i);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"?P:(a.status==="dirty"&&r.dirty(),s(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"?P:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!It(s))return P;let a=o.transform(s.value,i);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(s=>It(s)?Promise.resolve(o.transform(s.value,i)).then(a=>({status:r.value,value:a})):P);F.assertNever(o)}};De.create=(t,e,r)=>new De({schema:t,typeName:$.ZodEffects,effect:e,...D(r)});De.createWithPreprocess=(t,e,r)=>new De({schema:e,effect:{type:"preprocess",transform:t},typeName:$.ZodEffects,...D(r)});var Le=class extends z{_parse(e){return this._getType(e)===T.undefined?Ie(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Le.create=(t,e)=>new Le({innerType:t,typeName:$.ZodOptional,...D(e)});var Ye=class extends z{_parse(e){return this._getType(e)===T.null?Ie(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ye.create=(t,e)=>new Ye({innerType:t,typeName:$.ZodNullable,...D(e)});var Yt=class extends z{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===T.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Yt.create=(t,e)=>new Yt({innerType:t,typeName:$.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...D(e)});var Xt=class extends z{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return pr(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Oe(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Oe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Xt.create=(t,e)=>new Xt({innerType:t,typeName:$.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...D(e)});var br=class extends z{_parse(e){if(this._getType(e)!==T.nan){let n=this._getOrReturnCtx(e);return E(n,{code:x.invalid_type,expected:T.nan,received:n.parsedType}),P}return{status:"valid",value:e.data}}};br.create=t=>new br({typeName:$.ZodNaN,...D(t)});var dd=Symbol("zod_brand"),nn=class extends z{_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}},on=class t extends z{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?P:i.status==="dirty"?(r.dirty(),Dt(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?P:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:$.ZodPipeline})}},er=class extends z{_parse(e){let r=this._def.innerType._parse(e),n=o=>(It(o)&&(o.value=Object.freeze(o.value)),o);return pr(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};er.create=(t,e)=>new er({innerType:t,typeName:$.ZodReadonly,...D(e)});function ad(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Xa(t,e={},r){return t?jt.create().superRefine((n,o)=>{let i=t(n);if(i instanceof Promise)return i.then(s=>{if(!s){let a=ad(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!i){let s=ad(e,n),a=s.fatal??r??!0;o.addIssue({code:"custom",...s,fatal:a})}}):jt.create()}var fd={object:Ne.lazycreate},$;(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"})($||($={}));var pd=(t,e={message:`Input not instance of ${t.name}`})=>Xa(r=>r instanceof t,e),N=Et.create,pe=Mt.create,md=br.create,hd=Kt.create,ec=Ut.create,gd=Bt.create,yd=mr.create,bd=Ft.create,wd=Vt.create,vd=jt.create,sn=ut.create,xd=Fe.create,kd=hr.create,ze=dt.create,B=Ne.create,_d=Ne.strictCreate,an=Wt.create,cn=no.create,Id=Qt.create,Sd=Ze.create,wr=oo.create,Ed=gr.create,jd=yr.create,Td=io.create,Ad=Ht.create,Se=Jt.create,Ve=Gt.create,Rd=Zt.create,Od=Tt.create,Nd=De.create,Pd=Le.create,Cd=Ye.create,$d=De.createWithPreprocess,zd=on.create,qd=()=>N().optional(),Ld=()=>pe().optional(),Dd=()=>ec().optional(),Md={string:(t=>Et.create({...t,coerce:!0})),number:(t=>Mt.create({...t,coerce:!0})),boolean:(t=>Ut.create({...t,coerce:!0})),bigint:(t=>Kt.create({...t,coerce:!0})),date:(t=>Bt.create({...t,coerce:!0}))};var Kd=P;var Xh=j;var rc=class tc extends Ja{openAPIRegistry;defaultHook;constructor(e){super(e),this.openAPIRegistry=new pi,this.defaultHook=e?.defaultHook}openapi=({middleware:e,...r},n,o=this.defaultHook)=>{this.openAPIRegistry.registerPath(r);let i=[];if(r.request?.query){let c=ur("query",r.request.query,o);i.push(c)}if(r.request?.params){let c=ur("param",r.request.params,o);i.push(c)}if(r.request?.headers){let c=ur("header",r.request.headers,o);i.push(c)}if(r.request?.cookies){let c=ur("cookie",r.request.cookies,o);i.push(c)}let s=r.request?.body?.content;if(s)for(let c of Object.keys(s)){if(!s[c])continue;let l=s[c].schema;if(l instanceof z){if(Bd(c)){let u=ur("json",l,o);if(r.request?.body?.required)i.push(u);else{let d=async(p,h)=>{if(p.req.header("content-type")&&Bd(p.req.header("content-type")))return await u(p,h);p.req.addValidatedData("json",{}),await h()};i.push(d)}}if(Fd(c)){let u=ur("form",l,o);if(r.request?.body?.required)i.push(u);else{let d=async(p,h)=>{if(p.req.header("content-type")&&Fd(p.req.header("content-type")))return await u(p,h);p.req.addValidatedData("form",{}),await h()};i.push(d)}}}}let a=e?Array.isArray(e)?e:[e]:[];return this.on([r.method],r.path.replaceAll(/\/{(.+?)}/g,"/:$1"),...a,...i,n),this};getOpenAPIDocument=e=>{let n=new hi(this.openAPIRegistry.definitions).generateDocument(e);return this._basePath?Ud(n,this._basePath):n};getOpenAPI31Document=e=>{let n=new gi(this.openAPIRegistry.definitions).generateDocument(e);return this._basePath?Ud(n,this._basePath):n};doc=(e,r)=>this.get(e,n=>{let o=typeof r=="function"?r(n):r;try{let i=this.getOpenAPIDocument(o);return n.json(i)}catch(i){return n.json(i,500)}});doc31=(e,r)=>this.get(e,n=>{let o=typeof r=="function"?r(n):r;try{let i=this.getOpenAPI31Document(o);return n.json(i)}catch(i){return n.json(i,500)}});route(e,r){let n=e.replaceAll(/:([^\/]+)/g,"{$1}");return super.route(e,r),r instanceof tc?(r.openAPIRegistry.definitions.forEach(o=>{switch(o.type){case"component":return this.openAPIRegistry.registerComponent(o.componentType,o.name,o.component);case"route":return this.openAPIRegistry.registerPath({...o.route,path:Ue(n,o.route.path)});case"webhook":return this.openAPIRegistry.registerWebhook({...o.webhook,path:Ue(n,o.webhook.path)});case"schema":return this.openAPIRegistry.register(o.schema._def.openapi._internal.refId,o.schema);case"parameter":return this.openAPIRegistry.registerParameter(o.schema._def.openapi._internal.refId,o.schema);default:{let i=o;throw new Error(`Unknown registry type: ${i}`)}}}),this):this}basePath(e){return new tc({...super.basePath(e),defaultHook:this.defaultHook})}},Vd=t=>{let e={...t,getRoutingPath(){return t.path.replaceAll(/\/{(.+?)}/g,"/:$1")}};return Object.defineProperty(e,"getRoutingPath",{enumerable:!1})};yi(j);function Ud(t,e){let r={};return Object.keys(t.paths).forEach(n=>{r[Ue(e,n)]=t.paths[n]}),{...t,paths:r}}function Bd(t){return/^application\/([a-z-\.]+\+)?json/.test(t)}function Fd(t){return t.startsWith("multipart/form-data")||t.startsWith("application/x-www-form-urlencoded")}var so=32;function Wd(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)&&!Qd(r)&&typeof n=="string"&&n.length<=128))}function Qd(t){return/token|password|secret|authorization|cookie|headers|body|sql|params/iu.test(t)}function Hd(t){return t?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,Me(r,128)])):void 0}function nc(t){let e=Object.entries(t??{}),r=e.slice(0,16).filter(([n,o])=>/^[a-zA-Z][a-zA-Z0-9_.-]{0,47}$/u.test(n)&&!Qd(n)&&(typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o))).map(([n,o])=>[n,typeof o=="string"?Me(o,128):o]);return{values:Object.fromEntries(r),dropped:e.length-r.length}}function Jd(t){try{if(!(t instanceof Error))return{name:"NonError",message:typeof t=="string"?Me(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"?Me(r,2048):"",stack:typeof n=="string"?Me(n,16384):null}}catch{return{name:"Error",message:"[unreadable exception]",stack:null}}}function ji(t,e){let r=new Set;for(let n=0;n<10&&t&&typeof t=="object"&&!r.has(t);n++){r.add(t);let o=e.errorSpans.get(t),i=e.safeSqlErrors.get(t);if(o||i)return{spanId:o,safeSqlError:i};try{t=Object.getOwnPropertyDescriptor(t,"cause")?.value}catch{break}}return null}import{AsyncLocalStorage as eg}from"node:async_hooks";var vr=new eg,tg=100,rg=20;async function ng(t,e,r){let n=vr.getStore();if(!n||n.session.closed)return{status:"unavailable",reason:"outside_request"};let o=n.session;if(!o.provider)return{status:"unavailable",reason:"not_configured"};let i=o.source();if(!i)return{status:"unavailable",reason:"source_unavailable"};if(!Wd(e))return{status:"rejected",reason:"invalid_context"};let s=t&&typeof t=="object"?t:null,a=s?o.errors.get(s):void 0;if(a)return a;if(o.errorCount>=rg){try{o.provider.recordDroppedError?.(i)}catch{}return{status:"rejected",reason:"limit_exceeded"}}o.errorCount+=1;let c={schemaVersion:1,kind:"error",eventId:crypto.randomUUID(),occurredAt:new Date().toISOString(),source:{...i,routeTemplate:o.routeTemplate},mechanism:r,error:ji(t,o)?.safeSqlError??Jd(t),context:{...e,tags:Hd(e.tags)},traceId:o.traceId,spanId:o.traceId?ji(t,o)?.spanId??n.parentSpanId:null},l=(async()=>{try{let u=await o.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 s&&o.errors.set(s,l),o.pendingErrors.add(l),l}async function ao(t,e,r,n){try{return await og(t,e,r,n)}catch(o){let i=vr.getStore();throw t==="sql"&&i&&!i.session.closed&&o&&typeof o=="object"&&i.session.safeSqlErrors.set(o,ig()),o}}async function og(t,e,r,n){let o=vr.getStore();if(!o||o.session.closed||!o.session.traceId)return await r();let i=o.session;if(typeof e!="string"||!/^[\p{L}][\p{L}\p{N}_. -]{0,95}$/u.test(e)||i.spans.length>=tg)return i.droppedSpans+=1,await r();let s=nc(n?.attributes),a={spanId:Xd(),parentSpanId:o.parentSpanId,name:e,kind:t,startedAt:new Date().toISOString(),durationMs:null,state:"running",status:"ok",attributes:s.values,droppedAttributes:s.dropped};i.spans.push(a);let c=performance.now();return vr.run({session:i,parentSpanId:a.spanId},async()=>{try{let l=await r();if(n?.result){let u=n.result(l),d=nc({...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"&&!i.errorSpans.has(l)){let u=ji(l,i);i.errorSpans.set(l,u?.spanId??a.spanId),u?.safeSqlError&&i.safeSqlErrors.set(l,u.safeSqlError)}throw l}finally{a.durationMs=Math.max(0,performance.now()-c),a.state="finished"}})}function Zd(t){let e=vr.getStore();e&&(e.session.routeTemplate=t)}function Yd(t,e){let r=vr.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>=so){let o=r.session.spans.find(i=>i.spanId===r.parentSpanId);return o&&(o.attributes={...o.attributes,"trace.propagation":"hop_limit"}),null}return{...r.session.propagation,parentSpanId:r.parentSpanId,hop:r.session.propagation.hop+1}}async function oc(t,e){let r=t.background,n=t.incomingTrace?.status==="inherited"||t.incomingTrace?.status==="gateway"?t.incomingTrace.context:null,o=(t.incomingTrace?.status==="inherited"?t.incomingTrace.context.sampled:void 0)??!!(t.provider&&Math.random()<t.provider.traceSampleRate),i=!!(t.provider&&o),s=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:o,hop:n.hop}:t.provider&&t.source()?{traceId:crypto.randomUUID().replaceAll("-",""),sampled:o,hop:0}:null,c={spanId:a?Xd():"",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:i?a?.traceId??null:null,propagation:a,sampling:s,spans:i?[c]:[],droppedSpans:0,errorCount:0,errors:new WeakMap,pendingErrors:new Set,errorSpans:new WeakMap,safeSqlErrors:new WeakMap,closed:!1},u=performance.now();await Jc(()=>vr.run({session:l,parentSpanId:c.spanId},async()=>{let d,p=!1;try{await e()}catch(h){throw d=h,p=!0,h}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 h=l.source(),w=l.traceId&&h?{schemaVersion:1,kind:"trace",traceId:l.traceId,source:{...h,routeTemplate:l.routeTemplate},sampling:l.sampling,spans:l.spans.map(C=>({...C,attributes:{...C.attributes}})),droppedSpans:l.droppedSpans}:null,b=p?d:t.error(),_=p||b!=null?ng(b,{},"unhandled"):null;l.closed=!0;let k=(async()=>{let C=await Promise.all([...l.pendingErrors,..._?[_]:[]]),q=new Set;for(let O of C){let X="eventId"in O?O.eventId:O.status;O.status!=="emitted"&&!q.has(X)&&(q.add(X),Gd(t.requestId,O.status))}if(w&&l.provider)try{await l.provider.acceptTrace(w)}catch{Gd(t.requestId,"failed")}})();Gc(k)||(t.defer?t.defer(k):await k)}}),t.defer)}function Gd(t,e){console.warn(JSON.stringify({event:"runtime.telemetry_delivery",requestId:t,status:e}))}function ic(t,e,r="runtime.http_error"){let n=["Error","TypeError","RangeError","SyntaxError","ReferenceError","URIError","EvalError","AggregateError"],o="Error";try{if(t instanceof Error){let i=t.name;n.includes(i)&&(o=i)}}catch{}console.error(JSON.stringify({event:r,requestId:e,errorName:o}))}function Xd(){return crypto.randomUUID().replaceAll("-","").slice(0,16)}function ig(){let t="Database operation failed.";try{let e=new Error(t).stack;return{name:"DatabaseError",message:t,stack:typeof e=="string"?Me(e,16384):null}}catch{return{name:"DatabaseError",message:t,stack:null}}}function ef(t){return{execute:e=>{let r=e.type,n="statements"in e?e.statements.length:r==="query"?1:0;return ao("sql",`SQL ${r}`,()=>t.execute(e),{attributes:{"db.system":"sqlite","db.operation":r,"db.statement_count":n}})}}}function tf(t){return{execute:e=>ao("sql","SQL query",()=>t.execute(e),{attributes:{"db.system":"postgresql","db.operation":"query","db.statement_count":1}}),...t.transactionBatch?{transactionBatch:e=>ao("sql","SQL transactionBatch",()=>t.transactionBatch(e),{attributes:{"db.system":"postgresql","db.operation":"transactionBatch","db.statement_count":e.length}})}:{}}}function sc(t,e,r,n){return ao("rpc",r?"RPC system":"RPC extension",n,{attributes:{"rpc.system":"kuafu","rpc.target":t,"http.request.method":e},result:o=>({error:!o||o.status>=400,attributes:o?{"http.status_code":o.status}:{}})})}var rf=Symbol.for("@kuafucloud/extension-kit:object-storage-contexts"),co=globalThis[rf]??(globalThis[rf]=new WeakMap);function nf(t,e){let r=co.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 of(t,e){return co.set(t,{scope:Object.freeze({...e.scope}),bindings:e.bindings??{},readRegion:e.readRegion,homeRegion:e.homeRegion}),()=>{co.delete(t)}}function Ti(t,e,r){let n=co.get(t);if(!n)throw new W("storage.outside_request");let o=r??n.readRegion();if(!Re(o))throw new W("storage.region_unavailable");let s=(n.config??=Ui(n.bindings[Ki],n.scope)).regions[o]?.[e];if(!s)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=vo({service:a,...s,extensionId:n.scope.extensionId}),l=()=>{if(co.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 ac=N().regex(/^[a-z][a-z0-9-]{0,62}$/u),ln=B({projectId:N(),projectEnvKey:N(),extensionId:N(),region:Ve(["cn","global"]),collectionId:ac,objectId:N().uuid()}),sf=B({ref:ln,ownerId:N().nullable(),size:pe(),contentType:N(),createdAt:pe()}),af=B({url:N(),method:Ve(["GET","HEAD","PUT","POST","DELETE"]),headers:wr(N()),expiresAt:pe(),digestMetadataHeader:N().optional()}),sg=an([sf,af,B({ref:ln,request:af}),B({objects:ze(sf),cursor:N().nullable()}),B({deleted:Se(!0)})]),lo=B({code:N(),message:N()}),ag=cn("action",[B({action:Se("createUpload"),collectionId:ac,size:pe().int().min(0),contentType:N(),input:sn().optional()}),B({action:Se("resumeUpload"),ref:ln}),B({action:Se("completeUpload"),ref:ln}),B({action:Se("createDownload"),ref:ln}),B({action:Se("delete"),ref:ln}),B({action:Se("list"),collectionId:ac,cursor:N().optional(),limit:pe().int().min(1).max(100).optional()})]);function lf(t){return be(de({method:"POST",path:"/_storage/objects",accessLevel:"private",authScope:"account",request:{body:ag},responses:{200:{schema:B({data:sg})},400:{schema:lo},403:{schema:lo},404:{schema:lo},409:{schema:lo},503:{schema:lo}}}),async(e,{body:r})=>{let n="ref"in r?r.ref.collectionId:r.collectionId,o=t.find(s=>s.id===n);if(!o)return e.json({code:"storage.collection_not_found",message:"\u96C6\u5408\u4E0D\u5B58\u5728\u3002"},404);let i=e.get("cloudStorage").collection(o);e.header("cache-control","private, no-store");try{switch(r.action){case"createUpload":{let s=await i.createUpload(r);return e.json({data:{ref:s.object.ref,request:s.request}},200)}case"resumeUpload":{let s=await i.resumeUpload(r.ref);return e.json({data:{ref:s.object.ref,request:s.request}},200)}case"completeUpload":return e.json({data:cf(await i.completeUpload(r.ref))},200);case"createDownload":return e.json({data:await i.createDownload(r.ref)},200);case"delete":return await i.delete(r.ref),e.json({data:{deleted:!0}},200);case"list":{let s=await i.list(r);return e.json({data:{objects:s.objects.map(cf),cursor:s.cursor}},200)}}}catch(s){if(!(s instanceof W))throw s;return s.code==="storage.forbidden"||s.code==="storage.object_scope_mismatch"?e.json({code:s.code,message:"\u65E0\u6743\u64CD\u4F5C\u6B64\u6587\u4EF6\u3002"},403):s.code==="storage.object_not_found"?e.json({code:s.code,message:"\u6587\u4EF6\u4E0D\u5B58\u5728\u3002"},404):["storage.upload_invalid","storage.request_invalid"].includes(s.code)?e.json({code:s.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(s.code)?e.json({code:s.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 cf(t){return{ref:t.ref,ownerId:t.ownerId,size:t.size,contentType:t.contentType,createdAt:t.createdAt}}import{AsyncLocalStorage as cg}from"node:async_hooks";var uf=new cg;function ft(t,e){return uf.run(t,e)}function At(){return uf.getStore()}var uo={internalOnly:!0,auth:"signed",allowedCallerExtensions:["system"],allowCrossProject:!1,allowCrossEnvironment:!1},Ee=B({code:N(),message:N()});function df(t){let e=be(de({method:"GET",path:"/_internal/cloud-storage/catalog",accessLevel:"public",internalPolicy:uo,responses:{200:{schema:B({data:B({collections:ze(B({id:N(),upload:B({maxBytes:pe(),contentTypes:ze(N())}),operations:ze(N())})),usage:ze(B({region:Ve(["cn","global"]),collectionId:N(),state:Ve(["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(de({method:"POST",path:"/_internal/cloud-storage/objects/list",accessLevel:"public",internalPolicy:uo,request:{body:B({collectionId:N(),region:Ve(["cn","global"]),adminId:N().min(1),roles:ze(N()),cursor:N().optional(),limit:pe().int().min(1).max(100).default(50)})},responses:{200:{schema:B({data:B({objects:ze(B({id:N(),ownerId:N().nullable(),size:pe(),contentType:N(),createdAt:pe()})),cursor:N().nullable()})})},400:{schema:Ee},403:{schema:Ee},404:{schema:Ee},503:{schema:Ee}}}),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(!Ai(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 ft({...At(),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(de({method:"POST",path:"/_internal/cloud-storage/objects/delete",accessLevel:"public",internalPolicy:uo,request:{body:B({collectionId:N(),objectId:N().uuid(),region:Ve(["cn","global"]),adminId:N().min(1),roles:ze(N())})},responses:{200:{schema:B({data:B({deleted:Se(!0)})})},400:{schema:Ee},403:{schema:Ee},404:{schema:Ee},503:{schema:Ee}}}),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(!Ai(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 ft({...At(),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)}}),o=be(de({method:"POST",path:"/_internal/cloud-storage/objects/download",accessLevel:"public",internalPolicy:uo,request:{body:B({collectionId:N(),objectId:N().uuid(),region:Ve(["cn","global"]),adminId:N().min(1),roles:ze(N())})},responses:{200:{schema:B({data:B({request:B({url:N(),method:Se("GET"),headers:wr(N(),N()),expiresAt:pe()})})})},400:{schema:Ee},403:{schema:Ee},404:{schema:Ee},503:{schema:Ee}}}),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(!Ai(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 ft({...At(),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)}}),i=B({collectionId:N(),region:Ve(["cn","global"]),adminId:N().min(1),roles:ze(N())}),s=be(de({method:"POST",path:"/_internal/cloud-storage/objects/upload",accessLevel:"public",internalPolicy:uo,request:{body:cn("action",[i.extend({action:Se("create"),size:pe().int().min(0),contentType:N(),input:sn().optional()}),i.extend({action:Se("resume"),objectId:N().uuid()}),i.extend({action:Se("complete"),objectId:N().uuid()})])},responses:{200:{schema:B({data:an([B({objectId:N().uuid(),request:B({url:N(),method:Se("PUT"),headers:wr(N(),N()),expiresAt:pe()})}),B({objectId:N().uuid(),size:pe(),contentType:N()})])})},400:{schema:Ee},403:{schema:Ee},404:{schema:Ee},409:{schema:Ee},503:{schema:Ee}}}),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(!Ai(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 ft({...At(),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 h=await u.completeUpload(d);return a.json({data:{objectId:h.ref.objectId,size:h.size,contentType:h.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,o,s,lf(t)]}function Ai(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 lg=new WeakSet;function ff(t){return lg.has(t)}function fo({actor:t,object:e}){return t.kind==="account"&&e.ownerId===t.id}var ug=Object.freeze({ownerPrivate(){return{create:fo,read:fo,delete:fo,list:({actor:t})=>t.kind==="account"?{ownerId:t.id}:null}},ownerWritePublicRead(){return{create:fo,read:()=>!0,delete:fo}}});function xr(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 o of Object.values(n))r(o);Object.freeze(n)}return n};return r(JSON.parse(e))}var cc=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u;function mf(t,e){let r=new Map;for(let n of e)(!ff(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(o=>typeof n.permissions[o]=="function")})),collection(n){r.get(n.id)!==n&&te("collection_not_declared");let o=()=>t.current(),i=async(d,p)=>{let{actor:h}=o(),w=n.permissions[d];(!w||await w(Object.freeze({actor:Object.freeze({...h}),object:p,context:t.context()}))!==!0)&&te("forbidden"),o()},s=async d=>{let{scope:p}=o();(!d||Object.keys(p).some(w=>d[w]!==p[w])||d.collectionId!==n.id||!cc.test(d.objectId))&&te("object_scope_mismatch");let h=await t.directory().get(p.region,n.id,d.objectId);return h||te("object_not_found"),h},a=async d=>{let p=await s(d);return await i("read",p),p.state!=="ready"&&te("object_not_ready"),p},c=async d=>{let{scope:p,actor:h}=o();(!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=xr({ref:{...p,collectionId:n.id,objectId:t.createId()},ownerId:h.kind==="account"?h.id:null,binding:w,size:d.size,contentType:d.contentType,createdAt:t.now(),state:"uploading",etag:null});return cc.test(b.ref.objectId)||te("object_identity_invalid"),await i("create",b),b},l=d=>t.sign(d.map(p=>({key:kr(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),h=await u(p);return await t.directory().insert(p),h},async createUploads(d){(!d.length||d.length>64)&&te("upload_invalid");let p=[];for(let w of d)p.push(await c(w));let h=await l(p);return h.length!==p.length&&te("operation_unavailable"),await t.directory().insertBatch(p),p.map(({ref:w},b)=>({ref:w,request:h[b]}))},async resumeUpload(d){let p=await s(d);return await i("create",p),p.state!=="uploading"&&te("object_not_uploading"),u(p)},async completeUpload(d){let p=await s(d);if(await i("create",p),p.state==="ready")return p;p.state!=="uploading"&&te("object_not_uploading");let h=await t.storage().head(kr(p));if(h||te("upload_incomplete"),(h.size!==p.size||h.contentType!==p.contentType||!h.etag)&&te("object_receipt_invalid"),!await t.directory().transition(p,"ready",h.etag)){let b=await s(d);if(b.state==="ready"&&b.etag===h.etag)return b;te("object_state_conflict")}return xr({...p,state:"ready",etag:h.etag})},async put(d){let p=typeof d.body=="string"?new TextEncoder().encode(d.body):d.body;p instanceof Uint8Array||te("upload_invalid");let h=await c({...d,size:p.byteLength}),w=t.directory(),b=t.storage();await w.insert(h);let _=await b.put({key:kr(h),body:p,size:p.byteLength,contentType:d.contentType,condition:{kind:"if-absent"},signal:d.signal});return _.status!=="written"&&te("object_conflict"),(_.object.key!==kr(h)||_.object.size!==h.size||_.object.contentType!==h.contentType||!_.object.etag)&&te("object_receipt_invalid"),await w.transition(h,"ready",_.object.etag)||te("object_state_conflict"),xr({...h,state:"ready",etag:_.object.etag})},head:a,async createDownload(d){let p=await a(d),[h]=await t.sign([{key:kr(p),method:"GET"}],t.now()+5*6e4);return h},async get(d,p){let h=await a(d),w=await t.storage().get(kr(h),p);return w||te("object_not_found"),(w.object.etag!==h.etag||w.object.size!==h.size||w.object.contentType!==h.contentType)&&(await w.body.cancel(),te("object_changed")),{object:h,body:w.body}},async delete(d){let p=await s(d);if(await i("delete",p),p.state==="deleted")return;let h=t.directory();p.state==="ready"&&(await h.transition(p,"deleting")||te("object_state_conflict"),p=xr({...p,state:"deleting"})),p.state!=="deleting"&&te("object_not_ready"),await t.storage().delete(kr(p)),await h.transition(p,"deleted")||(await h.get(p.ref.region,p.ref.collectionId,p.ref.objectId))?.state!=="deleted"&&te("object_state_conflict")},async list(d={}){let{scope:p,actor:h}=o(),w=n.permissions.list,b=w?await w(Object.freeze({actor:Object.freeze({...h}),context:t.context()})):null;o(),dg(b)||te("forbidden");let _=d.limit??50;(!Number.isSafeInteger(_)||_<1||_>100||d.cursor!==void 0&&!cc.test(d.cursor))&&te("request_invalid");let k=await t.directory().list({region:p.region,collectionId:n.id,scope:b,after:d.cursor??null,limit:_+1}),C=k.slice(0,_);return{objects:C,cursor:k.length>_?C.at(-1).ref.objectId:null}}})}})}function dg(t){return!!t&&Object.keys(t).length===1&&("ownerId"in t&&typeof t.ownerId=="string"&&!!t.ownerId||"all"in t&&t.all===!0)}function kr(t){return`collections/${t.ref.collectionId}/${t.ref.objectId}`}function te(t){throw new W(`storage.${t}`)}function hf(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(s,a)=>{await r();let c=await t.execute({type:"query",statement:{sql:s,params:a,method:"all"}});if(!Array.isArray(c.rows))throw new W("storage.directory_invalid");return c.rows},o=s=>{try{let a=JSON.parse(String(s.payload));if(!["uploading","ready","deleting","deleted"].includes(String(s.state))||s.etag!==null&&typeof s.etag!="string"||!a.ref||!a.ref.objectId||!Number.isSafeInteger(a.size))throw new Error;return xr({...a,state:s.state,etag:s.etag})}catch{throw new W("storage.directory_invalid")}},i=s=>({method:"run",sql:"INSERT INTO CloudStorageObject(region, collection_id, object_id, owner_id, state, etag, payload) VALUES (?,?,?,?,?,?,?)",params:[s.ref.region,s.ref.collectionId,s.ref.objectId,s.ownerId,s.state,s.etag,JSON.stringify(s)]});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(s){await r(),await t.execute({type:"query",statement:i(s)})},async insertBatch(s){await r(),await t.execute({type:"transactionBatch",statements:s.map(i)})},async get(s,a,c){let l=await n("SELECT payload, state, etag FROM CloudStorageObject WHERE region=? AND collection_id=? AND object_id=?",[s,a,c]);return l.length?o(l[0]):null},async transition(s,a,c=s.etag){return(await n("UPDATE CloudStorageObject SET state=?, etag=? WHERE region=? AND collection_id=? AND object_id=? AND state=? RETURNING object_id",[a,c,s.ref.region,s.ref.collectionId,s.ref.objectId,s.state])).length===1},async list(s){let a="ownerId"in s.scope?s.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 ?`,[s.region,s.collectionId,s.after??"",...a===null?[]:[a],s.limit])).map(o)}}}function gf(t){let e=Object.freeze({...t.scope}),r=(o=!1)=>{let i=t.readContext();if(!i||i.projectId!==Number(e.projectId)||i.projectEnvKey!==e.projectEnvKey||i.extensionId!==e.extensionId||!Re(i.regionContext?.region))throw new W("storage.outside_request");o?nf(t.context,e):Ti(t.context,"objects",i.regionContext.region);let s=i.userId&&i.authScope?{kind:i.authScope,id:i.userId}:{kind:"anonymous"};return{scope:{...e,region:i.regionContext.region},actor:s}},n;return mf({current:r,directory(){if(r(!0),!n){let o=Jr(t.bindings);if(!o)throw new W("storage.directory_not_configured");let i=_t({projectId:Number(e.projectId),projectEnvKey:e.projectEnvKey,extensionId:e.extensionId,databaseName:"cloud-storage-v1"});n=hf(Mn(o.get(o.idFromName(i))))}return n},storage(){return Ti(t.context,"objects",r().scope.region)},sign(o,i){return Ti(t.context,"objects",r().scope.region).sign(o,i)},context(){return r(),t.context},createId:wu,now:Date.now},t.collections)}function _r(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}function fg(t){let e=t.replaceAll("-","+").replaceAll("_","/").padEnd(Math.ceil(t.length/4)*4,"="),r=atob(e),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.charCodeAt(o);return n}function yf(t){let e=new TextDecoder,r=fg(t);return JSON.parse(e.decode(r))}function lc(){let t=new Uint8Array(16);return crypto.getRandomValues(t),_r(t)}var pg=300*1e3;async function Ir(t){let e=t.requestId??lc(),r=t.timestamp??String(Date.now()),n=t.nonce??lc(),o=await wf(t.bodyText??""),i=await bf({method:t.method,path:t.path,timestamp:r,nonce:n,contentSha256:o,caller:t.caller,secret:t.secret});return{"x-request-id":e,"x-internal-caller-project-id":Hr(t.caller.projectId),"x-internal-caller-project-env-key":qt(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":o,"x-internal-signature":i}}async function bf(t){return await yg(gg({method:t.method,path:t.path,timestamp:t.timestamp,nonce:t.nonce,contentSha256:t.contentSha256,caller:t.caller}),t.secret)}async function Ri(t,e){let r=mg(t),n=t.req.header("x-internal-timestamp"),o=t.req.header("x-internal-nonce"),i=t.req.header("x-internal-content-sha256"),s=t.req.header("x-internal-signature"),a=t.req.header("x-internal-source-request-id")??t.req.header("x-request-id")??"";if(!r||!n||!o||!i||!s)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??pg;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 wf(u)!==i)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),h=`${p.pathname}${p.search}`;return await bf({method:t.req.raw.method,path:h,timestamp:n,nonce:o,contentSha256:i,caller:r,secret:e.secret})!==s?{ok:!1,response:t.json({code:"runtime.internal_unauthorized",message:"Invalid internal request signature."},401)}:e.allowedCallers?.length&&!e.allowedCallers.some(b=>hg(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 mg(t){let e=ce(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 hg(t,e){return!(e.projectId&&e.projectId!==t.projectId||e.projectEnvKey&&Y(e.projectEnvKey)!==t.projectEnvKey||e.extensionId&&e.extensionId!==t.extensionId)}function gg(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 wf(t){let e=new TextEncoder,r=await crypto.subtle.digest("SHA-256",e.encode(t));return _r(new Uint8Array(r))}async function yg(t,e){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",n,r.encode(t));return _r(new Uint8Array(o))}var vf="traceparent",xf="x-kuafu-trace-hop",Oi="x-kuafu-trace-signature";async function uc(t){let{request:e,source:r}=t,n=e.headers,o=t.env&&typeof t.env=="object"?t.env:{},i=o.INTERNAL_API_SIGNING_KEY,s=o.PLATFORM_GATEWAY_INGRESS_TOKEN;if(n.has("x-platform-trace-id")||n.has("x-platform-upstream-span-id")){if(!r||typeof s!="string"||!s||n.get("x-kuafu-gateway-ingress-token")!==s)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")??"",_=n.get("x-platform-upstream-span-id")??"";return!/^(?!0+$)[a-f0-9]{32}$/u.test(b)||!/^(?!0+$)[a-f0-9]{16}$/u.test(_)||!/^gw_[0-9a-f-]{36}$/u.test(n.get("x-platform-request-id")??"")?{status:"rejected_format"}:{status:"gateway",context:{traceId:b,parentSpanId:_,hop:0}}}if(![vf,xf,Oi].some(b=>n.has(b)))return{status:"none"};if(!r||typeof i!="string"||!i||typeof s!="string"||!s||n.get("x-kuafu-gateway-ingress-token")!==s||!n.has(Oi))return{status:"rejected_untrusted"};let a=n.get(vf)??"",c=n.get(xf)??"",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>so||!/^[a-zA-Z0-9_-]{43}$/u.test(n.get(Oi)??""))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 h={projectId:Number(r.projectId),projectEnvKey:r.projectEnvKey,extensionId:r.productId};if(await dc(a,c,h,n.get("x-internal-signature")??"",i)!==n.get(Oi))return{status:"rejected_signature"};try{if(!(await Ri({req:{raw:e,header:_=>n.get(_)??void 0},get:()=>{},json:(_,k)=>new Response(JSON.stringify(_),{status:k})},{secret:i})).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 dc(t,e,r,n,o){let i=new TextEncoder,s=await crypto.subtle.importKey("raw",i.encode(o),{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 _r(new Uint8Array(await crypto.subtle.sign("HMAC",s,i.encode(a))))}var bg="traceparent",wg="x-kuafu-trace-hop",vg="x-kuafu-trace-signature";async function fc(t){let e=Yd(t.caller,t.target);if(!e)return{};let r=`00-${e.traceId}-${e.parentSpanId}-${e.sampled?"01":"00"}`,n=String(e.hop),o=await dc(r,n,t.target,t.signedHeaders["x-internal-signature"],t.secret);return{[bg]:r,[wg]:n,[vg]:o}}var kf="kuafucloud_local_internal_api_signing_key",xg="x-kuafu-gateway-ingress-token";function Rt(t){let e=un(t,"INTERNAL_API_SIGNING_KEY");if(e)return e;if(!gt(t))throw new Error("INTERNAL_API_SIGNING_KEY is required in a Platform Product Worker.");return kf}function Ni(t){return un(t,"PROJECT_INTERNAL_SIGNING_KEY")||Rt(t)}function pc(t){let e=t?.RUNTIME_INTERNAL_RPC;return typeof e=="function"?e:null}function kg(t){let e=t?.PLATFORM_SYSTEM_SERVICE;return e&&typeof e=="object"&&"fetch"in e&&typeof e.fetch=="function"?e:null}function _f(t){let e=t?.PLATFORM_GATEWAY_SERVICE;return e&&typeof e=="object"&&"fetch"in e&&typeof e.fetch=="function"?e:null}function _g(t){return`https://platform-internal${Sr(t)}`}function Sr(t){return Pi("system",t)}function Pi(t,e){let r=e.startsWith("/")?e:`/${e}`;return`/api/${t}${r}`}function If(t){return Sf({...t,extensionId:"system"})}function Sf(t){return Nt({projectId:t.projectId,projectEnvKey:t.projectEnvKey,extensionId:t.extensionId},t.path)}async function Ef(t){t.signal?.throwIfAborted();let e=new Headers(t.headers);Tf(e,t.env);let r=Y(t.projectEnvKey);e.has("x-project-id")||e.set("x-project-id",Hr(t.projectId)),e.has("x-project-env-key")||e.set("x-project-env-key",qt(r)),e.has("x-platform-project-env-key")||e.set("x-platform-project-env-key",qt(r));let n=Sf({projectId:t.projectId,projectEnvKey:r,extensionId:t.extensionId,path:t.path}),o=_f(t.env);if(o)return await mc(o,{apiPath:n,method:t.method,headers:e,body:t.body,...t.signal?{signal:t.signal}:{}});let i=pc(t.env);if(i)return await i({path:n,method:t.method,headers:Object.fromEntries(e.entries()),...typeof t.body=="string"?{body:t.body}:{},...t.signal?{signal:t.signal}:{}});let s=jf(t.env,t.request);if(!s)return null;try{return await fetch(`${s}${n}`,{method:t.method,headers:e,...typeof t.body=="string"?{body:t.body}:{},...t.signal?{signal:t.signal}:{}})}catch{return null}}function Ig(t){let e=jf(t.env,t.request);return e?`${e}${If({projectId:t.projectId,projectEnvKey:t.projectEnvKey,path:t.path})}`:""}function jf(t,e){let r=un(t,"RUNTIME_INTERNAL_ORIGIN")||un(t,"PLATFORM_GATEWAY_ENDPOINT")||un(t,"KUAFUCLOUD_DEVMANAGER_ORIGIN");if(r)return Sg(r);if(e)try{let n=new URL(e.url);return Eg(n.hostname)?"":`${n.protocol}//${n.host}`}catch{}return""}function un(t,e){let r=t?.[e];return typeof r=="string"?r.trim():""}function Tf(t,e){let r=un(e,"PLATFORM_GATEWAY_INGRESS_TOKEN");r&&t.set(xg,r)}function Sg(t){return t.replace(/\/+$/u,"")}function Eg(t){return t==="platform-internal"||t==="cloud-manager.internal"}async function po(t){let e=new Headers(t.headers);Tf(e,t.env);let r=Y(t.projectEnvKey);Number.isInteger(t.projectId)&&!e.has("x-project-id")&&e.set("x-project-id",Hr(t.projectId)),e.has("x-project-env-key")||e.set("x-project-env-key",qt(r)),e.has("x-platform-project-env-key")||e.set("x-platform-project-env-key",qt(r));let n=If({projectId:t.projectId,projectEnvKey:r,path:t.path}),o=_f(t.env);if(t.preferGateway===!0){if(o)return await mc(o,{apiPath:n,method:t.method,headers:e,body:t.body});let c=pc(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 i=kg(t.env);if(i){let c=new Request(_g(t.path),{method:t.method,headers:e,...typeof t.body=="string"?{body:t.body}:{}});try{return await i.fetch(c)}catch{return null}}let s=pc(t.env);if(s)return await s({path:n,method:t.method,headers:Object.fromEntries(e.entries()),...typeof t.body=="string"?{body:t.body}:{}});if(o)return await mc(o,{apiPath:n,method:t.method,headers:e,body:t.body});let a=Ig({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 mc(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 Af(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),o=await Ir({method:t.method,path:Pi(t.target.extensionId,t.path),...n===void 0?{}:{bodyText:n},caller:t.caller,secret:t.signingSecret??Rt(t.env)}),i=e?{}:await fc({caller:t.caller,target:t.target,secret:t.signingSecret??Rt(t.env),signedHeaders:o});return await Ef({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"},...o,...i},...n===void 0?{}:{body:n}})};return e?r():sc(t.target.extensionId,t.method,!1,r)}function hc(t,e,r){if(!t||typeof t!="object"||!e.extensionId||!e.version)return null;let n=t,o=String(n.PLATFORM_PROJECT_ID??""),i=String(n.PLATFORM_PROJECT_ENV_KEY??"");return!/^\d{1,20}$/u.test(o)||!/^[a-zA-Z0-9_-]{1,64}$/u.test(i)||n.PLATFORM_EXTENSION_ID!==e.extensionId?null:{projectId:o,projectEnvKey:i,productId:e.extensionId,productRelease:e.version,runtime:"server",requestId:r,userId:null,routeTemplate:null}}function gc(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 o=Hc(e.MONITOR_SOURCE_GRANT_ID);return{traceSampleRate:n,recordDroppedError:i=>o.recordDroppedError(i),async acceptError(i){if(!o(i))throw new Error("monitor.log_not_emitted");return{eventId:i.eventId,emittedAt:new Date().toISOString()}},async acceptTrace(i){if(!o(i))throw new Error("monitor.log_not_emitted")}}}var mo=new WeakMap;function Rf(t){t&&(mo.has(t)||mo.set(t,new Map))}function yc(t,e,r){if(!t||!e||!Number.isFinite(r)||r<0)return;let n=Og(t),o=Ng(e),i=n.get(o);if(i){i.durationMs+=r,i.count+=1;return}n.set(o,{durationMs:r,count:1})}function Ag(t){if(!t)return"";let e=mo.get(t);if(!e||e.size===0)return"";let r=[];for(let[n,o]of e.entries()){let i=`${n};dur=${o.durationMs.toFixed(1)}`;o.count>1?r.push(`${i};desc="count=${o.count}"`):r.push(i)}return r.join(", ")}function Of(t,e){let r=Ag(t);r&&e.append("server-timing",r)}function Er(t){let e=t.req?.raw;return e instanceof Request?e:null}function ho(){return typeof globalThis.performance<"u"?globalThis.performance.now():Date.now()}async function Rg(t){try{return await t.run()}finally{yc(t.request,t.metricName,ho()-t.startMs)}}async function bc(t,e,r){let n=ho();return await Rg({startMs:n,request:t,metricName:e,run:r})}function Og(t){let e=mo.get(t);if(e)return e;let r=new Map;return mo.set(t,r),r}function Ng(t){return t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"_")||"metric"}var wc="/runtime/auth/verify",Nf="/runtime/setting/read",Pf="/runtime/credential/read";var Pg="accountIdentityVerifier";async function Cf(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 o=t.req.header("authorization"),i=Dg(o);if(!i)return t.json({code:"runtime.unauthenticated",message:"Authentication required."},401);let s=String(t.get("extensionId")??""),a=ce(t.get("projectId"))??Je,c=Y(t.get("projectEnvKey")),l=s==="center",u=l?Mg(i,{projectId:a,projectEnvKey:c}):{projectId:a,projectEnvKey:c},d=Er(t),p=e.accessLevel==="protected"?"protected":"private",h=e.authScope,w=await bc(d,"auth_remote",async()=>await qf({req:t.req,env:r,request:d,verificationProjectId:u.projectId,verificationProjectEnvKey:u.projectEnvKey,requestProjectId:a,requestProjectEnvKey:c,callerExtensionId:s,credential:i,accessLevel:p,authScope:h,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",yo({policy:pt(t.get("projectRegionPolicy")),accountRegion:w.data.extra?.serviceRegion})),null):t.json({code:w.error.code,message:w.error.message},w.error.status)}function $f(t,e){return async r=>await Cg(t,r,e)}function zf(t,e){t.set(Pg,e)}async function Cg(t,e,r){let n=Er({req:t.req??null}),o=ce(t.get("projectId"))??Je,i=Y(t.get("projectEnvKey")),s=String(t.get("extensionId")??""),a=await bc(n,"auth_remote",async()=>await qf({req:t.req??null,env:r,request:n,verificationProjectId:o,verificationProjectEnvKey:i,requestProjectId:o,requestProjectEnvKey:i,callerExtensionId:s,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=Lf(e),l=ce(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!==i?{ok:!1,response:t.json({code:"runtime.unauthenticated",message:"Invalid account identity token."},401)}:{ok:!0,payload:{...c,accountProjectId:l,accountProjectEnvKey:u}}}async function qf(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 Ir({method:"POST",path:Sr(wc),bodyText:r,caller:{projectId:t.requestProjectId,projectEnvKey:t.requestProjectEnvKey,extensionId:t.callerExtensionId},secret:Ni(t.env),...e?{requestId:e,sourceRequestId:e}:{}}),o=new Headers({"content-type":"application/json",...n}),i=await po({env:t.env,request:t.request,projectId:t.verificationProjectId,projectEnvKey:t.verificationProjectEnvKey,path:wc,method:"POST",headers:o,body:r});if(!i)return{ok:!1,error:{status:502,code:"runtime.internal_unavailable",message:"System auth call failed."}};let s=await zg(i);if(!i.ok){let d=dn(s?.code)||(i.status===401?"runtime.unauthenticated":"runtime.internal_error");return{ok:!1,error:{status:$g(i.status,d),code:d,message:dn(s?.message)||`System auth verify failed with status ${i.status}.`}}}let a=qg(s),c=dn(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=Lg(a?.extra);return{ok:!0,data:{userId:c,roles:l,...u?{extra:u}:{}}}}function $g(t,e){return e==="runtime.unauthenticated"||e==="runtime.token_expired"||e==="runtime.token_revoked"?401:t}async function zg(t){try{return await t.json()}catch{return null}}function qg(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 Lg(t){if(!t||typeof t!="object")return null;let e=t;if(e.tokenType!=="account")return null;let r=dn(e.email)??"",n=dn(e.displayName)??"",o=ce(e.accountProjectId);return o===null?null:{tokenType:"account",email:r,displayName:n,accountProjectId:o,accountProjectEnvKey:dn(e.accountProjectEnvKey)??void 0,...Re(e.serviceRegion)?{serviceRegion:e.serviceRegion}:{}}}function Dg(t){if(!t)return null;let[e,r]=t.split(" "),n=e?.trim().toLowerCase(),o=r?.trim()??"";if(!n||!o)return null;if(n==="bearer")return{kind:"bearer",token:o};if(n==="accesskey"){let i=o.indexOf(".");if(i<=0||i>=o.length-1)return null;let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();return!s||!a?null:{kind:"access-key",keyId:s,secret:a}}return null}function Mg(t,e){if(t.kind!=="bearer")return e;let r=Lf(t.token);if(!r||r.iss!=="system")return e;let n=r.typ==="project-session"?ce(r.projectId):r.typ==="account-identity"||r.typ==="account-refresh"?ce(r.accountProjectId):null;if(n===null)return e;let o=r.typ==="project-session"?Y(r.projectEnvKey):Y(r.accountProjectEnvKey);return{projectId:n,projectEnvKey:o}}function Lf(t){let e=t.split(".");if(e.length!==3)return null;let r=e[1];if(!r)return null;try{return yf(r)}catch{return null}}function dn(t){if(typeof t!="string")return null;let e=t.trim();return e||null}function Df(t){let e=new Map,r=async n=>{let o=JSON.stringify(n),i=e.get(o);return i||(i=Kf(t,Nf,{...n.key?{key:n.key}:{},...n.keys?{keys:[...n.keys]}:{},...n.productId?{productId:n.productId}:{}}).then(s=>{let a=jr(jr(s.data).settings);return Object.fromEntries(Object.entries(a).map(([c,l])=>[c,jr(l).value]))}),e.set(o,i)),await i};return{async get(n,o){return vc(n),(await r({key:n,...o}))[n]},async getMany(n,o){for(let i of n)vc(i);return await r({keys:n,...o})},async snapshot(n){return await r({...n})}}}function Mf(t){let e=new Map;return{async get(r,n){vc(r);let o=n?.purpose??"runtime",i=`${o}:${r}`,s=e.get(i);return s||(s=Kf(t,Pf,{key:r,purpose:o}).then(a=>jr(jr(a.data).payload)),e.set(i,s)),await s}}}async function Kf(t,e,r){let n=JSON.stringify(r),o=await Ir({method:"POST",path:Sr(e),bodyText:n,caller:{projectId:t.projectId,projectEnvKey:t.projectEnvKey,extensionId:t.extensionId},secret:Rt(t.env),...t.request?.headers.get("x-request-id")?{sourceRequestId:t.request.headers.get("x-request-id")}:{}}),i=await po({env:t.env,request:t.request,projectId:t.projectId,projectEnvKey:t.projectEnvKey,path:e,method:"POST",headers:{"content-type":"application/json",...o},body:n});if(!i)throw new Error(`System service is unavailable for ${e}.`);let s=await Kg(i);if(!i.ok){let a=jr(s).code;throw new Error(typeof a=="string"?a:`System request failed with ${i.status}.`)}return jr(s)}function vc(t){if(!t.trim()||t.includes("*"))throw new Error("A non-wildcard key is required.")}function jr(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}async function Kg(t){try{return await t.json()}catch{return null}}function Uf(){return async(t,e)=>{let r={env:t.env,request:Er(t),projectId:ce(t.get("projectId"))??Je,projectEnvKey:Y(t.get("projectEnvKey")),extensionId:String(t.get("extensionId")??"")};return t.set("settingReader",Df(r)),t.set("credentialReader",Mf(r)),zf(t,$f(t,r.env)),await e()}}function Bf(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 Ff(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 Vf(t={},e){return async(r,n)=>{let o=Ff(r.env,r.req.raw.headers)??Vg(),i=Er(r),s=ho();r.set("requestId",o),r.header("x-request-id",o),Rf(i);let a=hc(r.env,t,o),c=e??gc({env:r.env,request:r.req.raw,source:a}),l=await uc({env:r.env,request:r.req.raw,source:a});await oc({provider:c,requestId:o,method:r.req.method,incomingTrace:l,source:()=>a?{...a,userId:String(r.get("userId")??"")||null}:null,error:()=>r.error instanceof Lt?null:r.error,status:()=>r.res.status,...c&&Fg(r.env)?{defer:p=>r.executionCtx.waitUntil(p)}:{}},n),r.header("x-request-id",o),yc(i,"app_total",ho()-s),Of(i,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=Bf(r.env);d&&r.header("x-kuafu-worker-version-id",d)}}function Fg(t){return!gt(t)}function Vg(){return`req_${crypto.randomUUID()}`}var Wg="x-kuafu-gateway-ingress-token";function Wf(){return async(t,e)=>{let r=!gt(t.env),n=Qg(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(Wg)?.trim()??"")!==n)return t.json({code:"runtime.gateway_ingress_unauthorized",message:"Extension API must be accessed through the platform Gateway."},403);await e()}}function Qg(t,e){if(!t||typeof t!="object")return"";let r=t[e];return typeof r=="string"?r.trim():""}function Hf(t){return async(e,r)=>{let n=new URL(e.req.raw.url).pathname,o=xu(n),i=ce(e.req.header("x-project-id")),s=Qf(e.req.header("x-project-env-key")??e.req.header("x-platform-project-env-key")),a=Qf(e.env?.PLATFORM_PROJECT_ENV_KEY),c=i??o?.projectId??Je,l=s??o?.projectEnvKey??a??Y(null),u=String(e.req.header("authorization")??""),d=e.env?.PLATFORM_PROJECT_REGION_POLICY,p=pt(d===void 0?t.regionPolicy:d),h=yo({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",h);let b={};for(let[_,k]of e.req.raw.headers)b[_.toLowerCase()]=k;return ft({extensionId:t.extensionId,projectId:c,projectEnvKey:l,userId:"",accessKey:u,roles:[],regionContext:h,requestId:w,headers:b},()=>r())}}function Qf(t){if(!(typeof t!="string"||!t.trim()))return Y(t)}yi(g);function Yf(t){return Jg(t)}function Hg(t,e){return async(r,n)=>{let o=r.env,i=ju(t)?o:ga(t,o);Fn.set(r,o);let s=o,a=s?.PLATFORM_PROJECT_ID!==void 0||s?.PLATFORM_PROJECT_ENV_KEY!==void 0,c=Object.freeze({extensionId:t,projectId:a?ce(s?.PLATFORM_PROJECT_ID)??0:Ci(r.get("projectId")),projectEnvKey:a?typeof s?.PLATFORM_PROJECT_ENV_KEY=="string"?s.PLATFORM_PROJECT_ENV_KEY:"":go(r.get("projectEnvKey"))}),l=of(r,{bindings:o,scope:{extensionId:c.extensionId,projectId:String(c.projectId),projectEnvKey:c.projectEnvKey},homeRegion:r.get("projectRegionPolicy")?.homeRegion,readRegion:()=>At()?.regionContext?.region});r.set("cloudStorage",gf({context:r,bindings:o??{},collections:e,readContext:At,scope:{extensionId:c.extensionId,projectId:String(c.projectId),projectEnvKey:c.projectEnvKey}})),Iu(r,c,(u,d)=>Af({env:o,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=i;try{await n()}finally{r.env=o,Fn.delete(r),di.delete(r),l()}}}function Jg(t){let e=t.mountPath??Zg(t.config.extensionId),r=new rc,n=new rc;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((o,i)=>o instanceof Lt?o.getResponse():(ic(o,String(i.get("requestId")??"")),i.text("Internal Server Error",500))),Jf(r),Jf(n),r.doc(`${e}/doc`,{openapi:"3.0.0",info:Gg(t.config)}),n.use("*",Vf(t.config,t.telemetry)),n.use("*",Wf()),n.use("*",Hf(t.config)),n.get("/__kuafu/health",async o=>{let i=await Su({env:o.env,resolveScope:()=>({projectId:Ci(o.get("projectId")),projectEnvKey:go(o.get("projectEnvKey"))}),extensionId:t.config.extensionId});return o.json(i.body,i.status)}),Yg(t)&&n.use("*",Xg(t.config,t.tables,t.resolveDatabase)),n.use("*",Uf()),n.use("*",Hg(t.config.extensionId,t.cloudCollections??[]));for(let o of t.middleware??[])n.use("*",o);for(let o of df(t.cloudCollections??[]))n.openapi(Gf(o.route),Zf(o));for(let o of t.apis){let i=Gf(o.route);n.openapi(i,Zf(o))}return r.route(e,n),r}function Gg(t){return{title:t.displayName??t.name??t.extensionId,version:t.version??"0.0.0",description:t.description}}function Jf(t){t.openAPIRegistry.registerComponent("securitySchemes","BearerAuth",{type:"http",scheme:"bearer",bearerFormat:"JWT"})}function Zg(t){return`/api/${t}`}function Yg(t){return!!t.tables||typeof t.resolveDatabase=="function"||t.apis.length>0}function Xg(t,e,r){return async(n,o)=>{let i=r?await r(n,{config:t,tables:e}):(()=>{if(!e)throw new Error(`Database schema (tables) is required for ${t.extensionId}`);let s=n.env,a=e,c=Ci(n.get("projectId")),l=go(n.get("projectEnvKey")),u="default";if(ha({env:s,projectEnvKey:l})==="postgres"){let _=ry(s);if(!_)throw new Error(`PostgreSQL service binding ${pa} is required for ${t.extensionId}`);let k=yu(_,{projectId:c,projectEnvKey:l,extensionId:t.extensionId,databaseName:u});return bu(tf(k),{schema:a})}let p=Jr(s);if(!p)throw new Error(`Durable Object binding ${Br} is required for ${t.extensionId}`);let h=_t({projectId:c,projectEnvKey:l,extensionId:t.extensionId,databaseName:u}),w=p.get(p.idFromName(h)),b=Mn(w);return nu(ef(b),{schema:a})})();n.set("db",i),await o()}}function Gf(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(([o,i])=>{let s={description:i.description??`HTTP ${o}`};return"schema"in i&&i.schema&&(s.content={"application/json":{schema:i.schema}}),[o,s]})):{200:{description:"OK"}},n={method:t.method.toLowerCase(),path:xc(t.path),summary:t.summary,description:t.description,tags:t.tags,responses:r,middleware:async(o,i)=>{o.set("apiRouteTemplate",xc(t.path)),Zd(xc(t.path)),await i()}};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(o=>o.key)),Vd(n)}function Zf(t){return async e=>{let r=t.route.request?.body?await ey(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:{}},o=Fn.get(e)??e.env,i=await ty(e,t.route.internalPolicy,o);if(i)return i;let s=await Cf(e,{accessLevel:t.route.accessLevel??"public",authScope:t.route.authScope,requirePermissions:t.route.requirePermissions},o);if(s)return s;let a={extensionId:String(e.get("extensionId")??""),projectId:Ci(e.get("projectId")),projectEnvKey:go(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 ft(a,()=>t.handler(e,n))}}async function ey(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(o=>o.message).join("; ")}}async function ty(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 o=e.authSecretBinding?String(r?.[e.authSecretBinding]??"").trim():e.allowCrossEnvironment?Ni(r):Rt(r);if(!o)return t.json({code:"runtime.route_misconfigured",message:"Internal signing key is unavailable."},500);let i=await Ri(t,{secret:o});if(!i.ok)return i.response;let s=Tu(e,i.caller,{projectId:ce(t.get("projectId")),projectEnvKey:go(t.get("projectEnvKey"))});if(s)return t.json(s,403);let a=t.get("extra");return t.set("extra",{...a??{},internalCaller:i.caller,internalSourceRequestId:i.sourceRequestId}),null}function xc(t){return(t.startsWith("/")?t:`/${t}`).replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Ci(t){return ce(t)??Je}function go(t){return Y(typeof t=="string"?t:null)}function ry(t){let e=t?.[pa];return!e||typeof e!="object"||typeof e.fetch!="function"?null:e}var kc=g.object({id:g.string(),projectId:g.string(),envKey:g.string().min(1),provider:g.literal("github"),sourceKind:g.enum(["managed","external"]),providerRepositoryId:g.string().nullable(),organization:g.string(),name:g.string(),fullName:g.string().nullable(),cloneUrl:g.string().nullable(),defaultBranch:g.string().nullable(),templateKey:g.string().nullable().default(null),templateVersion:g.string().nullable(),templateRevision:g.string().nullable().default(null),status:g.enum(["provisioning","ready","deleting","failed"]),projectionState:g.enum(["uninitialized","initializing","ready","failed"]).default("ready"),createdOperationId:g.string(),createdBy:g.string(),createdAt:g.number(),updatedAt:g.number(),readOnly:g.boolean().default(!1),releaseWritable:g.boolean().default(!0)}),Xf=de({method:"GET",path:"/develop/repository/list",accessLevel:"protected",authScope:"admin",requirePermissions:[{key:"developer.read"}],summary:"\u5217\u51FA\u5F53\u524D Project prod \u5B9A\u4E49\u7684\u7814\u53D1\u4ED3\u5E93\u3002",responses:{200:{schema:g.object({data:g.object({primaryRepositoryId:g.string().nullable(),repositories:g.array(kc)})}),description:"\u5F53\u524D Project \u7684\u7814\u53D1\u4ED3\u5E93\u5217\u8868\u3002"},500:{schema:g.object({code:g.string(),message:g.string()}),description:"\u672C\u5730 Repository catalog \u7F3A\u5931\u6216\u975E\u6CD5\u3002"},400:{schema:g.object({code:g.string(),message:g.string()}),description:"\u4ED3\u5E93\u63A5\u53E3\u4EC5\u652F\u6301 prod \u73AF\u5883\u3002"}},tags:["develop","repository"]});var ny=g.object({hostProfileId:g.string(),repositories:g.array(g.object({profileId:g.string(),projectId:g.string(),repositoryId:g.string(),name:g.string(),owner:g.string(),provider:g.literal("github"),sourceKind:g.enum(["managed","external"]),defaultBranch:g.string().nullable()}))});function ep(t,e){let r=ny.parse(JSON.parse(String(t.KUAFUCLOUD_LOCAL_REPOSITORY_CATALOG)));return r.repositories.find(n=>n.profileId===r.hostProfileId&&n.projectId===e&&n.name===t.PREVIEW_REPOSITORY_NAME)}var oy=be(Xf,async t=>{let e=ep(t.env,String(t.get("projectId"))),r=e?[kc.parse({id:e.repositoryId,projectId:e.projectId,envKey:t.get("projectEnvKey"),provider:e.provider,sourceKind:e.sourceKind,providerRepositoryId:null,organization:e.owner,name:e.name,fullName:e.owner+"/"+e.name,cloneUrl:null,defaultBranch:e.defaultBranch,templateVersion:null,status:"ready",projectionState:"uninitialized",createdOperationId:"",createdBy:"local-catalog",createdAt:0,updatedAt:0,readOnly:!0,releaseWritable:!1})]:[];return t.json({data:{primaryRepositoryId:e?.repositoryId??null,repositories:r}},200)}),_c=g.array(g.unknown()).max(0),iy=be(de({method:"GET",path:"/develop/release/list",accessLevel:"protected",authScope:"admin",requirePermissions:[{key:"developer.read"}],request:{query:g.object({repositoryId:g.string().min(1).max(160)})},responses:{200:{schema:g.object({data:g.object({state:g.null(),mergeCandidates:_c,nodes:_c,releases:_c})}),description:"\u5F53\u524D\u6A21\u62DF\u4ED3\u7684\u672C\u5730\u7248\u672C\u5386\u53F2"},404:{schema:g.object({code:g.string(),message:g.string()}),description:"\u5F53\u524D\u4ED3\u4E0D\u53EF\u89C1"}}}),async(t,{query:e})=>ep(t.env,String(t.get("projectId")))?.repositoryId!==e.repositoryId?t.json({code:"preview.repository_not_found",message:"\u5F53\u524D\u4ED3\u5E93\u4E2D\u6CA1\u6709\u8BE5\u7248\u672C\u76EE\u5F55\u3002"},404):t.json({data:{state:null,mergeCandidates:[],nodes:[],releases:[]}},200)),tp=[oy,iy];var Sc=j.string().uuid(),op=j.string().regex(/^(?!0+$)[0-9a-f]{32}$/u),Ec=j.string().regex(/^(?!0+$)[0-9a-f]{16}$/u),rp=j.string().regex(/^[a-zA-Z][a-zA-Z0-9_.:-]{0,127}$/u),ip=j.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,47}$/u).refine(t=>!/token|password|secret|authorization|cookie|headers|body|sql|params/iu.test(t)),Ic=j.string().min(1).max(512).nullable(),np=j.string().max(512).refine(t=>!/[?\u0000-\u001f\u007f]/u.test(t)),sp=j.object({projectId:j.string().regex(/^[1-9]\d{0,15}$/u),projectEnvKey:j.string().regex(/^[a-z0-9][a-z0-9_-]{0,62}$/u),productId:j.string().regex(/^[a-z][a-z0-9-]{0,63}$/u),productRelease:j.string().min(1).max(128),runtime:j.enum(["server","extension-admin","web","app","mini-program"]),requestId:j.string().min(1).max(128).nullable(),routeTemplate:np.nullable(),pagePattern:np.nullable().optional(),userId:Ic,did:Ic.optional(),sessionId:Ic.optional()}).strict();var sy=j.object({schemaVersion:j.literal(1),kind:j.literal("error"),eventId:Sc,occurredAt:j.string().datetime({offset:!0}),source:sp,mechanism:j.enum(["handled","unhandled","resource"]),error:j.object({name:j.string().regex(/^[a-zA-Z][a-zA-Z0-9_.]{0,95}$/u),message:j.string().max(2048),stack:j.string().max(16384).nullable(),stackDigest:j.string().regex(/^sha256:[0-9a-f]{64}$/u).optional()}).strict(),context:j.object({code:rp.optional(),groupingKey:rp.optional(),tags:j.record(ip,j.string().max(128)).refine(t=>Object.keys(t).length<=16).optional()}).strict(),traceId:op.nullable(),spanId:Ec.nullable()}).strict().refine(t=>t.traceId!==null||t.spanId===null);var ay=j.object({spanId:Ec,parentSpanId:Ec.nullable(),name:j.string().min(1).max(256),kind:j.enum(["http","business","rpc","sql"]),startedAt:j.string().datetime({offset:!0}),durationMs:j.number().finite().min(0).max(864e5).nullable(),state:j.enum(["running","finished"]),status:j.enum(["ok","error"]),attributes:j.record(ip,j.union([j.string().max(128),j.number().finite(),j.boolean()])).refine(t=>Object.keys(t).length<=16),droppedAttributes:j.number().int().nonnegative().max(1e6)}).strict().refine(t=>t.state==="running"?t.durationMs===null:t.durationMs!==null);var cy=j.discriminatedUnion("rule",[j.object({unit:j.literal("trace"),rule:j.literal("head-random"),probability:j.number().finite().min(0).max(1),ruleVersion:j.literal(1)}).strict(),j.object({unit:j.literal("trace"),rule:j.literal("inherited"),probability:j.null(),ruleVersion:j.null()}).strict(),j.object({unit:j.literal("trace"),rule:j.literal("unknown"),probability:j.null(),ruleVersion:j.null()}).strict()]),ly=j.object({schemaVersion:j.literal(1),kind:j.literal("trace"),traceId:op,source:sp,sampling:cy,spans:j.array(ay).min(1).max(100),droppedSpans:j.number().int().nonnegative().max(1e6)}).strict().refine(t=>{let e=new Map(t.spans.map(r=>[r.spanId,r.parentSpanId]));return e.size!==t.spans.length?!1:t.spans.every(r=>{let n=new Set([r.spanId]),o=r.parentSpanId;for(;o&&e.has(o);){if(n.has(o))return!1;n.add(o),o=e.get(o)??null}return!0})}),fn=j.discriminatedUnion("channel",[j.object({schemaVersion:j.literal(1),channel:j.literal("errors"),deliveryId:Sc,events:j.array(sy).min(1).max(100)}).strict(),j.object({schemaVersion:j.literal(1),channel:j.literal("traces"),deliveryId:Sc,traces:j.array(ly).min(1).max(20)}).strict()]);var ap="developer";var cp=Xl({extensionId:ap,databaseName:"default",tables:{PreviewMonitorDelivery:cr.table("PreviewMonitorDelivery",{deliveryId:cr.text().primaryKey(),receivedAt:cr.text().notNull(),payload:cr.text().notNull()})}});var{PreviewMonitorDelivery:Ot}=cp,lp={PreviewMonitorDelivery:Ot};var up=["extension","site","app","mini-program"],dp=["server-http","extension-admin","site-web","app-hot-update","mini-program-release"];var uy=[{workflowKey:"repository.create",dispatchKind:"formal",bindingName:"REPOSITORY_CREATE_WORKFLOW",className:"RepositoryCreateWorkflow",nameSegment:"repository-create",scriptOwner:"platform-cloud-manager-worker"},{workflowKey:"monitor.runtime-job",dispatchKind:"formal",bindingName:"MONITOR_RUNTIME_JOB_WORKFLOW",className:"MonitorRuntimeJobWorkflow",nameSegment:"monitor-runtime-job",scriptOwner:"platform-cloud-manager-worker"},{workflowKey:"repository.destroy",dispatchKind:"formal",bindingName:"REPOSITORY_DESTROY_WORKFLOW",className:"RepositoryDestroyWorkflow",nameSegment:"repository-destroy",scriptOwner:"platform-cloud-manager-worker"},{workflowKey:"archive.projection",dispatchKind:"formal",bindingName:"ARCHIVE_PROJECTION_WORKFLOW",className:"ArchiveProjectionWorkflow",nameSegment:"archive-projection",scriptOwner:"platform-cloud-manager-worker"},{workflowKey:"release.projection",dispatchKind:"formal",bindingName:"RELEASE_PROJECTION_WORKFLOW",className:"ReleaseProjectionWorkflow",nameSegment:"release-projection",scriptOwner:"platform-cloud-manager-worker"},{workflowKey:"release.product-deployment",dispatchKind:"formal",bindingName:"RELEASE_PRODUCT_DEPLOYMENT_WORKFLOW",className:"ReleaseProductDeploymentWorkflow",nameSegment:"release-product-deployment",scriptOwner:"platform-cloud-manager-worker"},{workflowKey:"project.provision",dispatchKind:"formal",bindingName:"PROJECT_PROVISION_WORKFLOW",className:"ProjectProvisionWorkflow",nameSegment:"project-provision",scriptOwner:"platform-cloud-manager-worker"},{workflowKey:"project.destroy",dispatchKind:"formal",bindingName:"PROJECT_DESTROY_WORKFLOW",className:"ProjectDestroyWorkflow",nameSegment:"project-destroy",scriptOwner:"platform-cloud-manager-worker"},{workflowKey:"environment.provision",dispatchKind:"formal",bindingName:"ENVIRONMENT_PROVISION_WORKFLOW",className:"EnvironmentProvisionWorkflow",nameSegment:"environment-provision",scriptOwner:"platform-cloud-manager-worker"},{workflowKey:"environment.destroy",dispatchKind:"formal",bindingName:"ENVIRONMENT_DESTROY_WORKFLOW",className:"EnvironmentDestroyWorkflow",nameSegment:"environment-destroy",scriptOwner:"platform-cloud-manager-worker"},{workflowKey:"workflow.test-execution",dispatchKind:"test",bindingName:"WORKFLOW_TEST_EXECUTION_WORKFLOW",className:"WorkflowTestExecutionWorkflow",nameSegment:"workflow-test-execution",scriptOwner:"platform-cloud-manager-worker"},{workflowKey:"platform.integration-test",dispatchKind:"formal",bindingName:"PLATFORM_INTEGRATION_TEST_WORKFLOW",className:"PlatformIntegrationTestWorkflow",nameSegment:"platform-integration-test",scriptOwner:"platform-cloud-manager-worker"}],JN=uy.filter(t=>t.dispatchKind==="formal");var gP=64*1024*1024;var OP=Object.freeze([Object.freeze({tag:"im-sqlite-v1",new_sqlite_classes:Object.freeze(["ConversationDO","UserDO"])})]),NP=Object.freeze([Object.freeze({name:"CONVERSATIONS",className:"ConversationDO"}),Object.freeze({name:"USERS",className:"UserDO"})]);var eC=Object.freeze({homeRegion:"cn",splitRegions:!0});function gy({allowIcannDomains:t=!0,allowPrivateDomains:e=!1,detectIp:r=!0,extractHostname:n=!0,mixedInputs:o=!0,validHosts:i=null,validateHostname:s=!0}){return{allowIcannDomains:t,allowPrivateDomains:e,detectIp:r,extractHostname:n,mixedInputs:o,validHosts:i,validateHostname:s}}var mC=gy({});function Tc(){return{domain:null,domainWithoutSuffix:null,hostname:null,isIcann:null,isIp:null,isPrivate:null,publicSuffix:null,subdomain:null}}var VC=Tc();var bp=g.enum([...up]),hp=g.enum([...dp]),gp=g.object({productId:g.string(),productKind:bp}).strict(),yp=g.object({ownerProjectId:g.number().int().positive(),ownerProjectEnvKey:g.string().min(1),operationId:g.string().min(1),workflowKey:g.literal("release.product-deployment")}).strict(),ky=g.object({installation:g.object({id:g.string(),activeReleaseId:g.string().nullable(),upgradingReleaseId:g.string().nullable(),currentOperationId:g.string().nullable(),currentOperationAction:g.string().nullable(),revision:g.number().int().positive()}).strict(),surfaces:g.array(g.object({surface:hp,rolloutBps:g.number().int().min(0).max(1e4)}).strict()),grayDeployments:g.array(g.object({id:g.string(),surface:hp,releaseId:g.string(),allocationBps:g.number().int().min(1).max(9999),status:g.enum(["running","stopping"]),createdAt:g.number().int().nonnegative()}).strict()),workflowOperations:g.object({baseline:yp.nullable(),grayDeployments:g.array(g.object({grayDeploymentId:g.string().min(1),operation:yp}).strict())}).strict()}).strict(),wp=de({method:"GET",path:"/develop/product/traffic/get",accessLevel:"protected",authScope:"admin",requirePermissions:[{key:"developer.read"}],summary:"\u8BFB\u53D6\u751F\u4EA7\u73AF\u5883 Product \u7684\u57FA\u7EBF\u5347\u7EA7\u4E0E\u7070\u5EA6\u6D41\u91CF\u72B6\u6001\u3002",request:{query:g.object({productId:g.string().min(1).max(160).optional(),productKind:bp.optional()}).strict().superRefine((t,e)=>{!!t.productId!=!!t.productKind&&e.addIssue({code:g.ZodIssueCode.custom,message:"productId and productKind must be provided together."})})},responses:{200:{schema:g.object({data:g.object({products:g.array(gp),selectedProduct:gp.nullable(),state:ky.nullable()}).strict()}),description:"\u5F53\u524D\u53EF\u9009 Product \u4E0E\u6240\u9009 Product \u7684\u751F\u4EA7\u6D41\u91CF\u72B6\u6001\u3002"},409:{schema:g.object({code:g.string(),message:g.string()}),description:"\u5F53\u524D\u4E0D\u662F\u751F\u4EA7\u73AF\u5883\u3002"},502:{schema:g.object({code:g.string(),message:g.string()}),description:"System \u6D41\u91CF\u72B6\u6001\u8BFB\u53D6\u5931\u8D25\u3002"}},tags:["develop","product","traffic"]});var kp={accessLevel:"protected",authScope:"admin",requirePermissions:[{key:"developer.monitoring.read"}]},Rc=g.enum(["server","extension-admin","web","app","mini-program"]),Oc=g.object({productId:g.string(),productKind:g.enum(["extension","site","app","mini-program"]),displayName:g.string().nullable(),versions:g.array(g.string()),runtimes:g.array(Rc),defaultRuntime:Rc.nullable()}),_y=be(de({...kp,method:"GET",path:"/monitoring/catalog",responses:{200:{schema:g.object({data:g.object({products:g.array(Oc)})}),description:"\u5F53\u524D\u4ED3\u5E93\u7684\u4EA7\u54C1\u76EE\u5F55"}}}),async t=>{let e=t.env.PREVIEW_MONITOR_PRODUCTS,r=typeof e=="string"?g.array(Oc).parse(JSON.parse(e)):[];return t.json({data:{products:r}},200)}),vp=g.object({status:g.literal("ready"),scope:g.literal("environment"),checkedAt:g.number(),lastReconciledAt:g.number(),pendingBatches:g.number(),quarantinedBatches:g.number()}),Iy=g.object({requestCount:g.number(),status4xxCount:g.number(),status5xxCount:g.number(),durationCount:g.number(),averageDurationMs:g.number().nullable(),p95:g.null(),overflowDurationCount:g.number()}),Sy=g.object({issueId:g.string(),revision:g.number(),productId:g.string(),runtime:Rc,errorType:g.string(),message:g.string(),version:g.string(),count:g.number(),lastSeenAt:g.number()}),Ac={readStartedAt:g.number(),readCompletedAt:g.number()},Tr=g.array(g.unknown()).max(0),xp=g.object({from:g.number(),to:g.number(),productId:g.string().nullable(),consistency:g.literal("domain-shard-snapshots"),requests:g.object({...Ac,totals:Iy,trend:Tr,histogram:g.object({schemaVersion:g.literal(1),minimumResolutionMs:g.literal(1),relativeBucketWidth:g.literal(.1),maximumBoundMs:g.literal(6e5)}),coverage:g.object({observedOnly:g.literal(!0),status:g.literal("unknown")}),revisions:Tr,processing:vp,attention:Tr,p95Trend:Tr}),issues:g.object({...Ac,unresolvedCount:g.number(),items:g.array(Sy),processing:vp,observedOnly:g.literal(!0),lake:g.object({namespace:g.string(),bucketName:g.string(),tableUuid:g.string(),location:g.string(),retentionRevision:g.number(),positions:Tr})}),alerts:g.object({...Ac,status:g.literal("ready"),firingCount:g.number(),items:Tr,revisions:Tr})}),Ey=be(de({...kp,method:"POST",path:"/monitoring/overview/query",request:{body:g.object({from:g.number().int().nonnegative(),to:g.number().int().positive(),productId:g.string().optional()}).strict().refine(t=>t.to>t.from&&t.to-t.from<=30*864e5)},responses:{200:{schema:g.object({data:xp}),description:"\u5F53\u524D\u4ED3\u5E93\u6D4B\u8BD5\u7A97\u53E3\u5185\u7684\u76D1\u63A7\u603B\u89C8"}}}),async(t,{body:e})=>{let r=Date.now(),n=new Map,o=await t.get("db").select().from(Ot);for(let l of o){let u=fn.parse(JSON.parse(l.payload));if(u.channel==="errors")for(let d of u.events){let p=Date.parse(d.occurredAt),h=d.source;if(p<e.from||p>=e.to||e.productId&&h.productId!==e.productId)continue;let w=JSON.stringify([h.productId,h.runtime,d.error.name,d.context.groupingKey??d.error.message]),b=n.get(w);if(b)b.count++,p>b.lastSeenAt&&Object.assign(b,{lastSeenAt:p,message:d.error.message,version:h.productRelease});else{let _=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(w)));n.set(w,{issueId:"mi2_"+Array.from(_,k=>k.toString(16).padStart(2,"0")).join(""),revision:1,productId:h.productId,runtime:h.runtime,errorType:d.error.name,message:d.error.message,version:h.productRelease,count:1,lastSeenAt:p})}}}let i=Date.now(),s={readStartedAt:r,readCompletedAt:i},a={status:"ready",scope:"environment",checkedAt:i,lastReconciledAt:i,pendingBatches:0,quarantinedBatches:0},c=[...n.values()].sort((l,u)=>u.lastSeenAt-l.lastSeenAt||l.issueId.localeCompare(u.issueId)).slice(0,2);return t.json({data:xp.parse({from:e.from,to:e.to,productId:e.productId??null,consistency:"domain-shard-snapshots",requests:{...s,totals:{requestCount:0,status4xxCount:0,status5xxCount:0,durationCount:0,averageDurationMs:null,p95:null,overflowDurationCount:0},coverage:{observedOnly:!0,status:"unknown"},histogram:{schemaVersion:1,minimumResolutionMs:1,relativeBucketWidth:.1,maximumBoundMs:6e5},trend:[],revisions:[],processing:a,attention:[],p95Trend:[]},issues:{...s,unresolvedCount:n.size,items:c,observedOnly:!0,processing:a,lake:{namespace:"preview",bucketName:"",tableUuid:"PreviewMonitorDelivery",location:"sqlite",retentionRevision:0,positions:[]}},alerts:{...s,status:"ready",firingCount:0,items:[],revisions:[]}})},200)}),jy=be(wp,async(t,{query:e})=>{let r=t.env.PREVIEW_MONITOR_PRODUCTS,n=typeof r=="string"?g.array(Oc).parse(JSON.parse(r)).map(({productId:i,productKind:s})=>({productId:i,productKind:s})):[],o=(e.productId?n.find(i=>i.productId===e.productId&&i.productKind===e.productKind):n[0])??null;return t.json({data:{products:n,selectedProduct:o,state:null}},200)}),_p=[_y,Ey,jy];var Nc=g.object({code:g.string(),message:g.string()}),Ty={key:"developer.monitoring.read"},Ay=be(de({method:"POST",path:"/internal/monitoring/receive",accessLevel:"public",internalPolicy:{internalOnly:!0,auth:"signed",allowedCallerExtensions:["system"]},request:{body:g.object({delivery:fn}).strict()},responses:{200:{schema:g.object({data:g.object({deliveryId:g.string().uuid(),status:g.enum(["accepted","duplicate"]),memberCount:g.number().int().positive(),receivedAt:g.string().datetime()})}),description:"\u672C\u4ED3\u6301\u4E45\u5316\u56DE\u6267"},403:{schema:Nc,description:"\u6765\u6E90\u4E0D\u5C5E\u4E8E\u5F53\u524D\u73AF\u5883"},409:{schema:Nc,description:"\u6279\u6B21\u8EAB\u4EFD\u51B2\u7A81"}}}),async(t,{body:{delivery:e}})=>{let r=e.channel==="errors"?e.events:e.traces;if(r.some(({source:c})=>c.projectId!==String(t.get("projectId"))||c.projectEnvKey!==t.get("projectEnvKey")||c.runtime==="server"))return t.json({code:"monitor.source_forbidden",message:"\u524D\u7AEF\u91C7\u96C6\u6765\u6E90\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9884\u89C8\u3002"},403);let n=new Date().toISOString(),o=t.get("db"),i=JSON.stringify(e),[s]=await o.insert(Ot).values({deliveryId:e.deliveryId,receivedAt:n,payload:i}).onConflictDoNothing().returning(),a=s??(await o.select().from(Ot).where(it(Ot.deliveryId,e.deliveryId)).limit(1))[0];if(!a)throw new Error("preview.monitor_delivery_missing");return a.payload!==i?t.json({code:"monitor.delivery_conflict",message:"\u91CD\u590D\u6279\u6B21\u5185\u5BB9\u4E0D\u4E00\u81F4\u3002"},409):t.json({data:{deliveryId:e.deliveryId,memberCount:r.length,receivedAt:a.receivedAt,status:s?"accepted":"duplicate"}},200)}),Ry=be(de({method:"GET",path:"/monitoring/preview/delivery",accessLevel:"protected",authScope:"admin",requirePermissions:[Ty],request:{query:g.object({deliveryId:g.string().uuid()})},responses:{200:{schema:g.object({data:fn}),description:"\u672C\u4ED3\u76D1\u63A7\u4E8B\u4EF6\u4E0E\u94FE\u8DEF\u6570\u636E"},404:{schema:Nc,description:"\u5F53\u524D\u4ED3\u5E93\u6CA1\u6709\u8BE5\u6279\u6B21"}}}),async(t,{query:e})=>{let[r]=await t.get("db").select().from(Ot).where(it(Ot.deliveryId,e.deliveryId)).limit(1);return r?t.json({data:fn.parse(JSON.parse(r.payload))},200):t.json({code:"monitor.delivery_not_found",message:"\u5F53\u524D\u4ED3\u5E93\u6CA1\u6709\u8BE5\u6279\u6B21\u3002"},404)}),Ip=[Ay,Ry,..._p,...tp];var pn=Ip,Oy=Array.isArray(pn)?pn:pn&&typeof pn=="object"&&Array.isArray(pn.apis)?pn.apis:[],jp={extensionId:"developer",name:"\u5F00\u53D1\u8005",displayName:"\u5F00\u53D1\u8005",description:"\u7BA1\u7406\u4ED3\u5E93\u5206\u652F\u3001\u4EA7\u54C1\u53D1\u7248\u3001\u6D41\u91CF\u4E0E\u76D1\u63A7\u3002"},Sp=new WeakMap;function Ny(t){let e=t.PLATFORM_EXTENSION_RELEASE;if(typeof e!="string"||!e.trim())throw new Error("Deployed extension requires PLATFORM_EXTENSION_RELEASE.");let r=Sp.get(t);if(r&&r.config.version===e)return r;let n={...jp,version:e},o={config:n,app:Yf({config:n,apis:Oy,tables:lp,cloudCollections:void 0})};return Sp.set(t,o),o}var Ep=class extends Yo{},Py=(function({extensionId:e,resolveLogicalDatabaseObjectName:r,mainProjectId:n}){async function o(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=i(d.projectId),h=s(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 _=r({projectId:p,projectEnvKey:h,extensionId:e,databaseName:w}),k=b.get(b.idFromName(_));return l.pathname.endsWith("/apply-migration")?k.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")?k.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:[]})}):k.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 i(a){let c=Number(a);return Number.isFinite(c)&&c>0?Math.floor(c):n}function s(a){let c=typeof a=="string"?a.trim().toLowerCase():"";return/^[a-z0-9][a-z0-9_-]{0,62}$/.test(c)?c:"prod"}return o})({extensionId:jp.extensionId,resolveLogicalDatabaseObjectName:_t,mainProjectId:Je}),Cz={async fetch(t,e,r){let n=await Py(t,e);return n||Ny(e).app.fetch(t,e,r)}};export{Ep as KuafuSqlExecutorObject,Cz as default};
39
+ //# sourceMappingURL=index.js.map