@void/platform 1.11.0 → 1.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-logging.d.mts +8 -12
- package/dist/ai-logging.mjs +7 -10
- package/dist/browser-page.mjs +2 -2
- package/dist/email-protocol.mjs +16 -14
- package/dist/index.d.mts +30 -4
- package/dist/index.mjs +120 -69
- package/dist/installer.d.mts +2 -0
- package/dist/installer.mjs +13 -13
- package/dist/plans.mjs +22 -10
- package/dist/runtime/api/assets/admin/client.js +51 -45
- package/dist/runtime/api/assets/admin/style.css +1 -1
- package/dist/runtime/api/index.js +3748 -329
- package/dist/runtime/dispatch/index.js +8 -8
- package/dist/runtime/drizzle/0065_security_audits.sql +313 -0
- package/dist/runtime/drizzle/compatibility.json +28 -0
- package/dist/runtime/drizzle/meta/_journal.json +7 -0
- package/dist/runtime/emailGateway/index.js +5 -5
- package/dist/runtime/manifest.json +51 -16
- package/dist/runtime/proxy/index.js +5 -5
- package/dist/security-local-check.d.mts +28 -0
- package/dist/security-local-check.mjs +140 -0
- package/dist/security-lockfile.d.mts +34 -0
- package/dist/security-lockfile.mjs +181 -0
- package/dist/security-models.d.mts +88 -0
- package/dist/security-models.mjs +186 -0
- package/dist/security-policy.d.mts +245 -0
- package/dist/security-policy.mjs +491 -0
- package/package.json +23 -6
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var Wr=Object.create;var Ge=Object.defineProperty;var Xr=Object.getOwnPropertyDescriptor;var Yr=Object.getOwnPropertyNames;var Jr=Object.getPrototypeOf,Kr=Object.prototype.hasOwnProperty;var a=(e,t)=>Ge(e,"name",{value:t,configurable:!0});var ue=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Qr=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Zr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Yr(t))!Kr.call(e,o)&&o!==r&&Ge(e,o,{get:()=>t[o],enumerable:!(n=Xr(t,o))||n.enumerable});return e};var en=(e,t,r)=>(r=e!=null?Wr(Jr(e)):{},Zr(t||!e||!e.__esModule?Ge(r,"default",{value:e,enumerable:!0}):r,e));function H(e){return new Error(`[unenv] ${e} is not implemented yet!`)}var It=ue(()=>{g();a(H,"createNotImplementedError")});var qe,ze,tn,F,Ve,Y,J,fe,z,pe,K,vt=ue(()=>{g();It();qe=globalThis.performance?.timeOrigin??Date.now(),ze=globalThis.performance?.now?globalThis.performance.now.bind(globalThis.performance):()=>Date.now()-qe,tn={name:"node",entryType:"node",startTime:0,duration:0,nodeStart:0,v8Start:0,bootstrapComplete:0,environment:0,loopStart:0,loopExit:0,idleTime:0,uvMetricsInfo:{loopCount:0,events:0,eventsWaiting:0},detail:void 0,toJSON(){return this}},F=class{static{a(this,"PerformanceEntry")}__unenv__=!0;detail;entryType="event";name;startTime;constructor(t,r){this.name=t,this.startTime=r?.startTime||ze(),this.detail=r?.detail}get duration(){return ze()-this.startTime}toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration,detail:this.detail}}},Ve=class extends F{static{a(this,"PerformanceMark")}entryType="mark";constructor(){super(...arguments)}get duration(){return 0}},Y=class extends F{static{a(this,"PerformanceMeasure")}entryType="measure"},J=class extends F{static{a(this,"PerformanceResourceTiming")}entryType="resource";serverTiming=[];connectEnd=0;connectStart=0;decodedBodySize=0;domainLookupEnd=0;domainLookupStart=0;encodedBodySize=0;fetchStart=0;initiatorType="";name="";nextHopProtocol="";redirectEnd=0;redirectStart=0;requestStart=0;responseEnd=0;responseStart=0;secureConnectionStart=0;startTime=0;transferSize=0;workerStart=0;responseStatus=0},fe=class{static{a(this,"PerformanceObserverEntryList")}__unenv__=!0;getEntries(){return[]}getEntriesByName(t,r){return[]}getEntriesByType(t){return[]}},z=class{static{a(this,"Performance")}__unenv__=!0;timeOrigin=qe;eventCounts=new Map;_entries=[];_resourceTimingBufferSize=0;navigation=void 0;timing=void 0;timerify(t,r){throw H("Performance.timerify")}get nodeTiming(){return tn}eventLoopUtilization(){return{}}markResourceTiming(){return new J("")}onresourcetimingbufferfull=null;now(){return this.timeOrigin===qe?ze():Date.now()-this.timeOrigin}clearMarks(t){this._entries=t?this._entries.filter(r=>r.name!==t):this._entries.filter(r=>r.entryType!=="mark")}clearMeasures(t){this._entries=t?this._entries.filter(r=>r.name!==t):this._entries.filter(r=>r.entryType!=="measure")}clearResourceTimings(){this._entries=this._entries.filter(t=>t.entryType!=="resource"||t.entryType!=="navigation")}getEntries(){return this._entries}getEntriesByName(t,r){return this._entries.filter(n=>n.name===t&&(!r||n.entryType===r))}getEntriesByType(t){return this._entries.filter(r=>r.entryType===t)}mark(t,r){let n=new Ve(t,r);return this._entries.push(n),n}measure(t,r,n){let o,i;typeof r=="string"?(o=this.getEntriesByName(r,"mark")[0]?.startTime,i=this.getEntriesByName(n,"mark")[0]?.startTime):(o=Number.parseFloat(r?.start)||this.now(),i=Number.parseFloat(r?.end)||this.now());let s=new Y(t,{startTime:o,detail:{start:o,end:i}});return this._entries.push(s),s}setResourceTimingBufferSize(t){this._resourceTimingBufferSize=t}addEventListener(t,r,n){throw H("Performance.addEventListener")}removeEventListener(t,r,n){throw H("Performance.removeEventListener")}dispatchEvent(t){throw H("Performance.dispatchEvent")}toJSON(){return this}},pe=class{static{a(this,"PerformanceObserver")}__unenv__=!0;static supportedEntryTypes=[];_callback=null;constructor(t){this._callback=t}takeRecords(){return[]}disconnect(){throw H("PerformanceObserver.disconnect")}observe(t){throw H("PerformanceObserver.observe")}bind(t){return t}runInAsyncScope(t,r,...n){return t.call(r,...n)}asyncId(){return 0}triggerAsyncId(){return 0}emitDestroy(){return this}},K=globalThis.performance&&"addEventListener"in globalThis.performance?globalThis.performance:new z});var St=ue(()=>{g();vt()});var g=ue(()=>{St();if(!("__unenv__"in K)){let e=z.prototype;for(let t of Object.getOwnPropertyNames(e))if(t!=="constructor"&&!(t in K)){let r=Object.getOwnPropertyDescriptor(e,t);r&&Object.defineProperty(K,t,r)}}globalThis.performance=K;globalThis.Performance=z;globalThis.PerformanceEntry=F;globalThis.PerformanceMark=Ve;globalThis.PerformanceMeasure=Y;globalThis.PerformanceObserver=pe;globalThis.PerformanceObserverEntryList=fe;globalThis.PerformanceResourceTiming=J});var Ct=Qr(Lt=>{"use strict";g();var un=/^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;Lt.validate=function(e){if(!e||e.length>254)return!1;var t=un.test(e);if(!t)return!1;var r=e.split("@");if(r[0].length>64)return!1;var n=r[1].split(".");return!n.some(function(o){return o.length>63})}});g();g();g();var Tt=new TextEncoder,me,Mt;async function rn(e){return me&&Mt===e||(me=await crypto.subtle.importKey("raw",Tt.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),Mt=e),me}a(rn,"getSignKey");async function ge(e,t){let r=await rn(t),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,Tt.encode(e)));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}a(ge,"hmacSign");var he=new TextEncoder,Q=new TextDecoder,nn=5e3,ye=15e3,Nt=15e3,on=65536;async function sn(e,t){if(!t)throw new Error("Email signing key is not configured");return ge(e,t)}a(sn,"sign");async function V(e,t,r,n=nn){let o=new AbortController,i=Date.now()+n,s=a(async f=>{let h=i-Date.now();if(h<=0)throw o.abort(),new Error("EMAIL_ADMISSION_TIMEOUT");let y=f(),b;try{return await Promise.race([y,new Promise((R,E)=>{b=setTimeout(()=>{o.abort(),E(new Error("EMAIL_ADMISSION_TIMEOUT"))},h)})])}finally{b!==void 0&&clearTimeout(b)}},"beforeDeadline"),l=JSON.stringify(r),c=await sn(l,e.EMAIL_SIGNING_SECRET),d=await s(()=>e.API.fetch(`https://api/internal/email/actions${t}`,{method:"POST",headers:{"content-type":"application/json","x-void-internal":c},body:l,signal:o.signal}));if(!d.ok)throw d.body?.cancel().catch(()=>{}),d.status===409?new Error("IDEMPOTENCY_CONFLICT"):new Error(`EMAIL_ADMISSION_${d.status}`);let u=d.body?.getReader();if(!u)throw new Error("EMAIL_ADMISSION_EMPTY_RESPONSE");let p=new Uint8Array(on),m=0;try{for(;;){let f=await s(()=>u.read());if(f.done)break;if(m+f.value.byteLength>p.length)throw new Error("EMAIL_ADMISSION_RESPONSE_TOO_LARGE");p.set(f.value,m),m+=f.value.byteLength}return JSON.parse(Q.decode(p.subarray(0,m)))}finally{u.cancel().catch(()=>{});try{u.releaseLock()}catch{}}}a(V,"call");function kt(e,t){return V(e,"/receipts/claim",t)}a(kt,"claimRelayedReceipt");function Pt(e,t,r){return V(e,"/receipts/complete",{receiptId:t.receiptId,projectId:t.projectId,payloadDigest:t.payloadDigest,reject:r})}a(Pt,"completeRelayedReceipt");function an(e){if(ln(e)===-1)return e;let t=new Map,r=[],n=0,o=0,i=!1,s=!0,l=!0,c=a(f=>{f.byteLength!==0&&(r.push(f),n+=f.byteLength)},"append"),d=a((f,h,y)=>{c(e.subarray(o,f)),c(y),o=h,i=!0},"replace"),u=0;for(;u<e.byteLength;){let f=xt(e,u),h=f===e.byteLength?e.byteLength:f+2;if(s){if(f===u)s=!1,l=!1;else if(l&&(be(e,u,f,"Date: ")||be(e,u,f,"Message-ID: ")))d(u,h,new Uint8Array);else if(cn(e,u,f)){let y=f,b=h,R=Q.decode(e.subarray(u,y));for(;e[b]===32||e[b]===9;)y=xt(e,b),R+=` ${Q.decode(e.subarray(b,y)).replace(/^[ \t]+/,"")}`,b=y===e.byteLength?e.byteLength:y+2;let E=R.replace(/boundary="(=_void_(?:mixed|alternative|related)_[A-Za-z0-9_-]+)"/g,(A,w)=>{let _=t.get(w);return _||(_=`<void-boundary-${t.size}>`,t.set(w,_)),`boundary="${_}"`});E!==R&&d(u,y,he.encode(E)),u=b;continue}}else if(e[u]===45&&e[u+1]===45){let y=u+2,b=Ot(e,y,f)?Q.decode(e.subarray(y,f)):void 0,R=b===void 0?void 0:t.get(b);if(R!==void 0)d(u,f,he.encode(`--${R}`)),s=!0;else if(f-y>=2&&e[f-2]===45&&e[f-1]===45&&Ot(e,y,f-2)){let E=Q.decode(e.subarray(y,f-2)),A=t.get(E);A!==void 0&&d(u,f,he.encode(`--${A}--`))}}u=h}if(!i)return e;c(e.subarray(o));let p=new Uint8Array(n),m=0;for(let f of r)p.set(f,m),m+=f.byteLength;return p}a(an,"canonicalizeVoidMime");function ln(e){for(let t=0;t+3<e.byteLength;t++)if(e[t]===13&&e[t+1]===10&&e[t+2]===13&&e[t+3]===10)return t;return-1}a(ln,"findCrlfCrlf");function xt(e,t){let r=t;for(;r<e.byteLength;){let n=e.indexOf(13,r);if(n===-1)return e.byteLength;if(e[n+1]===10)return n;r=n+1}return e.byteLength}a(xt,"findCrlf");function be(e,t,r,n){if(r-t<n.length)return!1;for(let o=0;o<n.length;o++){let i=e[t+o],s=n.charCodeAt(o);if((i>=65&&i<=90?i+32:i)!==(s|32))return!1}return!0}a(be,"asciiPrefixEquals");function cn(e,t,r){let n="Content-Type:";if(!be(e,t,r,n))return!1;let o=t+n.length;for(;o<r&&(e[o]===32||e[o]===9||e[o]===11||e[o]===12);)o++;return be(e,o,r,"multipart/")}a(cn,"isMultipartContentType");function Ot(e,t,r){if(r<=t)return!1;for(let n=t;n<r;n++){let o=e[n];if(!(o>=65&&o<=90||o>=97&&o<=122||o>=48&&o<=57||o===95||o===45||o===61))return!1}return!0}a(Ot,"isBoundaryToken");async function we(e,t,r,n){let o=an(n),i=he.encode(JSON.stringify({kind:e,from:t.toLowerCase(),recipients:[...new Set(r.map(l=>l.toLowerCase()))].sort()})),s=new Uint8Array(i.length+1+o.length);return s.set(i),s[i.length]=0,s.set(o,i.length+1),[...new Uint8Array(await crypto.subtle.digest("SHA-256",s))].map(l=>l.toString(16).padStart(2,"0")).join("")}a(we,"emailPayloadDigest");function Ee(e,t,r=Nt){return V(e,"/admit",t,Math.min(r,Nt))}a(Ee,"admitEmail");function Z(e,t,r,n=ye){return V(e,`/${encodeURIComponent(t)}/start`,{recipients:r},Math.min(n,ye))}a(Z,"startEmailAttempt");function k(e,t,r,n,o={},i=ye){return V(e,`/${encodeURIComponent(t)}/finish`,{recipients:r,state:n,...o},Math.min(i,ye))}a(k,"finishEmailAttempt");function B(e,t,r,n,o){return V(e,"/receipts",{receiptId:t,projectId:r,status:n,...o?{route:o}:{}})}a(B,"recordEmailReceipt");g();g();var dn=new Set(["abuse","bounce","noreply","postmaster","security"]);function Dt(e){return dn.has(e)}a(Dt,"isReservedEmailSlug");var Lr=en(Ct(),1);import{EmailMessage as Dr}from"cloudflare:email";g();var jt=5e3,Ut=4*1024;function Re(e){return e.token}a(Re,"leaseBearer");async function Ae(e,t,r,n=jt){if(!e.EMAIL_SIGNING_SECRET)return null;let o=new AbortController,i=Date.now()+Math.min(n,jt),s=a(async m=>{let f=i-Date.now();if(f<=0)throw o.abort(),new Error("email credential lease timed out");let h=m(),y;try{return await Promise.race([h,new Promise((b,R)=>{y=setTimeout(()=>{o.abort(),R(new Error("email credential lease timed out"))},f)})])}finally{y!==void 0&&clearTimeout(y)}},"beforeDeadline"),l;try{let m=await ge(`email-lease-v1
|
|
1
|
+
var Jr=Object.create;var ze=Object.defineProperty;var Qr=Object.getOwnPropertyDescriptor;var Zr=Object.getOwnPropertyNames;var en=Object.getPrototypeOf,tn=Object.prototype.hasOwnProperty;var a=(e,t)=>ze(e,"name",{value:t,configurable:!0});var me=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var rn=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var nn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Zr(t))!tn.call(e,o)&&o!==r&&ze(e,o,{get:()=>t[o],enumerable:!(n=Qr(t,o))||n.enumerable});return e};var on=(e,t,r)=>(r=e!=null?Jr(en(e)):{},nn(t||!e||!e.__esModule?ze(r,"default",{value:e,enumerable:!0}):r,e));function F(e){return new Error(`[unenv] ${e} is not implemented yet!`)}var Tt=me(()=>{g();a(F,"createNotImplementedError")});var Ve,We,sn,B,Xe,J,Q,pe,W,ge,Z,Ot=me(()=>{g();Tt();Ve=globalThis.performance?.timeOrigin??Date.now(),We=globalThis.performance?.now?globalThis.performance.now.bind(globalThis.performance):()=>Date.now()-Ve,sn={name:"node",entryType:"node",startTime:0,duration:0,nodeStart:0,v8Start:0,bootstrapComplete:0,environment:0,loopStart:0,loopExit:0,idleTime:0,uvMetricsInfo:{loopCount:0,events:0,eventsWaiting:0},detail:void 0,toJSON(){return this}},B=class{static{a(this,"PerformanceEntry")}__unenv__=!0;detail;entryType="event";name;startTime;constructor(t,r){this.name=t,this.startTime=r?.startTime||We(),this.detail=r?.detail}get duration(){return We()-this.startTime}toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration,detail:this.detail}}},Xe=class extends B{static{a(this,"PerformanceMark")}entryType="mark";constructor(){super(...arguments)}get duration(){return 0}},J=class extends B{static{a(this,"PerformanceMeasure")}entryType="measure"},Q=class extends B{static{a(this,"PerformanceResourceTiming")}entryType="resource";serverTiming=[];connectEnd=0;connectStart=0;decodedBodySize=0;domainLookupEnd=0;domainLookupStart=0;encodedBodySize=0;fetchStart=0;initiatorType="";name="";nextHopProtocol="";redirectEnd=0;redirectStart=0;requestStart=0;responseEnd=0;responseStart=0;secureConnectionStart=0;startTime=0;transferSize=0;workerStart=0;responseStatus=0},pe=class{static{a(this,"PerformanceObserverEntryList")}__unenv__=!0;getEntries(){return[]}getEntriesByName(t,r){return[]}getEntriesByType(t){return[]}},W=class{static{a(this,"Performance")}__unenv__=!0;timeOrigin=Ve;eventCounts=new Map;_entries=[];_resourceTimingBufferSize=0;navigation=void 0;timing=void 0;timerify(t,r){throw F("Performance.timerify")}get nodeTiming(){return sn}eventLoopUtilization(){return{}}markResourceTiming(){return new Q("")}onresourcetimingbufferfull=null;now(){return this.timeOrigin===Ve?We():Date.now()-this.timeOrigin}clearMarks(t){this._entries=t?this._entries.filter(r=>r.name!==t):this._entries.filter(r=>r.entryType!=="mark")}clearMeasures(t){this._entries=t?this._entries.filter(r=>r.name!==t):this._entries.filter(r=>r.entryType!=="measure")}clearResourceTimings(){this._entries=this._entries.filter(t=>t.entryType!=="resource"||t.entryType!=="navigation")}getEntries(){return this._entries}getEntriesByName(t,r){return this._entries.filter(n=>n.name===t&&(!r||n.entryType===r))}getEntriesByType(t){return this._entries.filter(r=>r.entryType===t)}mark(t,r){let n=new Xe(t,r);return this._entries.push(n),n}measure(t,r,n){let o,s;typeof r=="string"?(o=this.getEntriesByName(r,"mark")[0]?.startTime,s=this.getEntriesByName(n,"mark")[0]?.startTime):(o=Number.parseFloat(r?.start)||this.now(),s=Number.parseFloat(r?.end)||this.now());let i=new J(t,{startTime:o,detail:{start:o,end:s}});return this._entries.push(i),i}setResourceTimingBufferSize(t){this._resourceTimingBufferSize=t}addEventListener(t,r,n){throw F("Performance.addEventListener")}removeEventListener(t,r,n){throw F("Performance.removeEventListener")}dispatchEvent(t){throw F("Performance.dispatchEvent")}toJSON(){return this}},ge=class{static{a(this,"PerformanceObserver")}__unenv__=!0;static supportedEntryTypes=[];_callback=null;constructor(t){this._callback=t}takeRecords(){return[]}disconnect(){throw F("PerformanceObserver.disconnect")}observe(t){throw F("PerformanceObserver.observe")}bind(t){return t}runInAsyncScope(t,r,...n){return t.call(r,...n)}asyncId(){return 0}triggerAsyncId(){return 0}emitDestroy(){return this}},Z=globalThis.performance&&"addEventListener"in globalThis.performance?globalThis.performance:new W});var xt=me(()=>{g();Ot()});var g=me(()=>{xt();if(!("__unenv__"in Z)){let e=W.prototype;for(let t of Object.getOwnPropertyNames(e))if(t!=="constructor"&&!(t in Z)){let r=Object.getOwnPropertyDescriptor(e,t);r&&Object.defineProperty(Z,t,r)}}globalThis.performance=Z;globalThis.Performance=W;globalThis.PerformanceEntry=B;globalThis.PerformanceMark=Xe;globalThis.PerformanceMeasure=J;globalThis.PerformanceObserver=ge;globalThis.PerformanceObserverEntryList=pe;globalThis.PerformanceResourceTiming=Q});var Bt=rn(Ft=>{"use strict";g();var An=/^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;Ft.validate=function(e){if(!e||e.length>254)return!1;var t=An.test(e);if(!t)return!1;var r=e.split("@");if(r[0].length>64)return!1;var n=r[1].split(".");return!n.some(function(o){return o.length>63})}});g();g();g();g();g();g();function k(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(k,"isRecord");g();g();g();g();g();g();g();function ee(e){return typeof e=="string"?e:null}a(ee,"asString");function G(e){return k(e)?e:{}}a(G,"asRecord");g();g();var kt=new TextEncoder,he,Pt;async function un(e){return he&&Pt===e||(he=await crypto.subtle.importKey("raw",kt.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),Pt=e),he}a(un,"getSignKey");async function ye(e,t){let r=await un(t),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,kt.encode(e)));return btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}a(ye,"hmacSign");function fn(e){return k(e)&&typeof e.recipient=="string"&&(e.state==="rejected"||e.state==="reserved"||e.state==="attempt_started"||e.state==="provider_accepted"||e.state==="failed"||e.state==="outcome_unknown"||e.state==="cancelled")&&(typeof e.errorCode=="string"||e.errorCode===null)&&(typeof e.providerReference=="string"||e.providerReference===null)}a(fn,"isRecipient");function Ye(e){return k(e)&&Array.isArray(e.recipients)&&e.recipients.every(fn)}a(Ye,"hasRecipients");function mn(e){return k(e)&&typeof e.operationId=="string"&&typeof e.replay=="boolean"&&(e.accountId===void 0||typeof e.accountId=="string")&&Ye(e)}a(mn,"isAdmission");function pn(e){return k(e)&&(e.state==="claimed"||e.state==="in_progress"||e.state==="completed")&&(e.reject===void 0||typeof e.reject=="boolean")}a(pn,"isReceiptClaim");function jt(e){return k(e)&&e.ok===!0}a(jt,"isAcknowledged");var be=new TextEncoder,te=new TextDecoder,gn=5e3,we=15e3,Dt=15e3,hn=65536;async function yn(e,t){if(!t)throw new Error("Email signing key is not configured");return ye(e,t)}a(yn,"sign");async function X(e,t,r,n,o=gn){let s=new AbortController,i=Date.now()+o,l=a(async h=>{let y=i-Date.now();if(y<=0)throw s.abort(),new Error("EMAIL_ADMISSION_TIMEOUT");let b=h(),R;try{return await Promise.race([b,new Promise((E,A)=>{R=setTimeout(()=>{s.abort(),A(new Error("EMAIL_ADMISSION_TIMEOUT"))},y)})])}finally{R!==void 0&&clearTimeout(R)}},"beforeDeadline"),c=JSON.stringify(r),d=await yn(c,e.EMAIL_SIGNING_SECRET),u=await l(()=>e.API.fetch(`https://api/internal/email/actions${t}`,{method:"POST",headers:{"content-type":"application/json","x-void-internal":d},body:c,signal:s.signal}));if(!u.ok)throw u.body?.cancel().catch(()=>{}),u.status===409?new Error("IDEMPOTENCY_CONFLICT"):new Error(`EMAIL_ADMISSION_${u.status}`);let m=u.body?.getReader();if(!m)throw new Error("EMAIL_ADMISSION_EMPTY_RESPONSE");let p=new Uint8Array(hn),f=0;try{for(;;){let y=await l(()=>m.read());if(y.done)break;if(f+y.value.byteLength>p.length)throw new Error("EMAIL_ADMISSION_RESPONSE_TOO_LARGE");p.set(y.value,f),f+=y.value.byteLength}let h=JSON.parse(te.decode(p.subarray(0,f)));if(!n(h))throw new Error("EMAIL_ADMISSION_INVALID_RESPONSE");return h}finally{m.cancel().catch(()=>{});try{m.releaseLock()}catch{}}}a(X,"call");function Ut(e,t){return X(e,"/receipts/claim",t,pn)}a(Ut,"claimRelayedReceipt");function $t(e,t,r){return X(e,"/receipts/complete",{receiptId:t.receiptId,projectId:t.projectId,payloadDigest:t.payloadDigest,reject:r},jt)}a($t,"completeRelayedReceipt");function bn(e){if(wn(e)===-1)return e;let t=new Map,r=[],n=0,o=0,s=!1,i=!0,l=!0,c=a(f=>{f.byteLength!==0&&(r.push(f),n+=f.byteLength)},"append"),d=a((f,h,y)=>{c(e.subarray(o,f)),c(y),o=h,s=!0},"replace"),u=0;for(;u<e.byteLength;){let f=Lt(e,u),h=f===e.byteLength?e.byteLength:f+2;if(i){if(f===u)i=!1,l=!1;else if(l&&(Ee(e,u,f,"Date: ")||Ee(e,u,f,"Message-ID: ")))d(u,h,new Uint8Array);else if(En(e,u,f)){let y=f,b=h,R=te.decode(e.subarray(u,y));for(;e[b]===32||e[b]===9;)y=Lt(e,b),R+=` ${te.decode(e.subarray(b,y)).replace(/^[ \t]+/,"")}`,b=y===e.byteLength?e.byteLength:y+2;let E=R.replaceAll(/boundary="(=_void_(?:mixed|alternative|related)_[A-Za-z0-9_-]+)"/g,(A,w)=>{let _=t.get(w);return _||(_=`<void-boundary-${t.size}>`,t.set(w,_)),`boundary="${_}"`});E!==R&&d(u,y,be.encode(E)),u=b;continue}}else if(e[u]===45&&e[u+1]===45){let y=u+2,b=Ct(e,y,f)?te.decode(e.subarray(y,f)):void 0,R=b===void 0?void 0:t.get(b);if(R!==void 0)d(u,f,be.encode(`--${R}`)),i=!0;else if(f-y>=2&&e[f-2]===45&&e[f-1]===45&&Ct(e,y,f-2)){let E=te.decode(e.subarray(y,f-2)),A=t.get(E);A!==void 0&&d(u,f,be.encode(`--${A}--`))}}u=h}if(!s)return e;c(e.subarray(o));let m=new Uint8Array(n),p=0;for(let f of r)m.set(f,p),p+=f.byteLength;return m}a(bn,"canonicalizeVoidMime");function wn(e){for(let t=0;t+3<e.byteLength;t++)if(e[t]===13&&e[t+1]===10&&e[t+2]===13&&e[t+3]===10)return t;return-1}a(wn,"findCrlfCrlf");function Lt(e,t){let r=t;for(;r<e.byteLength;){let n=e.indexOf(13,r);if(n===-1)return e.byteLength;if(e[n+1]===10)return n;r=n+1}return e.byteLength}a(Lt,"findCrlf");function Ee(e,t,r,n){if(r-t<n.length)return!1;for(let o=0;o<n.length;o++){let s=e[t+o],i=n.charCodeAt(o);if((s>=65&&s<=90?s+32:s)!==(i|32))return!1}return!0}a(Ee,"asciiPrefixEquals");function En(e,t,r){let n="Content-Type:";if(!Ee(e,t,r,n))return!1;let o=t+n.length;for(;o<r&&(e[o]===32||e[o]===9||e[o]===11||e[o]===12);)o++;return Ee(e,o,r,"multipart/")}a(En,"isMultipartContentType");function Ct(e,t,r){if(r<=t)return!1;for(let n=t;n<r;n++){let o=e[n];if(!(o>=65&&o<=90||o>=97&&o<=122||o>=48&&o<=57||o===95||o===45||o===61))return!1}return!0}a(Ct,"isBoundaryToken");async function Re(e,t,r,n){let o=bn(n),s=be.encode(JSON.stringify({kind:e,from:t.toLowerCase(),recipients:[...new Set(r.map(l=>l.toLowerCase()))].sort()})),i=new Uint8Array(s.length+1+o.length);return i.set(s),i[s.length]=0,i.set(o,s.length+1),[...new Uint8Array(await crypto.subtle.digest("SHA-256",i))].map(l=>l.toString(16).padStart(2,"0")).join("")}a(Re,"emailPayloadDigest");function Ae(e,t,r=Dt){return X(e,"/admit",t,mn,Math.min(r,Dt))}a(Ae,"admitEmail");function re(e,t,r,n=we){return X(e,`/${encodeURIComponent(t)}/start`,{recipients:r},Ye,Math.min(n,we))}a(re,"startEmailAttempt");function P(e,t,r,n,o={},s=we){return X(e,`/${encodeURIComponent(t)}/finish`,{recipients:r,state:n,...o},Ye,Math.min(s,we))}a(P,"finishEmailAttempt");function q(e,t,r,n,o){return X(e,"/receipts",{receiptId:t,projectId:r,status:n,...o?{route:o}:{}},jt)}a(q,"recordEmailReceipt");g();g();var Rn=new Set(["abuse","bounce","noreply","postmaster","security"]);function Ht(e){return Rn.has(e)}a(Ht,"isReservedEmailSlug");var $r=on(Bt(),1);import{EmailMessage as Ur}from"cloudflare:email";g();var Gt=5e3,qt=4*1024;function _e(e){return e.token}a(_e,"leaseBearer");async function Se(e,t,r,n=Gt){if(!e.EMAIL_SIGNING_SECRET)return null;let o=new AbortController,s=Date.now()+Math.min(n,Gt),i=a(async p=>{let f=s-Date.now();if(f<=0)throw o.abort(),new Error("email credential lease timed out");let h=p(),y;try{return await Promise.race([h,new Promise((b,R)=>{y=setTimeout(()=>{o.abort(),R(new Error("email credential lease timed out"))},f)})])}finally{y!==void 0&&clearTimeout(y)}},"beforeDeadline"),l;try{let p=await ye(`email-lease-v1
|
|
2
2
|
${r}
|
|
3
|
-
${t.toLowerCase()}`,e.EMAIL_SIGNING_SECRET);l=await s(()=>e.API.fetch("https://api/internal/email/domain-credential",{method:"POST",headers:{"content-type":"application/json","x-void-internal":m},body:JSON.stringify({domain:t,projectId:r}),signal:o.signal}))}catch{return null}if(!l.ok)return l.body?.cancel().catch(()=>{}),null;let c=l.headers.get("content-length");if(c!==null&&(!/^\d+$/.test(c)||Number(c)>Ut))return l.body?.cancel().catch(()=>{}),null;let d=l.body?.getReader();if(!d)return null;let u=new Uint8Array(Ut),p=0;try{for(;;){let f=await s(()=>d.read());if(f.done)break;if(p+f.value.byteLength>u.byteLength)throw new Error("email credential lease response too large");u.set(f.value,p),p+=f.value.byteLength}if(c!==null&&p!==Number(c))return null;let m=JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(u.subarray(0,p)));return fn(m)}catch{return null}finally{d.cancel().catch(()=>{});try{d.releaseLock()}catch{}}}a(Ae,"leaseEmailDomainCredential");function fn(e){if(typeof e!="object"||e===null)return null;let t=e.kind,r=e.accountId;if(typeof r!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(r))return null;if(t==="api_token"){let n=e.token;return typeof n=="string"&&n.length>0?{kind:t,token:n,accountId:r}:null}return null}a(fn,"parseLease");g();var _e=class extends Error{static{a(this,"EmailProviderTimeoutError")}constructor(){super("email provider outcome unknown after timeout"),this.name="EmailProviderTimeoutError"}};function Ie(e=6e4){let t=Date.now()+e;return{remainingMs(r=0){return Math.max(0,t-Date.now()-r)},expired(r=0){return Date.now()>=t-r},async run(r,n=0){let o=Math.min(3e4,t-Date.now()-n);if(o<=0)throw new _e;let i=r(),s;try{return await Promise.race([i,new Promise((l,c)=>{s=setTimeout(()=>c(new _e),o)})])}finally{s!==void 0&&clearTimeout(s)}}}}a(Ie,"createEmailProviderDeadline");g();import{EmailMessage as Cn}from"cloudflare:email";g();g();g();g();var ee=class extends Error{static{a(this,"HTTPException")}res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};g();var W=Symbol();g();g();g();var $t=a((e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData(),"bufferToFormData");var pn=1e4,ve=a(e=>"headers"in e,"isRawRequest"),Bt=a(async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,o=(ve(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return o==="multipart/form-data"||o==="application/x-www-form-urlencoded"?mn(e,{all:r,dot:n}):{}},"parseBody");async function mn(e,t){if(!ve(e)&&e.bodyCache.formData)return Ht(await e.bodyCache.formData,t);let r=ve(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=$t(n,r.get("Content-Type")||"");ve(e)||(e.bodyCache.formData=o);let i=await o;return i?Ht(i,t):{}}a(mn,"parseFormData");function Ht(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,i)=>{t.all||i.endsWith("[]")?gn(r,i,o):r[i]=o}),t.dot&&Object.entries(r).forEach(([o,i])=>{o.includes(".")&&(hn(r,o,i,n),delete r[o])}),r}a(Ht,"convertFormDataToBodyData");var gn=a((e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},"handleParsingAllValues"),hn=a((e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let o=e,i=t.split(".",34);i.length>33&&Ft(),i.forEach((s,l)=>{l===i.length-1?o[s]=r:((!o[s]||typeof o[s]!="object"||Array.isArray(o[s])||o[s]instanceof File)&&(n.count++>=pn&&Ft(),o[s]=Object.create(null)),o=o[s])})},"handleParsingNestedValues"),Ft=a(()=>{throw new Error("Nesting limit exceeded")},"throwNestingLimitExceeded");g();var Ye=a(e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},"splitPath"),te=a(e=>{let{groups:t,path:r}=yn(e),n=Ye(r);return bn(n,t)},"splitRoutingPath"),yn=a(e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},"extractGroupsFromPath"),bn=a((e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},"replaceGroupMarks"),Se={},re=a((e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return Se[n]||(r[2]?Se[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:Se[n]=[e,r[1],!0]),Se[n]}return null},"getPattern"),Me=a((e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},"tryDecode");var We=a(e=>decodeURI(e.includes("%25")?e.replace(/%25/g,"%2525"):e),"decodeURIWithPreservedPercent"),Je=a(e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let i=t.indexOf("?",n),s=t.indexOf("#",n),l=i===-1?s===-1?void 0:s:s===-1?i:Math.min(i,s),c=t.slice(r,l),d=Me(c,We);if(/%(?![0-9A-Fa-f]{2})/.test(c)){let u=new URL("http://localhost");if(u.pathname=d.replace(/[\\\t\n\r]/g,encodeURIComponent),Me(u.pathname,We)!==d)return Me(c.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"),We)}return d}else if(o===63||o===35)break}return t.slice(r,n)},"getPath");var Gt=a(e=>{let t=Je(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},"getPathNoStrict"),G=a((e,t,...r)=>(r.length&&(t=G(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),"mergePath"),Te=a(e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let i=o.slice(0,-1);n+="/"+i,r.push(n)}else n+="/"+o}),r.filter((o,i,s)=>s.indexOf(o)===i)},"checkOptionalParameter"),Ne=a(e=>e.indexOf("%")!==-1?Me(e,wn):e,"tryDecodeURIComponent"),Xe=a(e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),Ne(e)),"_decodeURI"),qt=a((e,t,r)=>{let n=e.indexOf("#",8);n!==-1&&(e=e.slice(0,n));let o;if(!r&&t&&!/[%+&=]/.test(t)){let l=e.indexOf("?",8),c=l;if(c===-1)return;for(e.startsWith(t,c+1)||(c=e.indexOf(`&${t}`,c+1));c!==-1;){let d=e.charCodeAt(c+t.length+1);if(d===61||d===38||isNaN(d)){if(c>l&&/(?:^|&)[^=&]*[%+]/.test(e.slice(l+1,c)))break;if(d===61){let u=c+t.length+2,p=e.indexOf("&",u);return Xe(e.slice(u,p===-1?void 0:p))}return""}c=e.indexOf(`&${t}`,c+1)}if(o=/[%+]/.test(e),!o)return}let i=Object.create(null);o??=/[%+]/.test(e);let s=e.indexOf("?",8);for(;s!==-1;){let l=e.indexOf("&",s+1),c=e.indexOf("=",s);c>l&&l!==-1&&(c=-1);let d=e.slice(s+1,c===-1?l===-1?void 0:l:c);if(o&&(d=Xe(d)),s=l,d==="")continue;let u;c===-1?u="":(u=e.slice(c+1,l===-1?void 0:l),o&&(u=Xe(u))),r?(i[d]&&Array.isArray(i[d])||(i[d]=[]),i[d].push(u)):i[d]??=u}return t?i[t]:i},"_getQueryParam"),zt=qt,Vt=a((e,t)=>qt(e,t,!0),"getQueryParams"),wn=decodeURIComponent;var Wt=class{static{a(this,"HonoRequest")}raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#e[0][this.routeIndex]?.[1][e],r=this.#o(t);return r&&Ne(r)}#s(){let e={},t=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of t){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=Ne(n))}return e}#o(e){return this.#e[1]?this.#e[1][e]:e}query(e){return zt(this.url,e)}queries(e){return Vt(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return Bt(this,e)}#n=a(e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;for(let o in t)return t[o].then(i=>{o==="json"&&(i=JSON.stringify(i));let s=o==="formData"?void 0:r.headers.get("content-type");return new Response(i,{headers:s?{"Content-Type":s}:void 0})[e]()});return t[e]=r[e]()},"#cachedBody");json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){(this.#t??={})[e]=t}valid(e){return this.#t?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[W](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};g();var Xt={Stringify:1,BeforeStream:2,Stream:3},En=a((e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r},"raw");var Ke=a(async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let i=e.callbacks;if(!i?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let s=Promise.all(i.map(l=>l({phase:t,buffer:o,context:n}))).then(l=>Promise.all(l.filter(Boolean).map(c=>Ke(c,t,!1,n,o))).then(()=>o[0]));return r?En(await s,i):s},"resolveCallback");var Rn="text/plain; charset=UTF-8",Qe=a((e,t)=>({"Content-Type":e,...t}),"setDefaultContentType"),ne=a((e,t)=>new Response(e,t),"createResponseInstance"),Ze=class{static{a(this,"Context")}#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#d;#l;#c;#a;#u;#f;constructor(e,t){this.#t=e,t&&(this.#o=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#f=t.path,this.#u=t.matchResult)}get req(){return this.#e??=new Wt(this.#t,this.#f,this.#u),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||=ne(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=ne(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#n=e,this.finalized=!0}render=a((...e)=>(this.#l??=t=>this.html(t),this.#l(...e)),"render");setLayout=a(e=>this.#d=e,"setLayout");getLayout=a(()=>this.#d,"getLayout");setRenderer=a(e=>{this.#l=e},"setRenderer");header=a((e,t,r)=>{this.finalized&&!this.#n.bodyUsed&&(this.#n=ne(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)},"header");status=a(e=>{this.#s=e},"status");set=a((e,t)=>{this.#r??=new Map,this.#r.set(e,t)},"set");get=a(e=>this.#r?this.#r.get(e):void 0,"get");get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a;if(typeof t=="object"&&t.headers){n??=new Headers;for(let[i,s]of new Headers(t.headers))i==="set-cookie"?n.append(i,s):n.set(i,s)}if(r){if(!n){let i=0;for(let s in r)if(++i>1||typeof r[s]!="string"){n=new Headers;break}}if(n)for(let i in r){let s=r[i];if(typeof s=="string")n.set(i,s);else{n.delete(i);for(let l of s)n.append(i,l)}}}let o=typeof t=="number"?t:t?.status??this.#s;return ne(e,{status:o,headers:n??r})}newResponse=a((...e)=>this.#i(...e),"newResponse");body=a((e,t,r)=>this.#i(e,t,r),"body");text=a((e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,Qe(Rn,r)),"text");json=a((e,t,r)=>this.#i(JSON.stringify(e),t,Qe("application/json",r)),"json");html=a((e,t,r)=>{let n=a(o=>this.#i(o,t,Qe("text/html; charset=UTF-8",r)),"res");return typeof e=="object"?Ke(e,Xt.Stringify,!1,{}).then(n):n(e)},"html");redirect=a((e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)},"redirect");notFound=a(()=>(this.#c??=()=>ne(),this.#c(this)),"notFound")};g();g();g();var et=a((e,t,r)=>(n,o)=>{let i=-1;return s(0);async function s(l){if(l<=i)throw new Error("next() called multiple times");i=l;let c,d=!1,u;if(e[l]?(u=e[l][0][0],n.req.routeIndex=l):u=l===e.length&&o||void 0,u)try{c=await u(n,()=>s(l+1))}catch(p){if(p instanceof Error&&t)n.error=p,c=await t(p,n),d=!0;else throw p}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||d)&&(n.res=c),n}},"compose");g();var An=a(e=>e.req[W][0].map(([[,t]])=>t),"matchedRoutes"),Yt=a((e,t)=>An(e).at(t??e.req.routeIndex)?.path??"","routePath");g();var Jt=["get","post","put","delete","options","patch","query"],xe="Can not add a route since the matcher is already built.",Oe=class extends Error{static{a(this,"UnsupportedPathError")}};g();var Kt="__COMPOSED_HANDLER";g();var Qt=a(e=>{let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.length-t},"countTrailingSlashes"),_n=a((e,t,r)=>{if(!/[:*]/.test(t))return t.length;let n=e.req.path,o=e.req[W],i=new Set,s=0;for(let l of te(t)){if(l[0]===":"&&l.endsWith("}?"))throw new Error(`mount(): Optional regular expression parameters are not supported in "${r}".`);let c=re(l);if(c&&c!=="*"){let d=c[1];if(i.has(d))throw new Error(`mount(): Duplicate path parameter "${d}" in "${r}".`);i.add(d)}if(c&&c!=="*"&&c[2]!==!0){let d=o.length===2?o[1][o[0][e.req.routeIndex][1][c[1]]]:o[0][e.req.routeIndex][1][c[1]];s+=d.length+1}else if(c||l.endsWith("*")){let d=n.indexOf("/",s+1);s=d===-1?n.length:d}else s+=l.length+1}return s},"getPathPrefixLength"),Zt=a((e,t,r)=>{if(/[^/]\*$/.test(r))throw new Error(`mount(): Wildcard must follow "/" in "${r}".`);let n=_n(e,t,r),o=e.req.path.slice(n)||"/";if(n>e.req.path.length||o[0]!=="/"||/\/(?:\.|%2e){1,2}(?:\/|$)/i.test(o))throw new ee(400,{message:"Invalid mounted path"});let i=e.req.raw.url;if(/^[^/?#]*\/\/[^/?#\\]*[?#\\]/.test(i))throw new ee(400,{message:"Invalid mounted path"});let s=i.search(/[?#]/),l=Qt(s===-1?i:i.slice(0,s));if(l>1&&Qt(e.req.path)===l-1)throw new ee(400,{message:"Invalid mounted path"});let c=new URL(i);return c.pathname=o.replace(/[\\\t\n\r]/g,encodeURIComponent),o.includes("%"),new Request(c,e.req.raw)},"createMountedRequest");var In=a(e=>e.text("404 Not Found",404),"notFoundHandler"),er=a((e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},"errorHandler"),tr=class rr{static{a(this,"Hono")}get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Jt,"all"].forEach(o=>{this[o]=(i,...s)=>{let l=o.toUpperCase();return typeof i=="string"?this.#t=i:this.#s(l,this.#t,i),s.forEach(c=>{this.#s(l,this.#t,c)}),this}}),this.on=(o,i,...s)=>{for(let l of[i].flat()){this.#t=l;for(let c of[o].flat()){let d=c.toUpperCase();for(let u of s)this.#s(d,this.#t,u)}}return this},this.use=(o,...i)=>(typeof o=="string"?this.#t=o:(this.#t="*",i.unshift(o)),i.forEach(s=>{this.#s("ALL",this.#t,s)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??Je:Gt}#e(){let t=new rr({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=In;errorHandler=er;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let i;r.errorHandler===er?i=o.handler:(i=a(async(s,l)=>(await et([],r.errorHandler)(s,()=>o.handler(s,l))).res,"handler"),i[Kt]=o.handler),n.#s(o.method,o.path,i,o.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=G(this._basePath,t),r}onError=a(t=>(this.errorHandler=t,this),"onError");notFound=a(t=>(this.#r=t,this),"notFound");mount(t,r,n){let o,i;n&&(typeof n=="function"?i=n:(i=n.optionHandler,n.replaceRequest===!1?o=a(d=>d,"replaceRequest"):o=n.replaceRequest));let s=i?d=>{let u=i(d);return Array.isArray(u)?u:[u]}:d=>{let u;try{u=d.executionCtx}catch{}return[d.env,u]},l=a(d=>{let u=Yt(d);return Zt(d,u.replace(/\/?\*$/,""),u)},"defaultReplaceRequest"),c=a(async(d,u)=>{let p=await r(o?o(d.req.raw):l(d),...s(d));if(p)return p;await u()},"handler");return this.#s("ALL",G(t,"*"),c),this}#s(t,r,n,o){r=G(this._basePath,r);let i={basePath:o!==void 0?G(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,i]),this.routes.push(i)}#o(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let i=this.getPath(t,{env:n}),s=this.router.match(o,i),l=new Ze(t,{path:i,matchResult:s,env:n,executionCtx:r,notFoundHandler:this.#r});if(s[0].length===1){let d;try{d=s[0][0][0][0](l,async()=>{l.res=await this.#r(l)})}catch(u){return this.#o(u,l)}return d instanceof Promise?d.then(u=>u||(l.finalized?l.res:this.#r(l))).catch(u=>this.#o(u,l)):d??this.#r(l)}let c=et(s[0],this.errorHandler,this.#r);return(async()=>{try{let d=await c(l);if(!d.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return d.res}catch(d){return this.#o(d,l)}})()}fetch=a((t,...r)=>this.#n(t,r[1],r[0],t.method),"fetch");request=a((t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${G("/",t)}`,r),n,o)),"request");fire=a(()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})},"fire")};g();g();var x=a(()=>Object.create(null),"createNullObject");g();var tt=[];function nr(e,t){let r=this.buildAllMatchers(),n=a(((o,i)=>{let s=r[o]||r.ALL,l=s[2][i];if(l)return l;let c=i.match(s[0]);if(!c)return[[],tt];let d=c.indexOf("",1);return[s[1][d],c]}),"match");return this.match=n,n(e,t)}a(nr,"match");g();var vn="[^/]+",Sn="[^]*",Mn="(?:|/[^]*)",C=Symbol(),or=new Set(".\\+*[^]$()");function Tn(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e==="[^]*"||e==="(?:|/[^]*)"?t==="[^]*"?-1:1:t==="[^]*"||t==="(?:|/[^]*)"?-1:e==="[^/]+"?1:t==="[^/]+"?-1:e.length===t.length?e<t?-1:1:t.length-e.length}a(Tn,"compareKey");var sr=class rt{static{a(this,"Node")}#t;#e;#r=x();insert(t,r,n,o,i){let s=this;for(let l=0,c=t.length;l<c;l++){let d=t[l],u=d.length===1?d==="*"?l===c-1?["","",Sn]:["","",vn]:null:d==="/*"?["","",Mn]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),p;if(u){let m=u[1],f=u[2]||"[^/]+";if(m&&u[2]&&(new RegExp(f).test("")||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))||f.length===1&&or.has(f)))throw C;if(i.push(f),p=s.#r[f],!p){if(f!=="[^]*"&&f!=="(?:|/[^]*)"){for(let h in s.#r)if((f.length>1||h.length>1)&&h!=="[^]*"&&h!=="(?:|/[^]*)")throw C}p=s.#r[f]=new rt}m!==""&&(p.#e??=o.varIndex++,n.push([m,p.#e]))}else if(i.push(d),p=s.#r[d],!p){for(let m in s.#r)if(m.length>1&&m!=="[^]*"&&m!=="(?:|/[^]*)")throw C;p=s.#r[d]=new rt}s=p}if(s.#t!==void 0)throw C;s.#t=r}buildRegExpStr(){let t=Object.keys(this.#r).sort(Tn).map(r=>{let n=this.#r[r],o=n.buildRegExpStr();return o===""?"":(typeof n.#e=="number"?`(${r})@${n.#e}`:or.has(r)?`\\${r}`:r)+o}).filter(Boolean);return typeof this.#t=="number"&&this.#t!==-1&&t.unshift(`#${this.#t}`),t.length===0?"":t.length===1?t[0]:"(?:"+t.join("|")+")"}};g();var nt=class{static{a(this,"Trie")}#t={varIndex:0};#e=new sr;#r=0;paths=x();insert(e,t){let r=[];if(t){this.#e.insert(e.split(""),-1,[],this.#t,r),this.paths[e]=[-1,[],r];return}let n=[],o=[],i=e;for(let l=0;;){let c=!1;if(i=i.replace(/\{(?:\{[\d,]+\}|[^}])+\}/g,d=>{let u=`@\\${l}`;return o[l]=[u,d],l++,c=!0,u}),!c)break}let s=i.match(/(?::[^\/]+)|(?:\/\*$)|./gs)||[];for(let l=o.length-1;l>=0;l--){let[c]=o[l];for(let d=s.length-1;d>=0;d--)if(s[d].indexOf(c)!==-1){s[d]=s[d].replace(c,o[l][1]);break}}this.#e.insert(s,this.#r,n,this.#t,r),this.paths[e]=[this.#r++,n,r]}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,i,s)=>i!==void 0?(r[++t]=Number(i),"$()"):(s!==void 0&&(n[Number(s)]=++t),"")),[new RegExp(`^${e}`),r,n]}};function Nn(e){let t=e[e.length-1];return t==="[^]*"||t==="(?:|/[^]*)"}a(Nn,"endsWithWildcard");function xn(e,t){let r=e.length-1;for(let n=0;n<r;n++)if(e[n]!==t[n])return!1;return e[r]==="[^]*"||t.length===r||t[r]==="/"}a(xn,"covers");var ir=class{static{a(this,"RegExpRouter")}name="RegExpRouter";#t;#e;constructor(){this.#t={ALL:[]},this.#e={ALL:new nt}}#r(e,t){try{this.#e[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===C?new Oe(t):r}}add(e,t,r){let n=this.#t;if(!n)throw new Error(xe);let o=this.#e;if(!n[e]){o[e]=new nt,n[e]=[...n.ALL];for(let l in o.ALL.paths)this.#r(e,l)}t==="/*"&&(t="*");let i=e==="ALL"?Object.keys(n):[e],s=Te(t)||[t];for(let l of s)for(let c of i)o[c].paths[l]||this.#r(c,l),n[c].push([r,l])}match=nr;buildAllMatchers(){let e=x();for(let t of Object.keys(this.#t))e[t]=this.#s(t);return this.#t=this.#e=void 0,e}#s(e){let t=this.#t[e],r=this.#e[e],n=x(),o=[],[i,s,l]=r.buildRegExp(),c=x(),d=t.map(([p,m],f)=>((c[m]??=[]).push(f),[p,r.paths[m][1].reduceRight((h,[y,b])=>(h[y]=l[b],h),x())])),u=Object.keys(c).filter(p=>Nn(r.paths[p][2]));for(let p in r.paths){let[m,,f]=r.paths[p],h=[...c[p]];for(let b of u)b!==p&&xn(r.paths[b][2],f)&&h.push(...c[b]);let y=h.sort((b,R)=>b-R).map(b=>d[b]);if(m===-1){let b=Math.max(-1,...y.flatMap(([,R])=>Object.values(R)));n[p]=[y,b===-1?tt:p.match(i).slice(0,b+1)]}else o[m]=y}return[i,s.map(p=>o[p]),n]}};g();var ar=class{static{a(this,"SmartRouter")}name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(xe);this.#e.push([e,t,r])}match(e,t){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 l=r[i];try{for(let c=0,d=n.length;c<d;c++)l.add(...n[c]);s=l.match(e,t)}catch(c){if(c instanceof Oe)continue;throw c}this.match=l.match.bind(l),this.#t=[l],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]}};g();g();var ot=x(),On=0,lr=class cr{static{a(this,"Node")}#t=[];#e=x();#r=[];#s;#o=ot;insert(t,r,n){let o=this,i=te(r),s=new Set,l=0;for(let c of i){let d=i[++l],u=re(c,d)||(d===void 0&&c&&c.indexOf("*")===c.length-1?c:null),p=Array.isArray(u),m=p?u[0]:u||c,f=o.#e[m]||=new cr;u&&!f.#s&&(f.#s=u,o.#r.push(f)),o=f,p&&s.add(u[1])}o.#t.push({[t]:{handler:n,possibleKeys:[...s],score:++On}})}#n(t,r,n,o,i){for(let s=0,l=r.#t.length;s<l;s++){let c=r.#t[s],d=c[n]||c.ALL;if(d){d.params=x(),t.push(d);for(let u=0,p=d.possibleKeys.length;u<p;u++){let m=d.possibleKeys[u];d.params[m]=i?.[m]&&!u?i[m]:o[m]??i?.[m]}}}}search(t,r){let n=[];this.#o=ot;let o=[this],i=Ye(r),s=[],l=i.length,c=null;for(let d=0;d<l;d++){let u=i[d],p=d===l-1,m=[];for(let h=0,y=o.length;h<y;h++){let b=o[h],R=b.#e[u];R&&(R.#o=b.#o,p?(R.#e["*"]&&this.#n(n,R.#e["*"],t,b.#o),this.#n(n,R,t,b.#o)):m.push(R));for(let E of b.#r){let A=E.#s,w=b.#o===ot?{}:{...b.#o};if(typeof A=="string"){(A==="*"||u.startsWith(A.slice(0,-1)))&&(this.#n(n,E,t,b.#o),A==="*"&&(E.#o=w,m.push(E)));continue}let[,_,S]=A;if(!(!u&&S===!0)){if(S!==!0){if(!c){c=[];let N=r[0]==="/"?1:0;for(let P=0;P<l;P++)c[P]=N,N+=i[P].length+1}let O=r.slice(c[d]),T=S.exec(O);if(T){Object.hasOwn(w,_)||(w[_]=T[0]),this.#n(n,E,t,b.#o,w),T[0].length===O.length&&E.#e["*"]&&this.#n(n,E.#e["*"],t,b.#o,w);for(let N in E.#e){E.#o=w;let P=T[0].match(/\//g)?.length??0;(s[P]||=[]).push(E);break}continue}}(S===!0||S.test(u))&&(Object.hasOwn(w,_)||(w[_]=u),p?(this.#n(n,E,t,w,b.#o),E.#e["*"]&&this.#n(n,E.#e["*"],t,w,b.#o)):(E.#o=w,m.push(E)))}}}let f=s.shift();o=f?m.concat(f):m}return n[1]&&n.sort((d,u)=>d.score-u.score),[n.map(({handler:d,params:u})=>[d,u])]}};var st=class{static{a(this,"TrieRouter")}name="TrieRouter";#t=new lr;add(e,t,r){for(let n of Te(t)||[t])this.#t.insert(e,n,r)}match(e,t){return this.#t.search(e,t)}};g();var it=class extends tr{static{a(this,"Hono")}constructor(e={}){super(e),this.router=e.router??new ar({routers:[new ir,new st]})}};g();g();g();g();g();g();g();g();g();g();g();g();function oe(e){return typeof e=="string"?e:null}a(oe,"asString");var jn=new it,Un=5e4,q=5e3,ke=5*1024*1024,$n=16*1024,Hn=new Set(["from","to","cc","bcc","subject","reply-to","date","message-id","in-reply-to","references","mime-version","content-type","content-transfer-encoding","content-disposition"]);function Fn(e){let t=0,r=!1;for(let n=0;n<e.byteLength;){let o=n;for(;o<e.byteLength&&e[o]!==10;)o++;let i=o>n&&e[o-1]===13?o-1:o;if(i===n)return!0;if(e[n]!==32&&e[n]!==9){let s=n;for(;s<i&&e[s]!==58;)s++;let l=new TextDecoder().decode(e.subarray(n,s)).toLowerCase();r=s<i&&!Hn.has(l)}if(r&&(t+=i-n+2,t>$n))return!1;n=o+1}return!0}a(Fn,"customMimeHeaderBytesWithinLimit");var ur=50,fr=320,pr=320;function se(e){let t=e.EMAIL_SENDER_DOMAIN;if(typeof t!="string")return null;let r=t.trim().toLowerCase();return r.length>0?r:null}a(se,"readSenderDomain");var Bn=/[.*+?^${}()|[\]\\]/g;function Gn(e){return e.replace(Bn,"\\$&")}a(Gn,"escapeRegExp");var mr=new Map;function qn(e){let t=mr.get(e);if(t)return t;let r=new RegExp(`^[a-z0-9._-]+(?:\\+[a-z0-9._=/-]+)*@${Gn(e)}$`);return mr.set(e,r),r}a(qn,"strictFromRe");var zn=new RegExp("[\\u0000-\\u001f\\u007f]+","g");function I(e,t=200){return e.slice(0,t).replace(zn," ")}a(I,"sanitizeForLog");var Vn=128;function ie(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}a(ie,"bytesToStream");var gr=10,Pe=13,yr=32,br=9,Wn=58,De=[102,114,111,109];function Xn(e,t,r){if(r-t<=De.length)return-1;for(let o=0;o<De.length;o++)if((e[t+o]|32)!==De[o])return-1;let n=t+De.length;for(;n<r&&(e[n]===yr||e[n]===br);)n++;return n<r&&e[n]===Wn?n+1:-1}a(Xn,"fromValueStart");var Yn={missing:"the message has no From header",multiple:"the message has more than one From header",malformed:"the From header must hold a single mailbox"};function ct(e){let t=e.byteLength,r=0,n=-1,o=-1,i=!1,s=!1,l=e.indexOf(Pe),c=0;for(;c<t;){let p=e.indexOf(gr,c),f=p===-1?t:p;if(f>c&&e[f-1]===Pe&&f--,f===c)break;if(l!==-1&&l<c&&(l=e.indexOf(Pe,c)),l!==-1&&l<f)return{ok:!1,reason:"malformed"};if(e[c]===yr||e[c]===br)s&&(o=f,i=!0);else{let h=Xn(e,c,f);s=h!==-1,s&&(r++,n=h,o=f,i=!1)}c=p===-1?t:p+1}if(r===0)return{ok:!1,reason:"missing"};if(r>1)return{ok:!1,reason:"multiple"};let d=e.subarray(n,o);if(i){d=e.slice(n,o);let p=0;for(let m=0;m<d.length;m++){let f=d[m];f!==Pe&&f!==gr&&(d[p++]=f)}d=d.subarray(0,p)}let u=Jn(new TextDecoder().decode(d));return u===null?{ok:!1,reason:"malformed"}:{ok:!0,addrSpec:u}}a(ct,"readMimeFromAddrSpec");function Jn(e){let t=!1,r=!1,n=-1,o=-1,i=-1;for(let l=0;l<e.length;l++){let c=e[l];if(t){r?r=!1:c==="\\"?r=!0:c==='"'&&(t=!1);continue}switch(c){case'"':if(n!==-1)return null;t=!0;break;case"<":if(n!==-1)return null;n=l;break;case">":if(n===-1||o!==-1)return null;o=l;break;case"@":i===-1&&(i=l);break;case",":case";":case":":case"(":case")":case"[":case"]":case"\\":return null;default:break}}if(t)return null;let s;if(n===-1)s=e.trim();else{if(o===-1||e.slice(o+1).trim().length!==0||i!==-1&&i<n)return null;s=e.slice(n+1,o)}return/^[\x21-\x7e]+$/.test(s)?s:null}a(Jn,"singleMailboxAddrSpec");jn.post("/send",async e=>{let t=Ie(Un),r=e.get("projectId"),n=e.get("body"),o=oe(n.from),i=oe(n.mimeBase64),s=oe(n.requestId),l=s===null?"unknown":I(s,Vn),c=oe(n.idempotencyKey);if(c!==null&&(c.length===0||c.length>128||!/^[\x20-\x7e]+$/.test(c)))return e.json({ok:!1,error:{code:"INVALID_TO",message:"invalid idempotency key"}},400);let d=c??(s&&s.length<=128&&/^[\x20-\x7e]+$/.test(s)?s:crypto.randomUUID()),u=Array.isArray(n.recipients)?n.recipients:null;if(!o||!i||!u)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"invalid body"}},400);if(u.length>ur)return e.json({ok:!1,error:{code:"INVALID_TO",message:`too many recipients (max ${ur}, got ${u.length})`}},413);if(o.length>pr)return e.json({ok:!1,error:{code:"INVALID_FROM",message:`sender exceeds ${pr} characters`}},413);let p=se(e.env);if(!p)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"email sender domain is not configured"}},502);let m=[],f=new Set;for(let v of u){if(typeof v!="string")continue;if(v.length>fr)return e.json({ok:!1,error:{code:"INVALID_TO",message:`recipient exceeds ${fr} characters`}},413);let M=v.trim().toLowerCase();!M||f.has(M)||(f.add(M),m.push(M))}if(m.length===0)return e.json({ok:!1,error:{code:"INVALID_TO",message:"no recipients"}},200);if(i.length>Math.ceil(ke*4/3)+4)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${ke} bytes (base64 length ${i.length})`}},413);let h;try{h=Qn(i)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"invalid base64 mime"}},400)}if(h.byteLength>ke)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${ke} bytes (got ${h.byteLength})`}},413);if(!Fn(h))return e.json({ok:!1,error:{code:"MIME_ERROR",message:"custom headers exceed the 16 KiB limit"}},413);let y=o.indexOf("@"),b=y===-1?"":o.slice(y+1).toLowerCase();if(b!==""&&b!==p)return Kn(e,r,o,b,p,m,h,l,d,t);let R=e.env.SEND_EMAIL;if(typeof R?.send!="function")return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"email sending is not configured"}},502);let E=o.split("@")[0]?.split("+")[0]??"";if(!/^[\x21-\x7e]+$/.test(o))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let A=o.toLowerCase();if(!qn(p).test(A))return e.json({ok:!1,error:{code:"INVALID_FROM",message:`from address must be <${E}>[+tag]@${p}`}},200);if((A.slice(0,A.indexOf("@")).split("+")[0]??"")!==E.toLowerCase())return e.json({ok:!1,error:{code:"INVALID_FROM",message:`from address must be <${E}>[+tag]@${p}`}},200);let S=Er(e,h,o);if(S)return S;let O=await Rr(e,t,{projectId:r,operationKey:d,from:o,recipients:m,raw:h,transport:"binding"});if(O instanceof Response)return O;let{admission:T,deliveries:N}=O,P=T.recipients.filter(v=>v.state==="reserved").map(v=>v.recipient);for(let v=0;v<P.length;v++){let M=P[v];if(t.expired(q)){let $=P.slice(v),X=await at(e.env,T.operationId,$,t.remainingMs());for(let de of $)N.push({recipient:de,ok:!1,state:X?"cancelled":"outcome_unknown",error:X?{code:"UPSTREAM_ERROR",message:"email batch deadline elapsed before provider submission"}:{code:"OUTCOME_UNKNOWN",message:"could not cancel unstarted email attempt"}});break}try{await Z(e.env,T.operationId,[M],t.remainingMs(q))}catch{let $=await at(e.env,T.operationId,[M],t.remainingMs());N.push({recipient:M,ok:!1,state:$?"cancelled":"outcome_unknown",error:$?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});continue}try{let $=new Cn(o,M,ie(h)),X=await t.run(()=>R.send($),q),de=typeof X?.messageId=="string"?X.messageId:"";try{await k(e.env,T.operationId,[M],"provider_accepted",{providerReference:de},t.remainingMs())}catch{N.push({recipient:M,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider accepted email but outcome could not be recorded"}});continue}N.push({recipient:M,ok:!0,state:"provider_accepted",messageId:de})}catch{try{await k(e.env,T.operationId,[M],"outcome_unknown",{errorCode:"OUTCOME_UNKNOWN"},t.remainingMs())}catch{}N.push({recipient:M,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"}})}}return Ar(r,l,N),N.some(v=>!v.ok)?e.json({ok:!1,operationId:T.operationId,deliveries:N},200):e.json({ok:!0,operationId:T.operationId,ids:N.map(v=>({recipient:v.recipient,messageId:v.messageId,state:"provider_accepted"}))})});var hr=64*1024;async function dt(e,t=3e4){let r=new AbortController,n=Date.now()+Math.min(3e4,t),o=JSON.stringify({from:e.from,recipients:e.recipients,mime_message:e.mimeMessage}),i=a(async p=>{let m=n-Date.now();if(m<=0)throw r.abort(),new Error("email sending request timed out");let f=p(),h;try{return await Promise.race([f,new Promise((y,b)=>{h=setTimeout(()=>{r.abort(),b(new Error("email sending request timed out"))},m)})])}finally{h!==void 0&&clearTimeout(h)}},"beforeDeadline"),s=await i(()=>fetch(`https://api.cloudflare.com/client/v4/accounts/${e.accountId}/email/sending/send_raw`,{method:"POST",headers:{authorization:`Bearer ${e.bearer}`,"content-type":"application/json"},body:o,signal:r.signal}));if(!s.ok)return s.body?.cancel().catch(()=>{}),{ok:!1,status:s.status};let l=s.headers.get("content-length");if(l!==null&&(!/^\d+$/.test(l)||Number(l)>hr))throw s.body?.cancel().catch(()=>{}),new Error("email sending API response too large");let c=s.body?.getReader();if(!c)throw new Error("email sending API response unreadable");let d=new Uint8Array(hr),u=0;try{for(;;){let p=await i(()=>c.read());if(p.done)break;if(u+p.value.byteLength>d.byteLength)throw new Error("email sending API response too large");d.set(p.value,u),u+=p.value.byteLength}if(l!==null&&u!==Number(l))throw new Error("email sending API response length mismatch");return{ok:!0,data:JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(d.subarray(0,u)))}}finally{c.cancel().catch(()=>{});try{c.releaseLock()}catch{}}}a(dt,"requestSendRaw");function Le(e){if(!Array.isArray(e))return null;let t=new Set;for(let r of e){if(typeof r!="string")return null;t.add(r.toLowerCase())}return t}a(Le,"readSendRawAddressList");function ut(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=Le(t.delivered),n=Le(t.permanent_bounces),o=Le(t.queued),i=Le(t.suppressed_recipients);return!r||!n||!o||!i||typeof t.message_id!="string"||t.message_id===""?null:{delivered:r,messageId:t.message_id,permanentBounces:n,queued:o,suppressedRecipients:i}}a(ut,"parseSendRawResult");function ft(e,t){let r=t.toLowerCase(),n=[e.delivered.has(r),e.queued.has(r),e.permanentBounces.has(r),e.suppressedRecipients.has(r)];return n.filter(Boolean).length!==1?"outcome_unknown":n[0]||n[1]?"provider_accepted":n[2]?"permanent_bounce":"suppressed"}a(ft,"classifySendRawRecipient");async function Kn(e,t,r,n,o,i,s,l,c,d){if(!/^[\x21-\x7e]+$/.test(r))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let u=Er(e,s,r);if(u)return u;let p;try{p=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(s)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"mime must be valid UTF-8"}},400)}let m=await Rr(e,d,{projectId:t,operationKey:c,from:r,recipients:i,raw:s,transport:"send_raw"});if(m instanceof Response)return m;let{admission:f,deliveries:h}=m;if(i=f.recipients.filter(w=>w.state==="reserved").map(w=>w.recipient),i.length===0)return lt(e,f.operationId,h);let y=await Ae(e.env,n,t,d.remainingMs(q));if(!y)return await k(e.env,f.operationId,i,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"could not lease the domain credential"}},502);if(f.accountId!==y.accountId)return await k(e.env,f.operationId,i,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"email domain changed during admission"}},503);try{await Z(e.env,f.operationId,i,d.remainingMs(q))}catch{let w=await at(e.env,f.operationId,i,d.remainingMs());for(let _ of i)h.push({recipient:_,ok:!1,state:w?"cancelled":"outcome_unknown",error:w?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});return lt(e,f.operationId,h)}let b=null,R="failed",E=null,A=null;try{A=await dt({accountId:y.accountId,bearer:Re(y),from:r,recipients:i,mimeMessage:p},d.remainingMs(q))}catch{b={code:"UPSTREAM_ERROR",message:"email sending request failed"},R="outcome_unknown"}if(A)if(!A.ok)b={code:A.status===429?"QUOTA_EXCEEDED":"UPSTREAM_ERROR",message:`email sending API returned ${A.status}`},R=A.status>=500||A.status===408?"outcome_unknown":"failed";else{let w=A.data,_=typeof w=="object"&&w!==null?w.success:void 0;_===!1?b={code:"UPSTREAM_ERROR",message:"email sending API refused the message"}:_!==!0?(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"):(E=ut(w.result),E||(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"))}for(let w of i){if(b){h.push({recipient:w,ok:!1,state:R,error:b});continue}let _=ft(E,w);_==="permanent_bounce"?h.push({recipient:w,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${w}' permanently bounced`}}):_==="suppressed"?h.push({recipient:w,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${w}' is on the suppression list`}}):_==="outcome_unknown"?h.push({recipient:w,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"email sending API did not classify the recipient"}}):h.push({recipient:w,ok:!0,state:"provider_accepted",messageId:E.messageId})}for(let w of h.filter(_=>f.recipients.some(S=>S.recipient===_.recipient&&S.state==="reserved")))try{await k(e.env,f.operationId,[w.recipient],w.ok?"provider_accepted":w.state==="outcome_unknown"?"outcome_unknown":"failed",{providerReference:w.messageId,errorCode:w.ok?void 0:w.state==="outcome_unknown"?"OUTCOME_UNKNOWN":b?.code??w.error?.code},d.remainingMs()),w.state=w.ok?"provider_accepted":w.state==="outcome_unknown"?"outcome_unknown":"failed",w.state==="outcome_unknown"&&!w.ok&&(w.error={code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"})}catch{w.ok=!1,w.state="outcome_unknown",w.error={code:"OUTCOME_UNKNOWN",message:"provider outcome could not be recorded"}}return Ar(t,l,h),h.some(w=>!w.ok)?e.json({ok:!1,operationId:f.operationId,deliveries:h},200):e.json({ok:!0,operationId:f.operationId,ids:h.map(w=>({recipient:w.recipient,messageId:w.messageId,state:"provider_accepted"}))})}a(Kn,"sendViaCustomDomain");async function wr(e,t){console.log(`[email-recv] ${e} ${I(t.from,320)} -> ${I(t.to,320)} ${t.status} (${t.byteSize}B) @${Date.now()}`)}a(wr,"recordInboundDelivery");function Er(e,t,r){let n=ct(t);if(n.ok&&n.addrSpec.toLowerCase()===r.toLowerCase())return null;let o=n.ok?"the From header address does not match the envelope sender":Yn[n.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${r}: ${o}`}},403)}a(Er,"refuseMimeFromMismatch");async function Rr(e,t,r){let{projectId:n,operationKey:o,from:i,recipients:s,raw:l,transport:c}=r,d;try{d=await Ee(e.env,{projectId:n,kind:"direct",key:o,digest:await we("direct",i,s,l),from:i,recipients:s,transport:c},t.remainingMs(q))}catch(p){let m=p instanceof Error&&p.message==="IDEMPOTENCY_CONFLICT";return e.json({ok:!1,error:{code:m?"IDEMPOTENCY_CONFLICT":"UPSTREAM_ERROR",message:m?"idempotency key has different content":"email admission unavailable"}},m?409:503)}let u=d.recipients.filter(p=>p.state!=="reserved").map(p=>({recipient:p.recipient,ok:p.state==="provider_accepted",state:p.state,messageId:p.providerReference??void 0,error:p.state==="provider_accepted"?void 0:{code:p.errorCode??(p.state==="outcome_unknown"||p.state==="attempt_started"?"OUTCOME_UNKNOWN":p.state==="cancelled"?"UPSTREAM_ERROR":"UNVERIFIED_DESTINATION"),message:p.state==="outcome_unknown"||p.state==="attempt_started"?"provider outcome unknown; inspect email logs before retrying":p.state==="cancelled"?"email attempt was cancelled before provider submission":"recipient was not admitted"}}));if(d.replay){for(let p of d.recipients.filter(m=>m.state==="reserved"))u.push({recipient:p.recipient,ok:!1,state:"reserved",error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved; inspect email logs before retrying"}});return lt(e,d.operationId,u)}return{admission:d,deliveries:u}}a(Rr,"admitDirectSend");async function at(e,t,r,n){try{let o=await k(e,t,r,"cancelled",{},n);return r.every(i=>o.recipients.some(s=>s.recipient===i&&s.state==="cancelled"))}catch{return!1}}a(at,"cancelUnstartedRecipients");function lt(e,t,r){return r.length===0?e.json({ok:!1,operationId:t,error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved"}},200):r.some(n=>!n.ok)?e.json({ok:!1,operationId:t,deliveries:r},200):e.json({ok:!0,operationId:t,ids:r.map(n=>({recipient:n.recipient,messageId:n.messageId??"",state:n.state}))},200)}a(lt,"emailActionResponse");function Ar(e,t,r){for(let n of r){let o=n.ok?"sent":n.error?.code??"unknown_error",i=n.messageId??"";console.log(`[email-log] ${e} ${t} ${I(n.recipient,320)} ${o} ${i} @${Date.now()}`)}}a(Ar,"logSend");function Qn(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}a(Qn,"base64Decode");g();g();var Ir="/__void/email/receipt/v1";var pt=new TextEncoder,Zn=new TextDecoder("utf-8",{fatal:!0});function eo(e,t,r){let n=0,o=0,i=!1,s=!1;for(let l of e)if(i)s?s=!1:l===92?s=!0:l===34&&(i=!1);else if(l===34)i=!0;else if(l===123||l===91){if(++n>t)throw new Error("email metadata too deep")}else if(l===125||l===93){if(--n<0)throw new Error("invalid email metadata")}else if(l===58&&++o>r)throw new Error("too many email metadata fields");if(i||n!==0)throw new Error("invalid email metadata")}a(eo,"assertFlatJson");function vr(e){let t=pt.encode(JSON.stringify({from:e.from,to:e.to,headers:e.headers,rawSize:e.rawSize,...e.viaDomain?{viaDomain:e.viaDomain}:{}}));if(t.byteLength>131072||e.raw.byteLength>10485760)throw new Error("email envelope too large");let r=new Uint8Array(4+t.byteLength+e.raw.byteLength);return new DataView(r.buffer).setUint32(0,t.byteLength),r.set(t,4),r.set(e.raw,4+t.byteLength),r}a(vr,"encodeEmailEnvelope");function _r(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}a(_r,"base64url");async function to(e,t){if(!e)throw new Error("Email signing key is not configured");return crypto.subtle.importKey("raw",pt.encode(e),{name:"HMAC",hash:"SHA-256"},!1,[t])}a(to,"receiptKey");async function Sr(e,t){let r=pt.encode(JSON.stringify(e)),n=new Uint8Array(await crypto.subtle.sign("HMAC",await to(t,"sign"),r));return`${_r(r)}.${_r(n)}`}a(Sr,"signEmailReceipt");async function Mr(e,t=15e3){return no(e,async r=>{let n=[],o=new Uint8Array(0),i=0,s=Date.now()+t,l=a(()=>ro(r,s,"email response timeout"),"readChunk");async function c(d){let u=new Uint8Array(d),p=0;for(;p<d;){if(o.byteLength===0){let f=await l();if(f.done)throw new Error("truncated email response");if(i+=f.value.byteLength,i>8388608)throw new Error("email response too large");o=f.value}let m=Math.min(o.byteLength,d-p);u.set(o.subarray(0,m),p),o=o.subarray(m),p+=m}return u}for(a(c,"exact");;){let d=await c(5),u=new DataView(d.buffer).getUint32(0),p=d[4];if(p===0){if(u!==0||o.byteLength!==0)throw new Error("invalid email response tail");if(!(await l()).done)throw new Error("invalid email response tail");if(n.some(y=>y.type==="reject")&&n.length!==1)throw new Error("email reject cannot accompany delivery actions");return n}if(p!==1||u>8192||n.length>=100)throw new Error("invalid email action frame");let m=await c(u);eo(m,2,40);let f=JSON.parse(Zn.decode(m));if(!f||typeof f!="object"||Array.isArray(f))throw new Error("invalid email action");let h=f;if(h.type==="reply"){if(typeof h.from!="string"||typeof h.to!="string"||Object.keys(h).length!==3)throw new Error("invalid email reply");let y=await c(5),b=new DataView(y.buffer).getUint32(0);if(y[4]!==2||b>5242880)throw new Error("invalid email reply frame");n.push({type:"reply",from:h.from,to:h.to,raw:await c(b)})}else if(h.type==="forward"){if(typeof h.to!="string"||Object.keys(h).length>3||h.headers!==void 0&&(typeof h.headers!="object"||h.headers===null||Array.isArray(h.headers)))throw new Error("invalid email forward");let y=h.headers;if(y&&(Object.keys(y).length>32||Object.values(y).some(b=>typeof b!="string")))throw new Error("invalid email headers");n.push({type:"forward",to:h.to,...y?{headers:y}:{}})}else if(h.type==="reject"){if(typeof h.reason!="string"||Object.keys(h).length!==2)throw new Error("invalid email reject");n.push({type:"reject",reason:h.reason})}else throw new Error("unknown email action")}})}a(Mr,"readEmailActions");async function ro(e,t,r){let n=t-Date.now();if(n<=0)throw new Error(r);let o;return Promise.race([e.read(),new Promise((i,s)=>{o=setTimeout(()=>s(new Error(r)),n)})]).finally(()=>{o!==void 0&&clearTimeout(o)})}a(ro,"readBeforeDeadline");async function no(e,t){let r=e.getReader();try{return await t(r)}catch(n){throw r.cancel().catch(()=>{}),n}finally{try{r.releaseLock()}catch{}}}a(no,"withReader");var oo=8,so=2e4,io=15e3,ae=new Map;async function mt(e,t,r){if(!r.deploymentId||!r.projectId)throw new Error("email deployment identity missing");let n=r.receiptId;if(!/^[a-f0-9-]{16,64}$/.test(n))throw new Error("invalid email receipt ID");let o=ae.get(r.projectId)??0;if(o>=oo)throw new Error("email project concurrency exceeded");ae.set(r.projectId,o+1);let i=Date.now()+so,s=new AbortController,l;try{let c=await Sr({version:1,receiptId:n,projectId:r.projectId,deploymentId:r.deploymentId,recipient:r.envelope.to,expiresAt:Date.now()+3e4},t.EMAIL_SIGNING_SECRET),d=i-Date.now();if(d<=0)throw new Error("email tenant request timeout");let u;try{l=await Promise.race([e.fetch(`https://worker${Ir}`,{method:"POST",headers:{"content-type":"application/vnd.void.email-envelope; version=1","x-void-email-receipt":c,"x-void-email-recipient":r.envelope.to},body:vr(r.envelope),signal:s.signal}),new Promise((f,h)=>{u=setTimeout(()=>{s.abort(),h(new Error("email tenant request timeout"))},d)})])}finally{u!==void 0&&clearTimeout(u)}if(!l.ok||l.headers.get("content-encoding")||l.headers.get("content-type")!==`application/vnd.void.email-actions; version=${1}`||!l.body)throw new Error(`invalid email tenant response (${l.status})`);let p=Math.min(io,i-Date.now());if(p<=0)throw new Error("email tenant request timeout");return{actions:await Mr(l.body,p),receiptId:n}}finally{s.abort(),l?.body?.cancel().catch(()=>{});let c=(ae.get(r.projectId)??1)-1;c===0?ae.delete(r.projectId):ae.set(r.projectId,c)}}a(mt,"dispatchBoundedEmailToTenant");function le(e,t){switch(typeof e){case"string":return I(e,t);case"number":case"boolean":case"undefined":return String(e);case"object":return e===null?"null":I(Object.prototype.toString.call(e),64);default:return`[${typeof e}]`}}a(le,"describeUntrusted");function Cr(e){let t=[e.slug,e.alias,e.mailbox].filter(r=>typeof r=="string").map(r=>r.toLowerCase());return[...new Set(t)]}a(Cr,"mailboxNames");function ao(e){return{routeId:e.routeId,routeGeneration:e.routeGeneration,connectionId:e.connectionId,addressing:e.addressing,domain:e.domain,projectSlug:e.slug}}a(ao,"receiptRouteFence");var D=10*1024*1024,ce=1024,yt=128*1024,lo=1e3,Nr=100,jr=320,xr=32,je=1024,Or=5*1024*1024,kr=8*1024*1024,co=15e3,Ue=class extends Error{constructor(r){super(`inbound message exceeds ${D} bytes (got ${r})`);this.size=r;this.name="InboundTooLargeError"}size;static{a(this,"InboundTooLargeError")}},$e=class extends Error{static{a(this,"InboundTooManyHeadersError")}constructor(){super(`inbound message carries more than ${ce} headers`),this.name="InboundTooManyHeadersError"}},He=class extends Error{static{a(this,"InboundHeadersTooLargeError")}constructor(){super(`inbound headers exceed ${yt} bytes`),this.name="InboundHeadersTooLargeError"}};function gt(e){return typeof e=="string"&&e.length<=jr&&(0,Lr.validate)(e)}a(gt,"isValidEmailAddress");function j(e){return le(e,jr)}a(j,"logAddress");function uo(e){if(typeof e!="object"||e===null)return console.error("[email-router] action list dropped: forward headers is not a plain object"),!1;let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return console.error("[email-router] action list dropped: forward headers is not a plain object"),!1;let r=Object.keys(e);if(r.length>xr)return console.error(`[email-router] action list dropped: forward has ${r.length} headers (max ${xr})`),!1;for(let n of r){let o=e[n];if(n.length>je)return console.error(`[email-router] action list dropped: forward header name exceeds ${je} characters`),!1;if(typeof o!="string")return console.error(`[email-router] action list dropped: forward header "${I(n,64)}" value is not a string`),!1;if(o.length>je)return console.error(`[email-router] action list dropped: forward header "${I(n,64)}" value exceeds ${je} characters`),!1}return!0}a(uo,"forwardHeadersWithinBounds");function fo(e,t){if(!/^[\x21-\x7e]+$/.test(e))return!1;let r=e.toLowerCase(),n=r.indexOf("@");return n<=0?!1:r.slice(n+1)!==t.domain||t.customDomain?!0:t.names.includes(r.slice(0,n).split("+")[0])}a(fo,"isPermittedReplySender");async function Ur(e,t,r,n){let o=se(t)??"void email",i=String(e.to??"").toLowerCase(),s=i.split("@")[0]??"",l=s.indexOf("+"),c=l===-1?s:s.slice(0,l),d=(n.mailbox??n.slug).toLowerCase(),u=i.indexOf("@"),p=u===-1?"":i.slice(u+1);if(!c){e.setReject(`${o}: missing project slug in recipient`);return}if(n.addressing!=="custom"&&Dt(c)){e.setReject(`${o}: "${I(c,64)}" is a reserved platform address`);return}if(!n.projectId||!n.workerName||!n.deploymentId||n.domain?.toLowerCase()!==p||n.addressing==="shared"&&d!==c){e.setReject(`${o}: authoritative route mismatch`);return}let m=n.workerName,f=n.projectId,h;try{h=n.limits?t.DISPATCH.get(m,{},{limits:n.limits}):t.DISPATCH.get(m)}catch(A){throw console.error(`[email-router] DISPATCH.get(${I(m,320)}) failed:`,A),new Error("email worker temporarily unavailable")}if(typeof e.rawSize=="number"&&e.rawSize>D){e.setReject(`${o}: message too large (max ${D} bytes)`);return}let y;try{y=await go(e),n.addressing==="custom"&&(y.viaDomain=p)}catch(A){if(A instanceof Ue){e.setReject(`${o}: message too large (max ${D} bytes)`);return}if(A instanceof $e){e.setReject(`${o}: too many headers (max ${ce})`);return}if(A instanceof He){e.setReject(`${o}: headers too large (max ${yt} bytes)`);return}console.error(`[email-router] failed to read message body for ${I(c,64)}:`,A),e.setReject(`${o}: could not read inbound message body`);return}let b=crypto.randomUUID(),R={projectId:f,receiptId:b,transport:"native"},E;try{await B(t,b,f,"received",ao(n))}catch{throw new Error("email admission temporarily unavailable")}try{E=(await mt(h,t,{projectId:f,deploymentId:n.deploymentId,envelope:y,receiptId:b})).actions}catch(A){await B(t,b,f,"handler_failed").catch(()=>{});let w=A instanceof Error?A.message.slice(0,320):le(A,320);throw console.error(`[email-router] dispatch to ${I(m,320)} failed:`,w),new Error("email handler execution unresolved")}try{await B(t,b,f,"handler_completed")}catch{console.error("[email-router] handler completed but receipt status could not be saved");return}try{await Hr(t,e,E,R,{customDomain:n.addressing==="custom",names:Cr(n),domain:p})}catch{console.error("[email-router] action execution unresolved",b);return}r.waitUntil(ht(t,f,e,E))}a(Ur,"routeInbound");async function $r(e,t,r){let{stub:n,projectId:o,domain:i,envelope:s,authoritative:l,receiptId:c}=r;if(l.projectId!==o||!l.workerName||!l.slug||l.domain?.toLowerCase()!==i)return{reject:!0};let d=l.workerName,u=po(s),p={projectId:o,receiptId:c,transport:"relay"},m;try{m=(await mt(n,e,{projectId:o,deploymentId:l.deploymentId,envelope:s,receiptId:c})).actions}catch(f){await B(e,c,o,"handler_failed").catch(()=>{});let h=f instanceof Error?f.message.slice(0,320):le(f,320);return console.error(`[email-relay] dispatch to ${I(d,320)} failed:`,h),t.waitUntil(ht(e,o,u.message,[{type:"reject",reason:"dispatch-error"}])),{reject:!0,temporary:!0}}try{await B(e,c,o,"handler_completed")}catch{return console.error("[email-relay] handler completed but receipt status could not be saved"),{reject:!1}}try{await Hr(e,u.message,m,p,{customDomain:l.addressing==="custom",names:Cr(l),domain:i})}catch{return console.error("[email-relay] action execution unresolved",c),{reject:!1}}return t.waitUntil(ht(e,o,u.message,m)),{reject:u.rejectedReason()!==null}}a($r,"routeRelayed");function po(e){let t=null;return{message:{from:e.from,to:e.to,rawSize:e.rawSize,headers:new Headers(e.headers),raw:ie(e.raw),setReject(n){t=n},async forward(n,o){throw new U("relayed forward requires a native email event")}},rejectedReason:a(()=>t,"rejectedReason")}}a(po,"createRelayedMessage");async function mo(e,t,r,n,o){let i=r.slice(r.indexOf("@")+1).toLowerCase();if(i===se(e)){let c=e.SEND_EMAIL;if(!c||typeof c.send!="function")throw new Error("shared email binding is unavailable");return async d=>(await c.send(new Dr(r,d,ie(n))))?.messageId}let s=await Ae(e,i,t);if(!s||o&&s.accountId!==o)throw new Error("could not lease the domain credential");let l=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(n);return async(c,d=3e4)=>{let u;try{u=await dt({accountId:s.accountId,bearer:Re(s),from:r,recipients:[c],mimeMessage:l},d)}catch{throw new Error("email sending request failed")}if(!u.ok)throw u.status>=500||u.status===408?new Error("email sending API outcome unknown"):new U(`email sending API returned ${u.status}`);let p=u.data;if(typeof p!="object"||p===null||!("success"in p))throw new Error("email sending API response invalid");if(p.success===!1)throw new U("email sending API refused the message");if(p.success!==!0)throw new Error("email sending API response invalid");let m=ut(p.result);if(!m)throw new Error("email sending API response invalid");let f=ft(m,c);if(f==="permanent_bounce")throw new U("recipient permanently bounced");if(f==="suppressed")throw new U("recipient is on the suppression list");if(f==="outcome_unknown")throw new Error("email sending API did not classify the recipient");return m.messageId}}a(mo,"prepareRelayedReply");async function ht(e,t,r,n){if(!t){console.error(`[email-router] cannot log inbound delivery: routing entry has no projectId (to=${I(String(r.to??""),320)})`);return}let o=n.some(i=>i&&typeof i=="object"&&i.type==="reject")?"rejected":n.length===0?"accepted":"handled";try{await wr(t,{from:String(r.from??""),to:String(r.to??""),byteSize:r.rawSize??0,status:o})}catch(i){console.error("[email-router] log-recv failed:",i)}}a(ht,"logRecv");async function go(e){let t=[],r=0,n=new TextEncoder;for(let s of e.headers){if(t.length>=ce)throw new $e;if(r+=n.encode(s[0]).byteLength+n.encode(s[1]).byteLength,r>yt)throw new He;t.push(s)}let o=await ho(e.raw),i=Object.fromEntries(t);return{from:String(e.from??""),to:String(e.to??""),headers:i,raw:o,rawSize:e.rawSize??o.byteLength}}a(go,"buildEnvelope");async function ho(e){let t=e.getReader(),r=[],n=0,o=Date.now()+co;try{for(;;){let l=o-Date.now();if(l<=0)throw new Error("inbound message stream timed out");let c,{value:d,done:u}=await Promise.race([t.read(),new Promise((p,m)=>{c=setTimeout(()=>m(new Error("inbound message stream timed out")),l)})]).finally(()=>{c!==void 0&&clearTimeout(c)});if(u)break;if(n+=d.byteLength,n>D)throw new Ue(n);r.push(d)}}catch(l){throw t.cancel().catch(()=>{}),l}finally{try{t.releaseLock()}catch{}}let i=new Uint8Array(n),s=0;for(let l of r)i.set(l,s),s+=l.byteLength;return i}a(ho,"readStreamToBytes");var U=class extends Error{static{a(this,"DefinitiveEmailActionError")}};async function yo(e,t){if(e.length>Nr)return console.error(`[email-router] action list dropped: ${e.length} actions returned (max ${Nr})`),null;let r=[],n=0;for(let o of e){if(!o||typeof o!="object")return console.error(`[email-router] dropping non-object action: ${le(o,320)}`),null;if(o.type==="reject"){let i=typeof o.reason=="string"?o.reason:"",s=i.length>0?I(i,lo):"rejected by handler";return r.push({type:"reject",reason:s}),r}if(o.type==="forward"){if(!gt(o.to))return console.error(`[email-router] forward dropped: invalid "to" address ${j(o.to)}`),null;let i;if(o.headers){if(!uo(o.headers))return null;try{i=new Headers(o.headers)}catch(s){return console.error("[email-router] action list dropped: forward headers invalid:",s instanceof Error?I(s.message,320):I(String(s),320)),null}}r.push({type:"forward",to:o.to,headers:i})}else if(o.type==="reply"){if(!gt(o.from)||!gt(o.to))return console.error(`[email-router] reply dropped: invalid address (from=${j(o.from)} to=${j(o.to)})`),null;if(!fo(o.from,t))return console.error(`[email-router] reply dropped: sender not owned by project "${I(t.names[0]??"",64)}" (from=${j(o.from)})`),null;if(!(o.raw instanceof Uint8Array))return console.error(`[email-router] reply dropped: raw is not a Uint8Array (from=${j(o.from)})`),null;let i=o.raw.byteLength;if(i>Or)return console.error(`[email-router] reply dropped: raw is ${i} bytes (max ${Or}) (from=${j(o.from)})`),null;if(n+i>kr)return console.error(`[email-router] reply dropped: cumulative reply bytes ${n+i} exceed this delivery's budget of ${kr} (from=${j(o.from)})`),null;let s=ct(o.raw);if(!s.ok||s.addrSpec.toLowerCase()!==o.from.toLowerCase())return console.error(`[email-router] reply dropped: MIME From is not the envelope sender (from=${j(o.from)}, ${s.ok?"header names another address":s.reason})`),null;n+=i,r.push({type:"reply",from:o.from,to:o.to,raw:o.raw})}else return console.warn(`[email-router] dropping unknown action type: ${le(o.type,320)}`),null}return r}a(yo,"validateActions");async function Hr(e,t,r,n,o){let i=await yo(r,o);if(i===null){await B(e,n.receiptId,n.projectId,"actions_rejected").catch(()=>{console.error("[email-router] could not record rejected actions")});return}await bo(e,t,i,n)}a(Hr,"enactActions");async function bo(e,t,r,n){if(!n.projectId||!n.receiptId){console.error("[email-router] action admission unavailable: missing project or receipt identity");return}let o=Ie();for(let[i,s]of r.entries()){if(s.type==="reject"){t.setReject(s.reason);return}if(o.expired()){console.error("[email-router] action batch deadline elapsed before admission");break}let l=s.to.toLowerCase(),c=s.type==="reply"?s.from:t.to,d=await we(s.type,c,[l],s.type==="reply"?s.raw:new TextEncoder().encode(JSON.stringify([...s.headers?.entries()??[]].sort()))),u;try{u=await Ee(e,{projectId:n.projectId,kind:s.type,key:`${n.receiptId}:${i}:${d.slice(0,16)}`,digest:d,from:c,recipients:[l],transport:n.transport==="relay"?s.type==="reply"&&s.from.slice(s.from.indexOf("@")+1).toLowerCase()===se(e)?"binding":"send_raw":s.type==="forward"?"native_forward":"native_reply",receiptId:n.receiptId})}catch(f){console.error("[email-router] action admission unavailable:",f instanceof Error?f.message:"unknown");continue}let p=u.recipients.find(f=>f.recipient===l);if(u.replay||p?.state!=="reserved")continue;let m;if(n.transport==="relay"&&s.type==="reply")try{m=await mo(e,n.projectId,s.from,s.raw,u.accountId)}catch{await k(e,u.operationId,[l],"cancelled").catch(()=>{console.error("[email-router] could not cancel unsubmitted relayed reply")}),console.error("[email-router] relayed reply could not be prepared");continue}if(o.expired()){let f=await Pr(e,u.operationId,l);console.error(f?"[email-router] action batch deadline elapsed; reservation cancelled":"[email-router] action batch deadline elapsed; cancellation unresolved");break}try{await Z(e,u.operationId,[l])}catch{let f=await Pr(e,u.operationId,l);console.error(f?"[email-router] attempt did not start; reservation cancelled":"[email-router] could not confirm attempt status");continue}try{let f;s.type==="forward"?await o.run(()=>t.forward(l,s.headers)):m?f=await o.run(()=>m(l,o.remainingMs())):await o.run(()=>t.reply(new Dr(s.from,l,ie(s.raw))));try{await k(e,u.operationId,[l],"provider_accepted",{providerReference:f})}catch{console.error("[email-router] provider accepted action but outcome ledger write failed")}}catch(f){let h=f instanceof U;try{await k(e,u.operationId,[l],h?"failed":"outcome_unknown",{errorCode:h?"UPSTREAM_ERROR":"OUTCOME_UNKNOWN"})}catch{}console.error(h?"[email-router] action provider refused":"[email-router] action provider outcome unknown")}}}a(bo,"enactSanitized");async function Pr(e,t,r){try{return(await k(e,t,[r],"cancelled")).recipients.some(o=>o.recipient===r&&o.state==="cancelled")}catch{return!1}}a(Pr,"cancelUnstartedAction");var Be=new TextEncoder,At=new TextDecoder,bt=128*1024,Rt=320,wo=2,qr="/email/destinations/confirm",Eo=4*1024,Fr=32*1024,Br=5e3,wt=0,L=class extends Error{constructor(r,n){super(r);this.status=n;this.name="MimeHeaderError"}status;static{a(this,"MimeHeaderError")}};function _t(e){return e.PLATFORM_TRAFFIC_STATE==="staging"||e.PLATFORM_TRAFFIC_STATE==="sandbox-drain"}a(_t,"isTrafficPaused");async function Gr(e){if(wt>=wo)throw new Error("email gateway busy");wt++;try{return await e()}finally{wt--}}a(Gr,"withDeliverySlot");async function zr(e,t){if(!t)throw new Error("Email signing key is not configured");let r=await crypto.subtle.importKey("raw",Be.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,Be.encode(e))),o="";for(let i of n)o+=String.fromCharCode(i);return btoa(o).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}a(zr,"sign");async function Vr(e,t){let r=Date.now()+5e3,n=new AbortController,o=a(async b=>{let R=r-Date.now();if(R<=0)throw n.abort(),new Error("ingress resolution timeout");let E;try{return await Promise.race([b(),new Promise((A,w)=>{E=setTimeout(()=>{n.abort(),w(new Error("ingress resolution timeout"))},R)})])}finally{E!==void 0&&clearTimeout(E)}},"beforeDeadline"),i=await zr(`email-ingress-v1
|
|
3
|
+
${t.toLowerCase()}`,e.EMAIL_SIGNING_SECRET);l=await i(()=>e.API.fetch("https://api/internal/email/domain-credential",{method:"POST",headers:{"content-type":"application/json","x-void-internal":p},body:JSON.stringify({domain:t,projectId:r}),signal:o.signal}))}catch{return null}if(!l.ok)return l.body?.cancel().catch(()=>{}),null;let c=l.headers.get("content-length");if(c!==null&&(!/^\d+$/.test(c)||Number(c)>qt))return l.body?.cancel().catch(()=>{}),null;let d=l.body?.getReader();if(!d)return null;let u=new Uint8Array(qt),m=0;try{for(;;){let f=await i(()=>d.read());if(f.done)break;if(m+f.value.byteLength>u.byteLength)throw new Error("email credential lease response too large");u.set(f.value,m),m+=f.value.byteLength}if(c!==null&&m!==Number(c))return null;let p=JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(u.subarray(0,m)));return _n(p)}catch{return null}finally{d.cancel().catch(()=>{});try{d.releaseLock()}catch{}}}a(Se,"leaseEmailDomainCredential");function _n(e){if(typeof e!="object"||e===null)return null;let t=e.kind,r=e.accountId;if(typeof r!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(r))return null;if(t==="api_token"){let n=e.token;return typeof n=="string"&&n.length>0?{kind:t,token:n,accountId:r}:null}return null}a(_n,"parseLease");g();var Ie=class extends Error{static{a(this,"EmailProviderTimeoutError")}constructor(){super("email provider outcome unknown after timeout"),this.name="EmailProviderTimeoutError"}};function ve(e=6e4){let t=Date.now()+e;return{remainingMs(r=0){return Math.max(0,t-Date.now()-r)},expired(r=0){return Date.now()>=t-r},async run(r,n=0){let o=Math.min(3e4,t-Date.now()-n);if(o<=0)throw new Ie;let s=r(),i;try{return await Promise.race([s,new Promise((l,c)=>{i=setTimeout(()=>c(new Ie),o)})])}finally{i!==void 0&&clearTimeout(i)}}}}a(ve,"createEmailProviderDeadline");g();import{EmailMessage as Gn}from"cloudflare:email";g();g();g();g();var ne=class extends Error{static{a(this,"HTTPException")}res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};g();var Y=Symbol();g();g();g();var zt=a((e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData(),"bufferToFormData");var Sn=1e4,Me=a(e=>"headers"in e,"isRawRequest"),Xt=a(async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,o=(Me(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return o==="multipart/form-data"||o==="application/x-www-form-urlencoded"?In(e,{all:r,dot:n}):{}},"parseBody");async function In(e,t){if(!Me(e)&&e.bodyCache.formData)return Vt(await e.bodyCache.formData,t);let r=Me(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=zt(n,r.get("Content-Type")||"");Me(e)||(e.bodyCache.formData=o);let s=await o;return s?Vt(s,t):{}}a(In,"parseFormData");function Vt(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,s)=>{t.all||s.endsWith("[]")?vn(r,s,o):r[s]=o}),t.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(Mn(r,o,s,n),delete r[o])}),r}a(Vt,"convertFormDataToBodyData");var vn=a((e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},"handleParsingAllValues"),Mn=a((e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let o=e,s=t.split(".",34);s.length>33&&Wt(),s.forEach((i,l)=>{l===s.length-1?o[i]=r:((!o[i]||typeof o[i]!="object"||Array.isArray(o[i])||o[i]instanceof File)&&(n.count++>=Sn&&Wt(),o[i]=Object.create(null)),o=o[i])})},"handleParsingNestedValues"),Wt=a(()=>{throw new Error("Nesting limit exceeded")},"throwNestingLimitExceeded");g();var Qe=a(e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},"splitPath"),oe=a(e=>{let{groups:t,path:r}=Nn(e),n=Qe(r);return Tn(n,t)},"splitRoutingPath"),Nn=a(e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},"extractGroupsFromPath"),Tn=a((e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},"replaceGroupMarks"),Ne={},ie=a((e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return Ne[n]||(r[2]?Ne[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:Ne[n]=[e,r[1],!0]),Ne[n]}return null},"getPattern"),Te=a((e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},"tryDecode");var Ke=a(e=>decodeURI(e.includes("%25")?e.replace(/%25/g,"%2525"):e),"decodeURIWithPreservedPercent"),Ze=a(e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let s=t.indexOf("?",n),i=t.indexOf("#",n),l=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=t.slice(r,l),d=Te(c,Ke);if(/%(?![0-9A-Fa-f]{2})/.test(c)){let u=new URL("http://localhost");if(u.pathname=d.replace(/[\\\t\n\r]/g,encodeURIComponent),Te(u.pathname,Ke)!==d)return Te(c.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"),Ke)}return d}else if(o===63||o===35)break}return t.slice(r,n)},"getPath");var Yt=a(e=>{let t=Ze(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},"getPathNoStrict"),z=a((e,t,...r)=>(r.length&&(t=z(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),"mergePath"),Oe=a(e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.slice(0,-1);n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},"checkOptionalParameter"),xe=a(e=>e.indexOf("%")!==-1?Te(e,On):e,"tryDecodeURIComponent"),Je=a(e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),xe(e)),"_decodeURI"),Kt=a((e,t,r)=>{let n=e.indexOf("#",8);n!==-1&&(e=e.slice(0,n));let o;if(!r&&t&&!/[%+&=]/.test(t)){let l=e.indexOf("?",8),c=l;if(c===-1)return;for(e.startsWith(t,c+1)||(c=e.indexOf(`&${t}`,c+1));c!==-1;){let d=e.charCodeAt(c+t.length+1);if(d===61||d===38||isNaN(d)){if(c>l&&/(?:^|&)[^=&]*[%+]/.test(e.slice(l+1,c)))break;if(d===61){let u=c+t.length+2,m=e.indexOf("&",u);return Je(e.slice(u,m===-1?void 0:m))}return""}c=e.indexOf(`&${t}`,c+1)}if(o=/[%+]/.test(e),!o)return}let s=Object.create(null);o??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let l=e.indexOf("&",i+1),c=e.indexOf("=",i);c>l&&l!==-1&&(c=-1);let d=e.slice(i+1,c===-1?l===-1?void 0:l:c);if(o&&(d=Je(d)),i=l,d==="")continue;let u;c===-1?u="":(u=e.slice(c+1,l===-1?void 0:l),o&&(u=Je(u))),r?(s[d]&&Array.isArray(s[d])||(s[d]=[]),s[d].push(u)):s[d]??=u}return t?s[t]:s},"_getQueryParam"),Jt=Kt,Qt=a((e,t)=>Kt(e,t,!0),"getQueryParams"),On=decodeURIComponent;var Zt=class{static{a(this,"HonoRequest")}raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r}param(e){return e?this.#r(e):this.#i()}#r(e){let t=this.#e[0][this.routeIndex]?.[1][e],r=this.#o(t);return r&&xe(r)}#i(){let e={},t=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of t){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=xe(n))}return e}#o(e){return this.#e[1]?this.#e[1][e]:e}query(e){return Jt(this.url,e)}queries(e){return Qt(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return Xt(this,e)}#n=a(e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;for(let o in t)return t[o].then(s=>{o==="json"&&(s=JSON.stringify(s));let i=o==="formData"?void 0:r.headers.get("content-type");return new Response(s,{headers:i?{"Content-Type":i}:void 0})[e]()});return t[e]=r[e]()},"#cachedBody");json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){(this.#t??={})[e]=t}valid(e){return this.#t?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Y](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};g();var er={Stringify:1,BeforeStream:2,Stream:3},xn=a((e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r},"raw");var et=a(async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let s=e.callbacks;if(!s?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let i=Promise.all(s.map(l=>l({phase:t,buffer:o,context:n}))).then(l=>Promise.all(l.filter(Boolean).map(c=>et(c,t,!1,n,o))).then(()=>o[0]));return r?xn(await i,s):i},"resolveCallback");var Pn="text/plain; charset=UTF-8",tt=a((e,t)=>({"Content-Type":e,...t}),"setDefaultContentType"),se=a((e,t)=>new Response(e,t),"createResponseInstance"),rt=class{static{a(this,"Context")}#t;#e;env={};#r;finalized=!1;error;#i;#o;#n;#d;#l;#c;#a;#u;#f;constructor(e,t){this.#t=e,t&&(this.#o=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#f=t.path,this.#u=t.matchResult)}get req(){return this.#e??=new Zt(this.#t,this.#f,this.#u),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||=se(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=se(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#n=e,this.finalized=!0}render=a((...e)=>(this.#l??=t=>this.html(t),this.#l(...e)),"render");setLayout=a(e=>this.#d=e,"setLayout");getLayout=a(()=>this.#d,"getLayout");setRenderer=a(e=>{this.#l=e},"setRenderer");header=a((e,t,r)=>{this.finalized&&!this.#n.bodyUsed&&(this.#n=se(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)},"header");status=a(e=>{this.#i=e},"status");set=a((e,t)=>{this.#r??=new Map,this.#r.set(e,t)},"set");get=a(e=>this.#r?this.#r.get(e):void 0,"get");get var(){return this.#r?Object.fromEntries(this.#r):{}}#s(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a;if(typeof t=="object"&&t.headers){n??=new Headers;for(let[s,i]of new Headers(t.headers))s==="set-cookie"?n.append(s,i):n.set(s,i)}if(r){if(!n){let s=0;for(let i in r)if(++s>1||typeof r[i]!="string"){n=new Headers;break}}if(n)for(let s in r){let i=r[s];if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let l of i)n.append(s,l)}}}let o=typeof t=="number"?t:t?.status??this.#i;return se(e,{status:o,headers:n??r})}newResponse=a((...e)=>this.#s(...e),"newResponse");body=a((e,t,r)=>this.#s(e,t,r),"body");text=a((e,t,r)=>!this.#a&&!this.#i&&!t&&!r&&!this.finalized?new Response(e):this.#s(e,t,tt(Pn,r)),"text");json=a((e,t,r)=>this.#s(JSON.stringify(e),t,tt("application/json",r)),"json");html=a((e,t,r)=>{let n=a(o=>this.#s(o,t,tt("text/html; charset=UTF-8",r)),"res");return typeof e=="object"?et(e,er.Stringify,!1,{}).then(n):n(e)},"html");redirect=a((e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)},"redirect");notFound=a(()=>(this.#c??=()=>se(),this.#c(this)),"notFound")};g();g();g();var nt=a((e,t,r)=>(n,o)=>{let s=-1;return i(0);async function i(l){if(l<=s)throw new Error("next() called multiple times");s=l;let c,d=!1,u;if(e[l]?(u=e[l][0][0],n.req.routeIndex=l):u=l===e.length&&o||void 0,u)try{c=await u(n,()=>i(l+1))}catch(m){if(m instanceof Error&&t)n.error=m,c=await t(m,n),d=!0;else throw m}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||d)&&(n.res=c),n}},"compose");g();var kn=a(e=>e.req[Y][0].map(([[,t]])=>t),"matchedRoutes"),tr=a((e,t)=>kn(e).at(t??e.req.routeIndex)?.path??"","routePath");g();var rr=["get","post","put","delete","options","patch","query"],Pe="Can not add a route since the matcher is already built.",ke=class extends Error{static{a(this,"UnsupportedPathError")}};g();var nr="__COMPOSED_HANDLER";g();var or=a(e=>{let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.length-t},"countTrailingSlashes"),Dn=a((e,t,r)=>{if(!/[:*]/.test(t))return t.length;let n=e.req.path,o=e.req[Y],s=new Set,i=0;for(let l of oe(t)){if(l[0]===":"&&l.endsWith("}?"))throw new Error(`mount(): Optional regular expression parameters are not supported in "${r}".`);let c=ie(l);if(c&&c!=="*"){let d=c[1];if(s.has(d))throw new Error(`mount(): Duplicate path parameter "${d}" in "${r}".`);s.add(d)}if(c&&c!=="*"&&c[2]!==!0){let d=o.length===2?o[1][o[0][e.req.routeIndex][1][c[1]]]:o[0][e.req.routeIndex][1][c[1]];i+=d.length+1}else if(c||l.endsWith("*")){let d=n.indexOf("/",i+1);i=d===-1?n.length:d}else i+=l.length+1}return i},"getPathPrefixLength"),ir=a((e,t,r)=>{if(/[^/]\*$/.test(r))throw new Error(`mount(): Wildcard must follow "/" in "${r}".`);let n=Dn(e,t,r),o=e.req.path.slice(n)||"/";if(n>e.req.path.length||o[0]!=="/"||/\/(?:\.|%2e){1,2}(?:\/|$)/i.test(o))throw new ne(400,{message:"Invalid mounted path"});let s=e.req.raw.url;if(/^[^/?#]*\/\/[^/?#\\]*[?#\\]/.test(s))throw new ne(400,{message:"Invalid mounted path"});let i=s.search(/[?#]/),l=or(i===-1?s:s.slice(0,i));if(l>1&&or(e.req.path)===l-1)throw new ne(400,{message:"Invalid mounted path"});let c=new URL(s);return c.pathname=o.replace(/[\\\t\n\r]/g,encodeURIComponent),o.includes("%"),new Request(c,e.req.raw)},"createMountedRequest");var Ln=a(e=>e.text("404 Not Found",404),"notFoundHandler"),sr=a((e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},"errorHandler"),ar=class lr{static{a(this,"Hono")}get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...rr,"all"].forEach(o=>{this[o]=(s,...i)=>{let l=o.toUpperCase();return typeof s=="string"?this.#t=s:this.#i(l,this.#t,s),i.forEach(c=>{this.#i(l,this.#t,c)}),this}}),this.on=(o,s,...i)=>{for(let l of[s].flat()){this.#t=l;for(let c of[o].flat()){let d=c.toUpperCase();for(let u of i)this.#i(d,this.#t,u)}}return this},this.use=(o,...s)=>(typeof o=="string"?this.#t=o:(this.#t="*",s.unshift(o)),s.forEach(i=>{this.#i("ALL",this.#t,i)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??Ze:Yt}#e(){let t=new lr({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Ln;errorHandler=sr;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===sr?s=o.handler:(s=a(async(i,l)=>(await nt([],r.errorHandler)(i,()=>o.handler(i,l))).res,"handler"),s[nr]=o.handler),n.#i(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=z(this._basePath,t),r}onError=a(t=>(this.errorHandler=t,this),"onError");notFound=a(t=>(this.#r=t,this),"notFound");mount(t,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=a(d=>d,"replaceRequest"):o=n.replaceRequest));let i=s?d=>{let u=s(d);return Array.isArray(u)?u:[u]}:d=>{let u;try{u=d.executionCtx}catch{}return[d.env,u]},l=a(d=>{let u=tr(d);return ir(d,u.replace(/\/?\*$/,""),u)},"defaultReplaceRequest"),c=a(async(d,u)=>{let m=await r(o?o(d.req.raw):l(d),...i(d));if(m)return m;await u()},"handler");return this.#i("ALL",z(t,"*"),c),this}#i(t,r,n,o){r=z(this._basePath,r);let s={basePath:o!==void 0?z(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#o(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),i=this.router.match(o,s),l=new rt(t,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let d;try{d=i[0][0][0][0](l,async()=>{l.res=await this.#r(l)})}catch(u){return this.#o(u,l)}return d instanceof Promise?d.then(u=>u||(l.finalized?l.res:this.#r(l))).catch(u=>this.#o(u,l)):d??this.#r(l)}let c=nt(i[0],this.errorHandler,this.#r);return(async()=>{try{let d=await c(l);if(!d.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return d.res}catch(d){return this.#o(d,l)}})()}fetch=a((t,...r)=>this.#n(t,r[1],r[0],t.method),"fetch");request=a((t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${z("/",t)}`,r),n,o)),"request");fire=a(()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})},"fire")};g();g();var O=a(()=>Object.create(null),"createNullObject");g();var ot=[];function cr(e,t){let r=this.buildAllMatchers(),n=a(((o,s)=>{let i=r[o]||r.ALL,l=i[2][s];if(l)return l;let c=s.match(i[0]);if(!c)return[[],ot];let d=c.indexOf("",1);return[i[1][d],c]}),"match");return this.match=n,n(e,t)}a(cr,"match");g();var Cn="[^/]+",jn="[^]*",Un="(?:|/[^]*)",j=Symbol(),dr=new Set(".\\+*[^]$()");function $n(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e==="[^]*"||e==="(?:|/[^]*)"?t==="[^]*"?-1:1:t==="[^]*"||t==="(?:|/[^]*)"?-1:e==="[^/]+"?1:t==="[^/]+"?-1:e.length===t.length?e<t?-1:1:t.length-e.length}a($n,"compareKey");var ur=class it{static{a(this,"Node")}#t;#e;#r=O();insert(t,r,n,o,s){let i=this;for(let l=0,c=t.length;l<c;l++){let d=t[l],u=d.length===1?d==="*"?l===c-1?["","",jn]:["","",Cn]:null:d==="/*"?["","",Un]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),m;if(u){let p=u[1],f=u[2]||"[^/]+";if(p&&u[2]&&(new RegExp(f).test("")||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))||f.length===1&&dr.has(f)))throw j;if(s.push(f),m=i.#r[f],!m){if(f!=="[^]*"&&f!=="(?:|/[^]*)"){for(let h in i.#r)if((f.length>1||h.length>1)&&h!=="[^]*"&&h!=="(?:|/[^]*)")throw j}m=i.#r[f]=new it}p!==""&&(m.#e??=o.varIndex++,n.push([p,m.#e]))}else if(s.push(d),m=i.#r[d],!m){for(let p in i.#r)if(p.length>1&&p!=="[^]*"&&p!=="(?:|/[^]*)")throw j;m=i.#r[d]=new it}i=m}if(i.#t!==void 0)throw j;i.#t=r}buildRegExpStr(){let t=Object.keys(this.#r).sort($n).map(r=>{let n=this.#r[r],o=n.buildRegExpStr();return o===""?"":(typeof n.#e=="number"?`(${r})@${n.#e}`:dr.has(r)?`\\${r}`:r)+o}).filter(Boolean);return typeof this.#t=="number"&&this.#t!==-1&&t.unshift(`#${this.#t}`),t.length===0?"":t.length===1?t[0]:"(?:"+t.join("|")+")"}};g();var st=class{static{a(this,"Trie")}#t={varIndex:0};#e=new ur;#r=0;paths=O();insert(e,t){let r=[];if(t){this.#e.insert(e.split(""),-1,[],this.#t,r),this.paths[e]=[-1,[],r];return}let n=[],o=[],s=e;for(let l=0;;){let c=!1;if(s=s.replace(/\{(?:\{[\d,]+\}|[^}])+\}/g,d=>{let u=`@\\${l}`;return o[l]=[u,d],l++,c=!0,u}),!c)break}let i=s.match(/(?::[^\/]+)|(?:\/\*$)|./gs)||[];for(let l=o.length-1;l>=0;l--){let[c]=o[l];for(let d=i.length-1;d>=0;d--)if(i[d].indexOf(c)!==-1){i[d]=i[d].replace(c,o[l][1]);break}}this.#e.insert(i,this.#r,n,this.#t,r),this.paths[e]=[this.#r++,n,r]}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++t]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++t),"")),[new RegExp(`^${e}`),r,n]}};function Hn(e){let t=e[e.length-1];return t==="[^]*"||t==="(?:|/[^]*)"}a(Hn,"endsWithWildcard");function Fn(e,t){let r=e.length-1;for(let n=0;n<r;n++)if(e[n]!==t[n])return!1;return e[r]==="[^]*"||t.length===r||t[r]==="/"}a(Fn,"covers");var fr=class{static{a(this,"RegExpRouter")}name="RegExpRouter";#t;#e;constructor(){this.#t={ALL:[]},this.#e={ALL:new st}}#r(e,t){try{this.#e[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===j?new ke(t):r}}add(e,t,r){let n=this.#t;if(!n)throw new Error(Pe);let o=this.#e;if(!n[e]){o[e]=new st,n[e]=[...n.ALL];for(let l in o.ALL.paths)this.#r(e,l)}t==="/*"&&(t="*");let s=e==="ALL"?Object.keys(n):[e],i=Oe(t)||[t];for(let l of i)for(let c of s)o[c].paths[l]||this.#r(c,l),n[c].push([r,l])}match=cr;buildAllMatchers(){let e=O();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#t=this.#e=void 0,e}#i(e){let t=this.#t[e],r=this.#e[e],n=O(),o=[],[s,i,l]=r.buildRegExp(),c=O(),d=t.map(([m,p],f)=>((c[p]??=[]).push(f),[m,r.paths[p][1].reduceRight((h,[y,b])=>(h[y]=l[b],h),O())])),u=Object.keys(c).filter(m=>Hn(r.paths[m][2]));for(let m in r.paths){let[p,,f]=r.paths[m],h=[...c[m]];for(let b of u)b!==m&&Fn(r.paths[b][2],f)&&h.push(...c[b]);let y=h.sort((b,R)=>b-R).map(b=>d[b]);if(p===-1){let b=Math.max(-1,...y.flatMap(([,R])=>Object.values(R)));n[m]=[y,b===-1?ot:m.match(s).slice(0,b+1)]}else o[p]=y}return[s,i.map(m=>o[m]),n]}};g();var mr=class{static{a(this,"SmartRouter")}name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(Pe);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let l=r[s];try{for(let c=0,d=n.length;c<d;c++)l.add(...n[c]);i=l.match(e,t)}catch(c){if(c instanceof ke)continue;throw c}this.match=l.match.bind(l),this.#t=[l],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};g();g();var at=O(),Bn=0,pr=class gr{static{a(this,"Node")}#t=[];#e=O();#r=[];#i;#o=at;insert(t,r,n){let o=this,s=oe(r),i=new Set,l=0;for(let c of s){let d=s[++l],u=ie(c,d)||(d===void 0&&c&&c.indexOf("*")===c.length-1?c:null),m=Array.isArray(u),p=m?u[0]:u||c,f=o.#e[p]||=new gr;u&&!f.#i&&(f.#i=u,o.#r.push(f)),o=f,m&&i.add(u[1])}o.#t.push({[t]:{handler:n,possibleKeys:[...i],score:++Bn}})}#n(t,r,n,o,s){for(let i=0,l=r.#t.length;i<l;i++){let c=r.#t[i],d=c[n]||c.ALL;if(d){d.params=O(),t.push(d);for(let u=0,m=d.possibleKeys.length;u<m;u++){let p=d.possibleKeys[u];d.params[p]=s?.[p]&&!u?s[p]:o[p]??s?.[p]}}}}search(t,r){let n=[];this.#o=at;let o=[this],s=Qe(r),i=[],l=s.length,c=null;for(let d=0;d<l;d++){let u=s[d],m=d===l-1,p=[];for(let h=0,y=o.length;h<y;h++){let b=o[h],R=b.#e[u];R&&(R.#o=b.#o,m?(R.#e["*"]&&this.#n(n,R.#e["*"],t,b.#o),this.#n(n,R,t,b.#o)):p.push(R));for(let E of b.#r){let A=E.#i,w=b.#o===at?{}:{...b.#o};if(typeof A=="string"){(A==="*"||u.startsWith(A.slice(0,-1)))&&(this.#n(n,E,t,b.#o),A==="*"&&(E.#o=w,p.push(E)));continue}let[,_,v]=A;if(!(!u&&v===!0)){if(v!==!0){if(!c){c=[];let T=r[0]==="/"?1:0;for(let D=0;D<l;D++)c[D]=T,T+=s[D].length+1}let x=r.slice(c[d]),N=v.exec(x);if(N){Object.hasOwn(w,_)||(w[_]=N[0]),this.#n(n,E,t,b.#o,w),N[0].length===x.length&&E.#e["*"]&&this.#n(n,E.#e["*"],t,b.#o,w);for(let T in E.#e){E.#o=w;let D=N[0].match(/\//g)?.length??0;(i[D]||=[]).push(E);break}continue}}(v===!0||v.test(u))&&(Object.hasOwn(w,_)||(w[_]=u),m?(this.#n(n,E,t,w,b.#o),E.#e["*"]&&this.#n(n,E.#e["*"],t,w,b.#o)):(E.#o=w,p.push(E)))}}}let f=i.shift();o=f?p.concat(f):p}return n[1]&&n.sort((d,u)=>d.score-u.score),[n.map(({handler:d,params:u})=>[d,u])]}};var lt=class{static{a(this,"TrieRouter")}name="TrieRouter";#t=new pr;add(e,t,r){for(let n of Oe(t)||[t])this.#t.insert(e,n,r)}match(e,t){return this.#t.search(e,t)}};g();var ct=class extends ar{static{a(this,"Hono")}constructor(e={}){super(e),this.router=e.router??new mr({routers:[new fr,new lt]})}};var qn=new ct,zn=5e4,V=5e3,De=5*1024*1024,Vn=16*1024,Wn=new Set(["from","to","cc","bcc","subject","reply-to","date","message-id","in-reply-to","references","mime-version","content-type","content-transfer-encoding","content-disposition"]);function Xn(e){let t=0,r=!1;for(let n=0;n<e.byteLength;){let o=n;for(;o<e.byteLength&&e[o]!==10;)o++;let s=o>n&&e[o-1]===13?o-1:o;if(s===n)return!0;if(e[n]!==32&&e[n]!==9){let i=n;for(;i<s&&e[i]!==58;)i++;let l=new TextDecoder().decode(e.subarray(n,i)).toLowerCase();r=i<s&&!Wn.has(l)}if(r&&(t+=s-n+2,t>Vn))return!1;n=o+1}return!0}a(Xn,"customMimeHeaderBytesWithinLimit");var hr=50,yr=320,br=320;function ae(e){let t=e.EMAIL_SENDER_DOMAIN;if(typeof t!="string")return null;let r=t.trim().toLowerCase();return r.length>0?r:null}a(ae,"readSenderDomain");var Yn=/[.*+?^${}()|[\]\\]/g;function Kn(e){return e.replaceAll(Yn,String.raw`\$&`)}a(Kn,"escapeRegExp");var wr=new Map;function Jn(e){let t=wr.get(e);if(t)return t;let r=new RegExp(`^[a-z0-9._-]+(?:\\+[a-z0-9._=/-]+)*@${Kn(e)}$`);return wr.set(e,r),r}a(Jn,"strictFromRe");var Qn=new RegExp(String.raw`[\u0000-\u001f\u007f]+`,"g");function S(e,t=200){return e.slice(0,t).replaceAll(Qn," ")}a(S,"sanitizeForLog");var Zn=128;function le(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}a(le,"bytesToStream");var Er=10,Le=13,Ar=32,_r=9,eo=58,Ce=[102,114,111,109];function to(e,t,r){if(r-t<=Ce.length)return-1;for(let o=0;o<Ce.length;o++)if((e[t+o]|32)!==Ce[o])return-1;let n=t+Ce.length;for(;n<r&&(e[n]===Ar||e[n]===_r);)n++;return n<r&&e[n]===eo?n+1:-1}a(to,"fromValueStart");var ro={missing:"the message has no From header",multiple:"the message has more than one From header",malformed:"the From header must hold a single mailbox"};function ft(e){let t=e.byteLength,r=0,n=-1,o=-1,s=!1,i=!1,l=e.indexOf(Le),c=0;for(;c<t;){let m=e.indexOf(Er,c),f=m===-1?t:m;if(f>c&&e[f-1]===Le&&f--,f===c)break;if(l!==-1&&l<c&&(l=e.indexOf(Le,c)),l!==-1&&l<f)return{ok:!1,reason:"malformed"};if(e[c]===Ar||e[c]===_r)i&&(o=f,s=!0);else{let h=to(e,c,f);i=h!==-1,i&&(r++,n=h,o=f,s=!1)}c=m===-1?t:m+1}if(r===0)return{ok:!1,reason:"missing"};if(r>1)return{ok:!1,reason:"multiple"};let d=e.subarray(n,o);if(s){d=e.slice(n,o);let m=0;for(let p=0;p<d.length;p++){let f=d[p];f!==Le&&f!==Er&&(d[m++]=f)}d=d.subarray(0,m)}let u=no(new TextDecoder().decode(d));return u===null?{ok:!1,reason:"malformed"}:{ok:!0,addrSpec:u}}a(ft,"readMimeFromAddrSpec");function no(e){let t=!1,r=!1,n=-1,o=-1,s=-1;for(let l=0;l<e.length;l++){let c=e[l];if(t){r?r=!1:c==="\\"?r=!0:c==='"'&&(t=!1);continue}switch(c){case'"':if(n!==-1)return null;t=!0;break;case"<":if(n!==-1)return null;n=l;break;case">":if(n===-1||o!==-1)return null;o=l;break;case"@":s===-1&&(s=l);break;case",":case";":case":":case"(":case")":case"[":case"]":case"\\":return null;default:break}}if(t)return null;let i;if(n===-1)i=e.trim();else{if(o===-1||e.slice(o+1).trim().length!==0||s!==-1&&s<n)return null;i=e.slice(n+1,o)}return/^[\u0021-\u007e]+$/.test(i)?i:null}a(no,"singleMailboxAddrSpec");qn.post("/send",async e=>{let t=ve(zn),r=e.get("projectId"),n=e.get("body"),o=ee(n.from),s=ee(n.mimeBase64),i=ee(n.requestId),l=i===null?"unknown":S(i,Zn),c=ee(n.idempotencyKey);if(c!==null&&(c.length===0||c.length>128||!/^[\u0020-\u007e]+$/.test(c)))return e.json({ok:!1,error:{code:"INVALID_TO",message:"invalid idempotency key"}},400);let d=c??(i&&i.length<=128&&/^[\u0020-\u007e]+$/.test(i)?i:crypto.randomUUID()),u=Array.isArray(n.recipients)?n.recipients:null;if(!o||!s||!u)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"invalid body"}},400);if(u.length>hr)return e.json({ok:!1,error:{code:"INVALID_TO",message:`too many recipients (max ${hr}, got ${u.length})`}},413);if(o.length>br)return e.json({ok:!1,error:{code:"INVALID_FROM",message:`sender exceeds ${br} characters`}},413);let m=ae(e.env);if(!m)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"email sender domain is not configured"}},502);let p=[],f=new Set;for(let I of u){if(typeof I!="string")continue;if(I.length>yr)return e.json({ok:!1,error:{code:"INVALID_TO",message:`recipient exceeds ${yr} characters`}},413);let M=I.trim().toLowerCase();!M||f.has(M)||(f.add(M),p.push(M))}if(p.length===0)return e.json({ok:!1,error:{code:"INVALID_TO",message:"no recipients"}},200);if(s.length>Math.ceil(De*4/3)+4)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${De} bytes (base64 length ${s.length})`}},413);let h;try{h=io(s)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"invalid base64 mime"}},400)}if(h.byteLength>De)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${De} bytes (got ${h.byteLength})`}},413);if(!Xn(h))return e.json({ok:!1,error:{code:"MIME_ERROR",message:"custom headers exceed the 16 KiB limit"}},413);let y=o.indexOf("@"),b=y===-1?"":o.slice(y+1).toLowerCase();if(b!==""&&b!==m)return oo(e,r,o,b,m,p,h,l,d,t);let R=e.env.SEND_EMAIL;if(typeof R?.send!="function")return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"email sending is not configured"}},502);let E=o.split("@")[0]?.split("+")[0]??"";if(!/^[\u0021-\u007e]+$/.test(o))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let A=o.toLowerCase();if(!Jn(m).test(A))return e.json({ok:!1,error:{code:"INVALID_FROM",message:`from address must be <${E}>[+tag]@${m}`}},200);if((A.slice(0,A.indexOf("@")).split("+")[0]??"")!==E.toLowerCase())return e.json({ok:!1,error:{code:"INVALID_FROM",message:`from address must be <${E}>[+tag]@${m}`}},200);let v=Ir(e,h,o);if(v)return v;let x=await vr(e,t,{projectId:r,operationKey:d,from:o,recipients:p,raw:h,transport:"binding"});if(x instanceof Response)return x;let{admission:N,deliveries:T}=x,D=N.recipients.filter(I=>I.state==="reserved").map(I=>I.recipient);for(let I=0;I<D.length;I++){let M=D[I];if(t.expired(V)){let H=D.slice(I),K=await dt(e.env,N.operationId,H,t.remainingMs());for(let fe of H)T.push({recipient:fe,ok:!1,state:K?"cancelled":"outcome_unknown",error:K?{code:"UPSTREAM_ERROR",message:"email batch deadline elapsed before provider submission"}:{code:"OUTCOME_UNKNOWN",message:"could not cancel unstarted email attempt"}});break}try{await re(e.env,N.operationId,[M],t.remainingMs(V))}catch{let H=await dt(e.env,N.operationId,[M],t.remainingMs());T.push({recipient:M,ok:!1,state:H?"cancelled":"outcome_unknown",error:H?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});continue}try{let H=new Gn(o,M,le(h)),K=await t.run(()=>R.send(H),V),fe=typeof K?.messageId=="string"?K.messageId:"";try{await P(e.env,N.operationId,[M],"provider_accepted",{providerReference:fe},t.remainingMs())}catch{T.push({recipient:M,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider accepted email but outcome could not be recorded"}});continue}T.push({recipient:M,ok:!0,state:"provider_accepted",messageId:fe})}catch{try{await P(e.env,N.operationId,[M],"outcome_unknown",{errorCode:"OUTCOME_UNKNOWN"},t.remainingMs())}catch{}T.push({recipient:M,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"}})}}return Mr(r,l,T),T.some(I=>!I.ok)?e.json({ok:!1,operationId:N.operationId,deliveries:T},200):e.json({ok:!0,operationId:N.operationId,ids:T.map(I=>({recipient:I.recipient,messageId:I.messageId,state:"provider_accepted"}))})});var Rr=64*1024;async function mt(e,t=3e4){let r=new AbortController,n=Date.now()+Math.min(3e4,t),o=JSON.stringify({from:e.from,recipients:e.recipients,mime_message:e.mimeMessage}),s=a(async m=>{let p=n-Date.now();if(p<=0)throw r.abort(),new Error("email sending request timed out");let f=m(),h;try{return await Promise.race([f,new Promise((y,b)=>{h=setTimeout(()=>{r.abort(),b(new Error("email sending request timed out"))},p)})])}finally{h!==void 0&&clearTimeout(h)}},"beforeDeadline"),i=await s(()=>fetch(`https://api.cloudflare.com/client/v4/accounts/${e.accountId}/email/sending/send_raw`,{method:"POST",headers:{authorization:`Bearer ${e.bearer}`,"content-type":"application/json"},body:o,signal:r.signal}));if(!i.ok)return i.body?.cancel().catch(()=>{}),{ok:!1,status:i.status};let l=i.headers.get("content-length");if(l!==null&&(!/^\d+$/.test(l)||Number(l)>Rr))throw i.body?.cancel().catch(()=>{}),new Error("email sending API response too large");let c=i.body?.getReader();if(!c)throw new Error("email sending API response unreadable");let d=new Uint8Array(Rr),u=0;try{for(;;){let m=await s(()=>c.read());if(m.done)break;if(u+m.value.byteLength>d.byteLength)throw new Error("email sending API response too large");d.set(m.value,u),u+=m.value.byteLength}if(l!==null&&u!==Number(l))throw new Error("email sending API response length mismatch");return{ok:!0,data:JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(d.subarray(0,u)))}}finally{c.cancel().catch(()=>{});try{c.releaseLock()}catch{}}}a(mt,"requestSendRaw");function je(e){if(!Array.isArray(e))return null;let t=new Set;for(let r of e){if(typeof r!="string")return null;t.add(r.toLowerCase())}return t}a(je,"readSendRawAddressList");function pt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=je(t.delivered),n=je(t.permanent_bounces),o=je(t.queued),s=je(t.suppressed_recipients);return!r||!n||!o||!s||typeof t.message_id!="string"||t.message_id===""?null:{delivered:r,messageId:t.message_id,permanentBounces:n,queued:o,suppressedRecipients:s}}a(pt,"parseSendRawResult");function gt(e,t){let r=t.toLowerCase(),n=[e.delivered.has(r),e.queued.has(r),e.permanentBounces.has(r),e.suppressedRecipients.has(r)];return n.filter(Boolean).length!==1?"outcome_unknown":n[0]||n[1]?"provider_accepted":n[2]?"permanent_bounce":"suppressed"}a(gt,"classifySendRawRecipient");async function oo(e,t,r,n,o,s,i,l,c,d){if(!/^[\u0021-\u007e]+$/.test(r))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let u=Ir(e,i,r);if(u)return u;let m;try{m=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(i)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"mime must be valid UTF-8"}},400)}let p=await vr(e,d,{projectId:t,operationKey:c,from:r,recipients:s,raw:i,transport:"send_raw"});if(p instanceof Response)return p;let{admission:f,deliveries:h}=p;if(s=f.recipients.filter(w=>w.state==="reserved").map(w=>w.recipient),s.length===0)return ut(e,f.operationId,h);let y=await Se(e.env,n,t,d.remainingMs(V));if(!y)return await P(e.env,f.operationId,s,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"could not lease the domain credential"}},502);if(f.accountId!==y.accountId)return await P(e.env,f.operationId,s,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"email domain changed during admission"}},503);try{await re(e.env,f.operationId,s,d.remainingMs(V))}catch{let w=await dt(e.env,f.operationId,s,d.remainingMs());for(let _ of s)h.push({recipient:_,ok:!1,state:w?"cancelled":"outcome_unknown",error:w?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});return ut(e,f.operationId,h)}let b=null,R="failed",E=null,A=null;try{A=await mt({accountId:y.accountId,bearer:_e(y),from:r,recipients:s,mimeMessage:m},d.remainingMs(V))}catch{b={code:"UPSTREAM_ERROR",message:"email sending request failed"},R="outcome_unknown"}if(A)if(!A.ok)b={code:A.status===429?"QUOTA_EXCEEDED":"UPSTREAM_ERROR",message:`email sending API returned ${A.status}`},R=A.status>=500||A.status===408?"outcome_unknown":"failed";else{let w=G(A.data),{success:_}=w;_===!1?b={code:"UPSTREAM_ERROR",message:"email sending API refused the message"}:_!==!0?(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"):(E=pt(w.result),E||(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"))}for(let w of s){if(b||!E){h.push({recipient:w,ok:!1,state:b?R:"outcome_unknown",error:b??{code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"}});continue}let _=gt(E,w);_==="permanent_bounce"?h.push({recipient:w,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${w}' permanently bounced`}}):_==="suppressed"?h.push({recipient:w,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${w}' is on the suppression list`}}):_==="outcome_unknown"?h.push({recipient:w,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"email sending API did not classify the recipient"}}):h.push({recipient:w,ok:!0,state:"provider_accepted",messageId:E.messageId})}for(let w of h.filter(_=>f.recipients.some(v=>v.recipient===_.recipient&&v.state==="reserved")))try{await P(e.env,f.operationId,[w.recipient],w.ok?"provider_accepted":w.state==="outcome_unknown"?"outcome_unknown":"failed",{providerReference:w.messageId,errorCode:w.ok?void 0:w.state==="outcome_unknown"?"OUTCOME_UNKNOWN":b?.code??w.error?.code},d.remainingMs()),w.state=w.ok?"provider_accepted":w.state==="outcome_unknown"?"outcome_unknown":"failed",w.state==="outcome_unknown"&&!w.ok&&(w.error={code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"})}catch{w.ok=!1,w.state="outcome_unknown",w.error={code:"OUTCOME_UNKNOWN",message:"provider outcome could not be recorded"}}return Mr(t,l,h),h.some(w=>!w.ok)?e.json({ok:!1,operationId:f.operationId,deliveries:h},200):e.json({ok:!0,operationId:f.operationId,ids:h.map(w=>({recipient:w.recipient,messageId:w.messageId,state:"provider_accepted"}))})}a(oo,"sendViaCustomDomain");async function Sr(e,t){console.log(`[email-recv] ${e} ${S(t.from,320)} -> ${S(t.to,320)} ${t.status} (${t.byteSize}B) @${Date.now()}`)}a(Sr,"recordInboundDelivery");function Ir(e,t,r){let n=ft(t);if(n.ok&&n.addrSpec.toLowerCase()===r.toLowerCase())return null;let o=n.ok?"the From header address does not match the envelope sender":ro[n.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${r}: ${o}`}},403)}a(Ir,"refuseMimeFromMismatch");async function vr(e,t,r){let{projectId:n,operationKey:o,from:s,recipients:i,raw:l,transport:c}=r,d;try{d=await Ae(e.env,{projectId:n,kind:"direct",key:o,digest:await Re("direct",s,i,l),from:s,recipients:i,transport:c},t.remainingMs(V))}catch(m){let p=m instanceof Error&&m.message==="IDEMPOTENCY_CONFLICT";return e.json({ok:!1,error:{code:p?"IDEMPOTENCY_CONFLICT":"UPSTREAM_ERROR",message:p?"idempotency key has different content":"email admission unavailable"}},p?409:503)}let u=d.recipients.filter(m=>m.state!=="reserved").map(m=>({recipient:m.recipient,ok:m.state==="provider_accepted",state:m.state,messageId:m.providerReference??void 0,error:m.state==="provider_accepted"?void 0:{code:m.errorCode??(m.state==="outcome_unknown"||m.state==="attempt_started"?"OUTCOME_UNKNOWN":m.state==="cancelled"?"UPSTREAM_ERROR":"UNVERIFIED_DESTINATION"),message:m.state==="outcome_unknown"||m.state==="attempt_started"?"provider outcome unknown; inspect email logs before retrying":m.state==="cancelled"?"email attempt was cancelled before provider submission":"recipient was not admitted"}}));if(d.replay){for(let m of d.recipients.filter(p=>p.state==="reserved"))u.push({recipient:m.recipient,ok:!1,state:"reserved",error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved; inspect email logs before retrying"}});return ut(e,d.operationId,u)}return{admission:d,deliveries:u}}a(vr,"admitDirectSend");async function dt(e,t,r,n){try{let o=await P(e,t,r,"cancelled",{},n);return r.every(s=>o.recipients.some(i=>i.recipient===s&&i.state==="cancelled"))}catch{return!1}}a(dt,"cancelUnstartedRecipients");function ut(e,t,r){return r.length===0?e.json({ok:!1,operationId:t,error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved"}},200):r.some(n=>!n.ok)?e.json({ok:!1,operationId:t,deliveries:r},200):e.json({ok:!0,operationId:t,ids:r.map(n=>({recipient:n.recipient,messageId:n.messageId??"",state:n.state}))},200)}a(ut,"emailActionResponse");function Mr(e,t,r){for(let n of r){let o=n.ok?"sent":n.error?.code??"unknown_error",s=n.messageId??"";console.log(`[email-log] ${e} ${t} ${S(n.recipient,320)} ${o} ${s} @${Date.now()}`)}}a(Mr,"logSend");function io(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}a(io,"base64Decode");g();g();g();function ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(ht,"isRecord");var yt=1,Tr="/__void/email/receipt/v1";var bt=new TextEncoder,so=new TextDecoder("utf-8",{fatal:!0});function ao(e){return Object.values(e).every(t=>typeof t=="string")}a(ao,"hasStringHeaderValues");function lo(e,t,r){let n=0,o=0,s=!1,i=!1;for(let l of e)if(s)i?i=!1:l===92?i=!0:l===34&&(s=!1);else if(l===34)s=!0;else if(l===123||l===91){if(++n>t)throw new Error("email metadata too deep")}else if(l===125||l===93){if(--n<0)throw new Error("invalid email metadata")}else if(l===58&&++o>r)throw new Error("too many email metadata fields");if(s||n!==0)throw new Error("invalid email metadata")}a(lo,"assertFlatJson");function Or(e){let t=bt.encode(JSON.stringify({from:e.from,to:e.to,headers:e.headers,rawSize:e.rawSize,...e.viaDomain?{viaDomain:e.viaDomain}:{}}));if(t.byteLength>131072||e.raw.byteLength>10485760)throw new Error("email envelope too large");let r=new Uint8Array(4+t.byteLength+e.raw.byteLength);return new DataView(r.buffer).setUint32(0,t.byteLength),r.set(t,4),r.set(e.raw,4+t.byteLength),r}a(Or,"encodeEmailEnvelope");function Nr(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}a(Nr,"base64url");async function co(e,t){if(!e)throw new Error("Email signing key is not configured");return crypto.subtle.importKey("raw",bt.encode(e),{name:"HMAC",hash:"SHA-256"},!1,[t])}a(co,"receiptKey");async function xr(e,t){let r=bt.encode(JSON.stringify(e)),n=new Uint8Array(await crypto.subtle.sign("HMAC",await co(t,"sign"),r));return`${Nr(r)}.${Nr(n)}`}a(xr,"signEmailReceipt");async function Pr(e,t=15e3){return fo(e,async r=>{let n=[],o=new Uint8Array(0),s=0,i=Date.now()+t,l=a(()=>uo(r,i,"email response timeout"),"readChunk");async function c(d){let u=new Uint8Array(d),m=0;for(;m<d;){if(o.byteLength===0){let f=await l();if(f.done)throw new Error("truncated email response");if(s+=f.value.byteLength,s>8388608)throw new Error("email response too large");o=f.value}let p=Math.min(o.byteLength,d-m);u.set(o.subarray(0,p),m),o=o.subarray(p),m+=p}return u}for(a(c,"exact");;){let d=await c(5),u=new DataView(d.buffer).getUint32(0),m=d[4];if(m===0){if(u!==0||o.byteLength!==0)throw new Error("invalid email response tail");if(!(await l()).done)throw new Error("invalid email response tail");if(n.some(h=>h.type==="reject")&&n.length!==1)throw new Error("email reject cannot accompany delivery actions");return n}if(m!==1||u>8192||n.length>=100)throw new Error("invalid email action frame");let p=await c(u);lo(p,2,40);let f=JSON.parse(so.decode(p));if(!ht(f))throw new Error("invalid email action");if(f.type==="reply"){if(typeof f.from!="string"||typeof f.to!="string"||Object.keys(f).length!==3)throw new Error("invalid email reply");let h=await c(5),y=new DataView(h.buffer).getUint32(0);if(h[4]!==2||y>5242880)throw new Error("invalid email reply frame");n.push({type:"reply",from:f.from,to:f.to,raw:await c(y)})}else if(f.type==="forward"){let h=f.headers;if(typeof f.to!="string"||Object.keys(f).length>3||h!==void 0&&!ht(h))throw new Error("invalid email forward");if(h&&(Object.keys(h).length>32||!ao(h)))throw new Error("invalid email headers");n.push({type:"forward",to:f.to,...h?{headers:h}:{}})}else if(f.type==="reject"){if(typeof f.reason!="string"||Object.keys(f).length!==2)throw new Error("invalid email reject");n.push({type:"reject",reason:f.reason})}else throw new Error("unknown email action")}})}a(Pr,"readEmailActions");async function uo(e,t,r){let n=t-Date.now();if(n<=0)throw new Error(r);let o;return Promise.race([e.read(),new Promise((s,i)=>{o=setTimeout(()=>i(new Error(r)),n)})]).finally(()=>{o!==void 0&&clearTimeout(o)})}a(uo,"readBeforeDeadline");async function fo(e,t){let r=e.getReader();try{return await t(r)}catch(n){throw r.cancel().catch(()=>{}),n}finally{try{r.releaseLock()}catch{}}}a(fo,"withReader");var mo=8,po=2e4,go=15e3,ce=new Map;async function wt(e,t,r){if(!r.deploymentId||!r.projectId)throw new Error("email deployment identity missing");let n=r.receiptId;if(!/^[a-f0-9-]{16,64}$/.test(n))throw new Error("invalid email receipt ID");let o=ce.get(r.projectId)??0;if(o>=mo)throw new Error("email project concurrency exceeded");ce.set(r.projectId,o+1);let s=Date.now()+po,i=new AbortController,l;try{let c=await xr({version:yt,receiptId:n,projectId:r.projectId,deploymentId:r.deploymentId,recipient:r.envelope.to,expiresAt:Date.now()+3e4},t.EMAIL_SIGNING_SECRET),d=s-Date.now();if(d<=0)throw new Error("email tenant request timeout");let u;try{l=await Promise.race([e.fetch(`https://worker${Tr}`,{method:"POST",headers:{"content-type":"application/vnd.void.email-envelope; version=1","x-void-email-receipt":c,"x-void-email-recipient":r.envelope.to},body:Or(r.envelope),signal:i.signal}),new Promise((f,h)=>{u=setTimeout(()=>{i.abort(),h(new Error("email tenant request timeout"))},d)})])}finally{u!==void 0&&clearTimeout(u)}if(!l.ok||l.headers.get("content-encoding")||l.headers.get("content-type")!==`application/vnd.void.email-actions; version=${yt}`||!l.body)throw new Error(`invalid email tenant response (${l.status})`);let m=Math.min(go,s-Date.now());if(m<=0)throw new Error("email tenant request timeout");return{actions:await Pr(l.body,m),receiptId:n}}finally{i.abort(),l?.body?.cancel().catch(()=>{});let c=(ce.get(r.projectId)??1)-1;c===0?ce.delete(r.projectId):ce.set(r.projectId,c)}}a(wt,"dispatchBoundedEmailToTenant");function de(e,t){switch(typeof e){case"string":return S(e,t);case"number":case"boolean":case"undefined":return String(e);case"object":return e===null?"null":S(Object.prototype.toString.call(e),64);default:return`[${typeof e}]`}}a(de,"describeUntrusted");function Hr(e){let t=[e.slug,e.alias,e.mailbox].flatMap(r=>typeof r=="string"?[r.toLowerCase()]:[]);return[...new Set(t)]}a(Hr,"mailboxNames");function ho(e){return{routeId:e.routeId,routeGeneration:e.routeGeneration,connectionId:e.connectionId,addressing:e.addressing,domain:e.domain,projectSlug:e.slug}}a(ho,"receiptRouteFence");var L=10*1024*1024,ue=1024,At=128*1024,yo=1e3,kr=100,Fr=320,Dr=32,$e=1024,Lr=5*1024*1024,Cr=8*1024*1024,bo=15e3,He=class extends Error{constructor(r){super(`inbound message exceeds ${L} bytes (got ${r})`);this.size=r;this.name="InboundTooLargeError"}size;static{a(this,"InboundTooLargeError")}},Fe=class extends Error{static{a(this,"InboundTooManyHeadersError")}constructor(){super(`inbound message carries more than ${ue} headers`),this.name="InboundTooManyHeadersError"}},Be=class extends Error{static{a(this,"InboundHeadersTooLargeError")}constructor(){super(`inbound headers exceed ${At} bytes`),this.name="InboundHeadersTooLargeError"}};function Et(e){return typeof e=="string"&&e.length<=Fr&&(0,$r.validate)(e)}a(Et,"isValidEmailAddress");function U(e){return de(e,Fr)}a(U,"logAddress");function wo(e){if(typeof e!="object"||e===null)return console.error("[email-router] action list dropped: forward headers is not a plain object"),!1;let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return console.error("[email-router] action list dropped: forward headers is not a plain object"),!1;let r=G(e),n=Object.keys(r);if(n.length>Dr)return console.error(`[email-router] action list dropped: forward has ${n.length} headers (max ${Dr})`),!1;for(let o of n){let s=r[o];if(o.length>$e)return console.error(`[email-router] action list dropped: forward header name exceeds ${$e} characters`),!1;if(typeof s!="string")return console.error(`[email-router] action list dropped: forward header "${S(o,64)}" value is not a string`),!1;if(s.length>$e)return console.error(`[email-router] action list dropped: forward header "${S(o,64)}" value exceeds ${$e} characters`),!1}return!0}a(wo,"forwardHeadersWithinBounds");function Eo(e,t){if(!/^[\u0021-\u007e]+$/.test(e))return!1;let r=e.toLowerCase(),n=r.indexOf("@");return n<=0?!1:r.slice(n+1)!==t.domain||t.customDomain?!0:t.names.includes(r.slice(0,n).split("+")[0])}a(Eo,"isPermittedReplySender");async function Br(e,t,r,n){let o=ae(t)??"void email",s=String(e.to??"").toLowerCase(),i=s.split("@")[0]??"",l=i.indexOf("+"),c=l===-1?i:i.slice(0,l),d=(n.mailbox??n.slug).toLowerCase(),u=s.indexOf("@"),m=u===-1?"":s.slice(u+1);if(!c){e.setReject(`${o}: missing project slug in recipient`);return}if(n.addressing!=="custom"&&Ht(c)){e.setReject(`${o}: "${S(c,64)}" is a reserved platform address`);return}if(!n.projectId||!n.workerName||!n.deploymentId||n.domain?.toLowerCase()!==m||n.addressing==="shared"&&d!==c){e.setReject(`${o}: authoritative route mismatch`);return}let p=n.workerName,f=n.projectId,h;try{h=n.limits?t.DISPATCH.get(p,{},{limits:n.limits}):t.DISPATCH.get(p)}catch(A){throw console.error(`[email-router] DISPATCH.get(${S(p,320)}) failed:`,A),new Error("email worker temporarily unavailable")}if(typeof e.rawSize=="number"&&e.rawSize>L){e.setReject(`${o}: message too large (max ${L} bytes)`);return}let y;try{y=await _o(e),n.addressing==="custom"&&(y.viaDomain=m)}catch(A){if(A instanceof He){e.setReject(`${o}: message too large (max ${L} bytes)`);return}if(A instanceof Fe){e.setReject(`${o}: too many headers (max ${ue})`);return}if(A instanceof Be){e.setReject(`${o}: headers too large (max ${At} bytes)`);return}console.error(`[email-router] failed to read message body for ${S(c,64)}:`,A),e.setReject(`${o}: could not read inbound message body`);return}let b=crypto.randomUUID(),R={projectId:f,receiptId:b,transport:"native"},E;try{await q(t,b,f,"received",ho(n))}catch{throw new Error("email admission temporarily unavailable")}try{E=(await wt(h,t,{projectId:f,deploymentId:n.deploymentId,envelope:y,receiptId:b})).actions}catch(A){await q(t,b,f,"handler_failed").catch(()=>{});let w=A instanceof Error?A.message.slice(0,320):de(A,320);throw console.error(`[email-router] dispatch to ${S(p,320)} failed:`,w),new Error("email handler execution unresolved")}try{await q(t,b,f,"handler_completed")}catch{console.error("[email-router] handler completed but receipt status could not be saved");return}try{await qr(t,e,E,R,{customDomain:n.addressing==="custom",names:Hr(n),domain:m})}catch{console.error("[email-router] action execution unresolved",b);return}r.waitUntil(Rt(t,f,e,E))}a(Br,"routeInbound");async function Gr(e,t,r){let{stub:n,projectId:o,domain:s,envelope:i,authoritative:l,receiptId:c}=r;if(l.projectId!==o||!l.workerName||!l.slug||l.domain?.toLowerCase()!==s)return{reject:!0};let d=l.workerName,u=Ro(i),m={projectId:o,receiptId:c,transport:"relay"},p;try{p=(await wt(n,e,{projectId:o,deploymentId:l.deploymentId,envelope:i,receiptId:c})).actions}catch(f){await q(e,c,o,"handler_failed").catch(()=>{});let h=f instanceof Error?f.message.slice(0,320):de(f,320);return console.error(`[email-relay] dispatch to ${S(d,320)} failed:`,h),t.waitUntil(Rt(e,o,u.message,[{type:"reject",reason:"dispatch-error"}])),{reject:!0,temporary:!0}}try{await q(e,c,o,"handler_completed")}catch{return console.error("[email-relay] handler completed but receipt status could not be saved"),{reject:!1}}try{await qr(e,u.message,p,m,{customDomain:l.addressing==="custom",names:Hr(l),domain:s})}catch{return console.error("[email-relay] action execution unresolved",c),{reject:!1}}return t.waitUntil(Rt(e,o,u.message,p)),{reject:u.rejectedReason()!==null}}a(Gr,"routeRelayed");function Ro(e){let t=null;return{message:{from:e.from,to:e.to,rawSize:e.rawSize,headers:new Headers(e.headers),raw:le(e.raw),setReject(n){t=n},async forward(n,o){throw new $("relayed forward requires a native email event")}},rejectedReason:a(()=>t,"rejectedReason")}}a(Ro,"createRelayedMessage");async function Ao(e,t,r,n,o){let s=r.slice(r.indexOf("@")+1).toLowerCase();if(s===ae(e)){let c=e.SEND_EMAIL;if(!c||typeof c.send!="function")throw new Error("shared email binding is unavailable");return async d=>(await c.send(new Ur(r,d,le(n))))?.messageId}let i=await Se(e,s,t);if(!i||o&&i.accountId!==o)throw new Error("could not lease the domain credential");let l=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(n);return async(c,d=3e4)=>{let u;try{u=await mt({accountId:i.accountId,bearer:_e(i),from:r,recipients:[c],mimeMessage:l},d)}catch{throw new Error("email sending request failed")}if(!u.ok)throw u.status>=500||u.status===408?new Error("email sending API outcome unknown"):new $(`email sending API returned ${u.status}`);let m=u.data;if(typeof m!="object"||m===null||!("success"in m))throw new Error("email sending API response invalid");if(m.success===!1)throw new $("email sending API refused the message");if(m.success!==!0)throw new Error("email sending API response invalid");let p=pt("result"in m?m.result:void 0);if(!p)throw new Error("email sending API response invalid");let f=gt(p,c);if(f==="permanent_bounce")throw new $("recipient permanently bounced");if(f==="suppressed")throw new $("recipient is on the suppression list");if(f==="outcome_unknown")throw new Error("email sending API did not classify the recipient");return p.messageId}}a(Ao,"prepareRelayedReply");async function Rt(e,t,r,n){if(!t){console.error(`[email-router] cannot log inbound delivery: routing entry has no projectId (to=${S(String(r.to??""),320)})`);return}let o=n.some(s=>s&&typeof s=="object"&&s.type==="reject")?"rejected":n.length===0?"accepted":"handled";try{await Sr(t,{from:String(r.from??""),to:String(r.to??""),byteSize:r.rawSize??0,status:o})}catch(s){console.error("[email-router] log-recv failed:",s)}}a(Rt,"logRecv");async function _o(e){let t=[],r=0,n=new TextEncoder;for(let i of e.headers){if(t.length>=ue)throw new Fe;if(r+=n.encode(i[0]).byteLength+n.encode(i[1]).byteLength,r>At)throw new Be;t.push(i)}let o=await So(e.raw),s=Object.fromEntries(t);return{from:String(e.from??""),to:String(e.to??""),headers:s,raw:o,rawSize:e.rawSize??o.byteLength}}a(_o,"buildEnvelope");async function So(e){let t=e.getReader(),r=[],n=0,o=Date.now()+bo;try{for(;;){let l=o-Date.now();if(l<=0)throw new Error("inbound message stream timed out");let c,{value:d,done:u}=await Promise.race([t.read(),new Promise((m,p)=>{c=setTimeout(()=>p(new Error("inbound message stream timed out")),l)})]).finally(()=>{c!==void 0&&clearTimeout(c)});if(u)break;if(n+=d.byteLength,n>L)throw new He(n);r.push(d)}}catch(l){throw t.cancel().catch(()=>{}),l}finally{try{t.releaseLock()}catch{}}let s=new Uint8Array(n),i=0;for(let l of r)s.set(l,i),i+=l.byteLength;return s}a(So,"readStreamToBytes");var $=class extends Error{static{a(this,"DefinitiveEmailActionError")}};async function Io(e,t){if(e.length>kr)return console.error(`[email-router] action list dropped: ${e.length} actions returned (max ${kr})`),null;let r=[],n=0;for(let o of e){if(!o||typeof o!="object")return console.error(`[email-router] dropping non-object action: ${de(o,320)}`),null;if(o.type==="reject"){let s=typeof o.reason=="string"?o.reason:"",i=s.length>0?S(s,yo):"rejected by handler";return r.push({type:"reject",reason:i}),r}if(o.type==="forward"){if(!Et(o.to))return console.error(`[email-router] forward dropped: invalid "to" address ${U(o.to)}`),null;let s;if(o.headers){if(!wo(o.headers))return null;try{s=new Headers(o.headers)}catch(i){return console.error("[email-router] action list dropped: forward headers invalid:",i instanceof Error?S(i.message,320):S(String(i),320)),null}}r.push({type:"forward",to:o.to,headers:s})}else if(o.type==="reply"){if(!Et(o.from)||!Et(o.to))return console.error(`[email-router] reply dropped: invalid address (from=${U(o.from)} to=${U(o.to)})`),null;if(!Eo(o.from,t))return console.error(`[email-router] reply dropped: sender not owned by project "${S(t.names[0]??"",64)}" (from=${U(o.from)})`),null;if(!(o.raw instanceof Uint8Array))return console.error(`[email-router] reply dropped: raw is not a Uint8Array (from=${U(o.from)})`),null;let s=o.raw.byteLength;if(s>Lr)return console.error(`[email-router] reply dropped: raw is ${s} bytes (max ${Lr}) (from=${U(o.from)})`),null;if(n+s>Cr)return console.error(`[email-router] reply dropped: cumulative reply bytes ${n+s} exceed this delivery's budget of ${Cr} (from=${U(o.from)})`),null;let i=ft(o.raw);if(!i.ok||i.addrSpec.toLowerCase()!==o.from.toLowerCase())return console.error(`[email-router] reply dropped: MIME From is not the envelope sender (from=${U(o.from)}, ${i.ok?"header names another address":i.reason})`),null;n+=s,r.push({type:"reply",from:o.from,to:o.to,raw:o.raw})}else return console.warn(`[email-router] dropping unknown action type: ${de(o.type,320)}`),null}return r}a(Io,"validateActions");async function qr(e,t,r,n,o){let s=await Io(r,o);if(s===null){await q(e,n.receiptId,n.projectId,"actions_rejected").catch(()=>{console.error("[email-router] could not record rejected actions")});return}await Mo(e,t,s,n)}a(qr,"enactActions");function vo(e,t){let r=e.join(","),n=t.join(",");return r<n?-1:r>n?1:0}a(vo,"compareHeaderEntries");async function Mo(e,t,r,n){if(!n.projectId||!n.receiptId){console.error("[email-router] action admission unavailable: missing project or receipt identity");return}let o=ve();for(let[s,i]of r.entries()){if(i.type==="reject"){t.setReject(i.reason);return}if(o.expired()){console.error("[email-router] action batch deadline elapsed before admission");break}let l=i.to.toLowerCase(),c=i.type==="reply"?i.from:t.to,d=await Re(i.type,c,[l],i.type==="reply"?i.raw:new TextEncoder().encode(JSON.stringify([...i.headers?.entries()??[]].sort(vo)))),u;try{u=await Ae(e,{projectId:n.projectId,kind:i.type,key:`${n.receiptId}:${s}:${d.slice(0,16)}`,digest:d,from:c,recipients:[l],transport:n.transport==="relay"?i.type==="reply"&&i.from.slice(i.from.indexOf("@")+1).toLowerCase()===ae(e)?"binding":"send_raw":i.type==="forward"?"native_forward":"native_reply",receiptId:n.receiptId})}catch(f){console.error("[email-router] action admission unavailable:",f instanceof Error?f.message:"unknown");continue}let m=u.recipients.find(f=>f.recipient===l);if(u.replay||m?.state!=="reserved")continue;let p;if(n.transport==="relay"&&i.type==="reply")try{p=await Ao(e,n.projectId,i.from,i.raw,u.accountId)}catch{await P(e,u.operationId,[l],"cancelled").catch(()=>{console.error("[email-router] could not cancel unsubmitted relayed reply")}),console.error("[email-router] relayed reply could not be prepared");continue}if(o.expired()){let f=await jr(e,u.operationId,l);console.error(f?"[email-router] action batch deadline elapsed; reservation cancelled":"[email-router] action batch deadline elapsed; cancellation unresolved");break}try{await re(e,u.operationId,[l])}catch{let f=await jr(e,u.operationId,l);console.error(f?"[email-router] attempt did not start; reservation cancelled":"[email-router] could not confirm attempt status");continue}try{let f;i.type==="forward"?await o.run(()=>t.forward(l,i.headers)):p?f=await o.run(()=>p(l,o.remainingMs())):await o.run(()=>{if(!t.reply)throw new Error("native email reply requires a native event");return t.reply(new Ur(i.from,l,le(i.raw)))});try{await P(e,u.operationId,[l],"provider_accepted",{providerReference:f})}catch{console.error("[email-router] provider accepted action but outcome ledger write failed")}}catch(f){let h=f instanceof $;try{await P(e,u.operationId,[l],h?"failed":"outcome_unknown",{errorCode:h?"UPSTREAM_ERROR":"OUTCOME_UNKNOWN"})}catch{}console.error(h?"[email-router] action provider refused":"[email-router] action provider outcome unknown")}}}a(Mo,"enactSanitized");async function jr(e,t,r){try{return(await P(e,t,[r],"cancelled")).recipients.some(o=>o.recipient===r&&o.state==="cancelled")}catch{return!1}}a(jr,"cancelUnstartedAction");var qe=new TextEncoder,Mt=new TextDecoder,_t=128*1024,vt=320,No=2,Xr="/email/destinations/confirm",To=4*1024,zr=32*1024,Vr=5e3,St=0,C=class extends Error{constructor(r,n){super(r);this.status=n;this.name="MimeHeaderError"}status;static{a(this,"MimeHeaderError")}};function Nt(e){return e.PLATFORM_TRAFFIC_STATE==="staging"||e.PLATFORM_TRAFFIC_STATE==="sandbox-drain"}a(Nt,"isTrafficPaused");async function Wr(e){if(St>=No)throw new Error("email gateway busy");St++;try{return await e()}finally{St--}}a(Wr,"withDeliverySlot");async function Yr(e,t){if(!t)throw new Error("Email signing key is not configured");let r=await crypto.subtle.importKey("raw",qe.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,qe.encode(e))),o="";for(let s of n)o+=String.fromCharCode(s);return btoa(o).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}a(Yr,"sign");function Oo(e){let t=G(e);return typeof t.routeId=="string"&&typeof t.routeGeneration=="number"&&Number.isSafeInteger(t.routeGeneration)&&t.routeGeneration>=1&&typeof t.projectId=="string"&&typeof t.connectionId=="string"&&typeof t.workerName=="string"&&typeof t.deploymentId=="string"&&typeof t.slug=="string"&&(t.mailbox===void 0||typeof t.mailbox=="string")&&(t.alias===void 0||typeof t.alias=="string")&&typeof t.domain=="string"&&(t.addressing==="shared"||t.addressing==="custom")&&(t.limits===void 0||typeof t.limits=="object"&&t.limits!==null&&!Array.isArray(t.limits)&&Object.values(t.limits).every(r=>typeof r=="number"))}a(Oo,"isAuthoritativeRoute");async function Kr(e,t){let r=Date.now()+5e3,n=new AbortController,o=a(async y=>{let b=r-Date.now();if(b<=0)throw n.abort(),new Error("ingress resolution timeout");let R;try{return await Promise.race([y(),new Promise((E,A)=>{R=setTimeout(()=>{n.abort(),A(new Error("ingress resolution timeout"))},b)})])}finally{R!==void 0&&clearTimeout(R)}},"beforeDeadline"),s=await Yr(`email-ingress-v1
|
|
4
4
|
${t.accountId}
|
|
5
5
|
${t.zoneId}
|
|
6
6
|
${t.ingressName}
|
|
7
|
-
${t.to.toLowerCase()}`,e.EMAIL_SIGNING_SECRET),
|
|
8
|
-
`),n=Object.create(null),o="",
|
|
7
|
+
${t.to.toLowerCase()}`,e.EMAIL_SIGNING_SECRET),i=await o(()=>e.API.fetch("https://api/internal/email/resolve-ingress",{method:"POST",headers:{"content-type":"application/json","x-void-internal":s},body:JSON.stringify(t),signal:n.signal}));if(!i.ok){if(i.body?.cancel().catch(()=>{}),i.status>=500||i.status===429)throw new Error("email routing unavailable");return null}let l=Number(i.headers.get("content-length"));if(Number.isFinite(l)&&l>4096)throw i.body?.cancel().catch(()=>{}),new Error("invalid email routing response");let c=i.body?.getReader();if(!c)throw new Error("invalid email routing response");let d=[],u=0;try{for(;;){let y=await o(()=>c.read());if(y.done)break;if(u+=y.value.byteLength,u>4096)throw new Error("invalid email routing response");d.push(y.value)}}finally{c.cancel().catch(()=>{});try{c.releaseLock()}catch{}}let m=new Uint8Array(u),p=0;for(let y of d)m.set(y,p),p+=y.byteLength;let f=Mt.decode(m),h;try{h=JSON.parse(f)}catch{throw new Error("invalid email routing response")}if(!Oo(h))throw new Error("invalid email routing response");return h}a(Kr,"resolveIngress");async function xo(e,t){if(!e||!Number.isSafeInteger(t)||t<0||t>L)throw new Error("invalid MIME length");let r=e.getReader(),n=new Uint8Array(t),o=0,s=Date.now()+15e3;try{for(;;){let i=s-Date.now();if(i<=0)throw new Error("MIME timeout");let l,c=await Promise.race([r.read(),new Promise((d,u)=>{l=setTimeout(()=>u(new Error("MIME timeout")),i)})]).finally(()=>{l!==void 0&&clearTimeout(l)});if(c.done)break;if(o+=c.value.byteLength,o>t||o>L)throw new Error("MIME too large");n.set(c.value,o-c.value.byteLength)}if(o!==t)throw new Error("truncated MIME");return n}catch(i){throw r.cancel().catch(()=>{}),i}finally{try{r.releaseLock()}catch{}}}a(xo,"readMime");function Po(e){let t=-1;for(let i=0;i<e.length-3&&i<_t+4;i++)if(e[i]===13&&e[i+1]===10&&e[i+2]===13&&e[i+3]===10){t=i;break}if(t<0)throw new C("invalid MIME headers",e.byteLength>_t?413:400);if(t>_t)throw new C("MIME headers too large",413);let r=Mt.decode(e.subarray(0,t)).split(`\r
|
|
8
|
+
`),n=Object.create(null),o="",s=0;for(let i of r){if(++s>ue)throw new C("too many MIME headers",413);if(/^[ \t]/.test(i)){if(!o)throw new C("invalid MIME header fold",400);n[o]+=` ${i.trim()}`;continue}let l=i.indexOf(":");if(l<=0)throw new C("invalid MIME header",400);let c=i.slice(0,l).toLowerCase();if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c))throw new C("invalid MIME header name",400);n[c]=n[c]?`${n[c]}, ${i.slice(l+1).trim()}`:i.slice(l+1).trim(),o=c}return n}a(Po,"parseHeaders");async function ko(e,t,r){if(Nt(t))return new Response(null,{status:503});if(e.headers.get("content-encoding"))return new Response(null,{status:415});let n=e.headers.get("x-void-email-account")??"",o=e.headers.get("x-void-email-zone")??"",s=e.headers.get("x-void-email-ingress")??"",i=e.headers.get("x-void-email-request-id")??"",l=e.headers.get("x-void-email-from")??"",c=e.headers.get("x-void-email-to")??"",d=e.headers.get("authorization")??"";if([n,o,s,l,c,d].some(y=>!y||y.length>vt)||!d.startsWith("Bearer ")||!/^[a-f0-9-]{36}$/.test(i))return new Response(null,{status:400});let u=e.headers.get("content-length");if(u===null||!/^\d+$/.test(u))return new Response(null,{status:411});let m=Number(u);if(!Number.isSafeInteger(m)||m<0)return new Response(null,{status:411});if(m>L)return new Response(null,{status:413});let p;try{p=await Kr(t,{accountId:n,zoneId:o,ingressName:s,from:l,to:c,secret:d.slice(7)})}catch{return new Response(null,{status:503})}if(!p)return new Response(null,{status:403});let f;try{f=await xo(e.body,m)}catch(y){return console.error("[email-gateway] ingress failed:",y instanceof Error?y.message.slice(0,200):"unknown"),new Response(null,{status:502})}let h;try{h=Po(f)}catch(y){if(y instanceof C)return new Response(null,{status:y.status});throw y}try{let y=c.slice(c.lastIndexOf("@")+1).toLowerCase();if(y!==p.domain)return new Response(null,{status:403});let b={from:l,to:c,raw:f,rawSize:f.byteLength,headers:h,...p.addressing==="custom"?{viaDomain:y}:{}},R;try{R=p.limits?t.DISPATCH.get(p.workerName,{},{limits:p.limits}):t.DISPATCH.get(p.workerName)}catch(x){return console.error("[email-gateway] tenant dispatch stub unavailable:",x),new Response(null,{status:503})}let E=await It(qe.encode(JSON.stringify([p.connectionId,i]))),A=await It(qe.encode(JSON.stringify([l,c,await It(f)]))),w={receiptId:E,projectId:p.projectId,payloadDigest:A,route:{routeId:p.routeId,routeGeneration:p.routeGeneration,connectionId:p.connectionId,addressing:p.addressing,domain:p.domain,projectSlug:p.slug}},_;try{_=await Ut(t,w)}catch(x){if(x instanceof Error&&x.message==="IDEMPOTENCY_CONFLICT")return new Response(null,{status:409});throw x}if(_.state==="completed"&&typeof _.reject=="boolean")return new Response(null,{status:_.reject?403:204,headers:{"x-void-email-receipt":E}});if(_.state!=="claimed")return new Response(null,{status:503,headers:{"x-void-email-receipt":E}});let v=await Gr(t,r,{stub:R,projectId:p.projectId,domain:y,envelope:b,authoritative:p,receiptId:E});if(v.temporary)return new Response(null,{status:503});try{await $t(t,w,v.reject)}catch{console.error("[email-gateway] receipt completion remains unresolved",E)}return new Response(null,{status:v.reject?403:204,headers:{"x-void-email-receipt":E}})}catch(y){return console.error("[email-gateway] ingress failed:",y instanceof Error?y.message.slice(0,200):"unknown"),new Response(null,{status:502})}}a(ko,"ingress");async function It(e){return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",e)),t=>t.toString(16).padStart(2,"0")).join("")}a(It,"sha256");async function Do(e,t){if(e.headers.get("content-encoding"))return e.body?.cancel().catch(()=>{}),new Response(null,{status:400});let r=e.headers.get("content-length");if(r&&(!/^\d+$/.test(r)||Number(r)>1024))return e.body?.cancel().catch(()=>{}),new Response(null,{status:400});let n=e.headers.get("authorization")??"";if(!n.startsWith("Bearer ")||n.length>vt)return new Response(null,{status:403});let o=e.body?.getReader();if(!o)return new Response(null,{status:400});let s=new Uint8Array(1024),i=0,l=Date.now()+5e3;try{for(;;){let b=l-Date.now();if(b<=0)return new Response(null,{status:400});let R,E=await Promise.race([o.read(),new Promise((A,w)=>{R=setTimeout(()=>w(new Error("probe timeout")),b)})]).finally(()=>{R!==void 0&&clearTimeout(R)});if(E.done)break;if(i+=E.value.byteLength,i>s.byteLength)return new Response(null,{status:400});s.set(E.value,i-E.value.byteLength)}}catch{return new Response(null,{status:400})}finally{o.cancel().catch(()=>{});try{o.releaseLock()}catch{}}if(i===0||r&&i!==Number(r))return new Response(null,{status:400});let c;try{c=JSON.parse(Mt.decode(s.subarray(0,i)))}catch{return new Response(null,{status:400})}if(!c||typeof c!="object")return new Response(null,{status:400});let{accountId:d,zoneId:u,ingressName:m}=G(c);if([d,u,m].some(b=>typeof b!="string"||!b||b.length>vt))return new Response(null,{status:400});let p=await Yr(`email-probe-v1
|
|
9
9
|
${d}
|
|
10
10
|
${u}
|
|
11
|
-
${
|
|
11
|
+
${m}`,t.EMAIL_SIGNING_SECRET),f=new AbortController,h=Date.now()+5e3,y;try{let b=await Promise.race([t.API.fetch("https://api/internal/email/probe-ingress",{method:"POST",headers:{"content-type":"application/json","x-void-internal":p},body:JSON.stringify({accountId:d,zoneId:u,ingressName:m,secret:n.slice(7)}),signal:f.signal}),new Promise((R,E)=>{y=setTimeout(()=>{f.abort(),E(new Error("email probe timeout"))},Math.max(0,h-Date.now()))})]);return b.body?.cancel().catch(()=>{}),new Response(null,{status:b.status===204?204:403})}catch{return new Response(null,{status:503})}finally{y!==void 0&&clearTimeout(y)}}a(Do,"probe");function Ge(e,t,r){let n=new Headers({"cache-control":"no-store","content-security-policy":"frame-ancestors 'none'","referrer-policy":"no-referrer","x-content-type-options":"nosniff","x-frame-options":"DENY"});return r&&n.set("content-type",r),new Response(e,{status:t,headers:n})}a(Ge,"confirmationResponse");async function Lo(e,t,r){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>zr)throw new Error("confirmation response too large");let o=e.body?.getReader();if(!o)return null;let s=new Uint8Array(zr),i=0;try{for(;;){let l=t-Date.now();if(l<=0)throw new Error("confirmation response timeout");let c,d=await Promise.race([o.read(),new Promise((u,m)=>{c=setTimeout(()=>{r.abort(),m(new Error("confirmation response timeout"))},l)})]).finally(()=>{c!==void 0&&clearTimeout(c)});if(d.done)return s.slice(0,i);if(i+=d.value.byteLength,i>s.byteLength)throw new Error("confirmation response too large");s.set(d.value,i-d.value.byteLength)}}finally{o.cancel().catch(()=>{});try{o.releaseLock()}catch{}}}a(Lo,"readConfirmationResponse");async function Co(e,t){let n=[...new URL(e.url).searchParams.entries()];if(n.length!==1||n[0][0]!=="token"||!n[0][1]||n[0][1].length>To||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(n[0][1]))return Ge(null,400);if(Nt(t))return Ge(null,503);let o=Date.now()+Vr,s=new AbortController,i,l;try{let c=new URL(`https://api${Xr}`);c.searchParams.set("token",n[0][1]);let d=t.API.fetch(c.toString(),{method:e.method,redirect:"manual",signal:s.signal});d.then(m=>{s.signal.aborted&&m!==i&&m.body?.cancel().catch(()=>{})},()=>{}),i=await Promise.race([d,new Promise((m,p)=>{l=setTimeout(()=>{s.abort(),p(new Error("confirmation request timeout"))},Vr)})]),l!==void 0&&(clearTimeout(l),l=void 0);let u=await Lo(i,o,s);return Ge(u,i.status,i.headers.get("content-type"))}catch{return Ge(null,503)}finally{s.abort(),l!==void 0&&clearTimeout(l),i?.body?.cancel().catch(()=>{})}}a(Co,"confirmDestination");var Lc={async fetch(e,t,r){let n=new URL(e.url);if(e.method==="GET"&&n.pathname==="/health")return Response.json({ok:!0,installationId:t.PLATFORM_INSTALLATION_ID,platformVersion:t.PLATFORM_VERSION,emailProtocolVersion:1});if((e.method==="GET"||e.method==="POST")&&n.pathname===Xr)return Co(e,t);if(e.method!=="POST")return new Response(null,{status:404});if(n.pathname==="/email/probe")return Do(e,t);if(n.pathname==="/email/ingress")try{return await Wr(()=>ko(e,t,r))}catch{return new Response(null,{status:503})}return new Response(null,{status:404})},async email(e,t,r){if(Nt(t))throw new Error("Email gateway temporarily unavailable");let n=t.EMAIL_SHARED_ACCOUNT_ID,o=t.EMAIL_SHARED_ZONE_ID,s=t.EMAIL_SHARED_INGRESS_NAME;if(!n||!o||!s){e.setReject("Email routing is not configured");return}let i;try{i=await Kr(t,{accountId:n,zoneId:o,ingressName:s,from:e.from,to:e.to,native:!0})}catch{throw new Error("Email route temporarily unavailable")}if(!i){e.setReject("Email route unavailable");return}await Wr(()=>Br(e,t,r,i))}};export{Lc as default};
|
|
@@ -2,18 +2,18 @@
|
|
|
2
2
|
"artifacts": {
|
|
3
3
|
"api": {
|
|
4
4
|
"path": "api/index.js",
|
|
5
|
-
"sha256": "
|
|
6
|
-
"size":
|
|
5
|
+
"sha256": "c8175c253bd020cea298b7008862aa4f5734c64004995ce0f96675b176072b8b",
|
|
6
|
+
"size": 5180968
|
|
7
7
|
},
|
|
8
8
|
"dispatch": {
|
|
9
9
|
"path": "dispatch/index.js",
|
|
10
|
-
"sha256": "
|
|
11
|
-
"size":
|
|
10
|
+
"sha256": "94e4ffd61c63018079fb64188ff74eae4f89813a94fe75aca59043734993ef36",
|
|
11
|
+
"size": 93950
|
|
12
12
|
},
|
|
13
13
|
"proxy": {
|
|
14
14
|
"path": "proxy/index.js",
|
|
15
|
-
"sha256": "
|
|
16
|
-
"size":
|
|
15
|
+
"sha256": "b8d7877a69dcfcc38441e2b175e9fed866bda39d2246625b0461c1127b57a89d",
|
|
16
|
+
"size": 89376
|
|
17
17
|
},
|
|
18
18
|
"tail": {
|
|
19
19
|
"path": "tail/index.js",
|
|
@@ -22,24 +22,25 @@
|
|
|
22
22
|
},
|
|
23
23
|
"emailGateway": {
|
|
24
24
|
"path": "emailGateway/index.js",
|
|
25
|
-
"sha256": "
|
|
26
|
-
"size":
|
|
25
|
+
"sha256": "39f814f0bd7ac9a4a2403e401c0c78c9051b0b7167cd7c4e0cf9d65489e11ce5",
|
|
26
|
+
"size": 84655
|
|
27
27
|
}
|
|
28
28
|
},
|
|
29
29
|
"appAccessSetup": 1,
|
|
30
30
|
"storageLocationHint": 1,
|
|
31
31
|
"runtimeLogs": 1,
|
|
32
|
+
"securityAudits": 1,
|
|
32
33
|
"deploymentExecution": 1,
|
|
33
34
|
"assets": {
|
|
34
35
|
"adminClient": {
|
|
35
36
|
"path": "api/assets/admin/client.js",
|
|
36
|
-
"sha256": "
|
|
37
|
-
"size":
|
|
37
|
+
"sha256": "9b9f57ad1fb59d5214e075d65c08285e1d60873790e2176b570c7c4bbc909353",
|
|
38
|
+
"size": 2018336
|
|
38
39
|
},
|
|
39
40
|
"adminStyle": {
|
|
40
41
|
"path": "api/assets/admin/style.css",
|
|
41
|
-
"sha256": "
|
|
42
|
-
"size":
|
|
42
|
+
"sha256": "0674b287ba73e928709e0b0accd40362a3459e9362773638dbe8cfb26be8d7ec",
|
|
43
|
+
"size": 356499
|
|
43
44
|
}
|
|
44
45
|
},
|
|
45
46
|
"authenticationProtocolVersion": 1,
|
|
@@ -47,7 +48,7 @@
|
|
|
47
48
|
"applicationRoutingVersion": 1,
|
|
48
49
|
"privatePreviews": 1,
|
|
49
50
|
"database": {
|
|
50
|
-
"journalSha256": "
|
|
51
|
+
"journalSha256": "da56dc7023083ef5d42c6ca9b80a2f9f1936ce5605614ede051bd935f03f69ed",
|
|
51
52
|
"lineage": "void-platform-postgresql-v1",
|
|
52
53
|
"migrations": [
|
|
53
54
|
{
|
|
@@ -397,6 +398,12 @@
|
|
|
397
398
|
"sha256": "afa559facd49146c2a57828e60ecae54b9cc824382fc2fb1b83d3ab9bc2fd3c5",
|
|
398
399
|
"tag": "0064_project_ai_logging",
|
|
399
400
|
"timestampMillis": 1794435917244
|
|
401
|
+
},
|
|
402
|
+
{
|
|
403
|
+
"index": 65,
|
|
404
|
+
"sha256": "c26c25f2b23795b3b5073a92d606cab74d82fe0cd8876921cc13fe85f5cfbb84",
|
|
405
|
+
"tag": "0065_security_audits",
|
|
406
|
+
"timestampMillis": 1794980793652
|
|
400
407
|
}
|
|
401
408
|
],
|
|
402
409
|
"protocolVersion": 1,
|
|
@@ -513,18 +520,46 @@
|
|
|
513
520
|
"platformVersion": "1.6.0",
|
|
514
521
|
"schemaDigest": "41c9f2abec1a793d64d2acd71aa2fd737c3b3a594bc3d1c3c19b9546da05263c"
|
|
515
522
|
},
|
|
523
|
+
{
|
|
524
|
+
"platformVersion": "1.6.1",
|
|
525
|
+
"schemaDigest": "41c9f2abec1a793d64d2acd71aa2fd737c3b3a594bc3d1c3c19b9546da05263c"
|
|
526
|
+
},
|
|
527
|
+
{
|
|
528
|
+
"platformVersion": "1.6.2",
|
|
529
|
+
"schemaDigest": "41c9f2abec1a793d64d2acd71aa2fd737c3b3a594bc3d1c3c19b9546da05263c"
|
|
530
|
+
},
|
|
516
531
|
{
|
|
517
532
|
"platformVersion": "1.7.0",
|
|
518
533
|
"schemaDigest": "41c9f2abec1a793d64d2acd71aa2fd737c3b3a594bc3d1c3c19b9546da05263c"
|
|
534
|
+
},
|
|
535
|
+
{
|
|
536
|
+
"platformVersion": "1.8.0",
|
|
537
|
+
"schemaDigest": "908e7aab4ad12e872e2e0e7e17bb5072971e9a260fb378f6f6abc43af68ea883"
|
|
538
|
+
},
|
|
539
|
+
{
|
|
540
|
+
"platformVersion": "1.9.0",
|
|
541
|
+
"schemaDigest": "908e7aab4ad12e872e2e0e7e17bb5072971e9a260fb378f6f6abc43af68ea883"
|
|
542
|
+
},
|
|
543
|
+
{
|
|
544
|
+
"platformVersion": "1.9.1",
|
|
545
|
+
"schemaDigest": "908e7aab4ad12e872e2e0e7e17bb5072971e9a260fb378f6f6abc43af68ea883"
|
|
546
|
+
},
|
|
547
|
+
{
|
|
548
|
+
"platformVersion": "1.10.0",
|
|
549
|
+
"schemaDigest": "908e7aab4ad12e872e2e0e7e17bb5072971e9a260fb378f6f6abc43af68ea883"
|
|
550
|
+
},
|
|
551
|
+
{
|
|
552
|
+
"platformVersion": "1.11.0",
|
|
553
|
+
"schemaDigest": "908e7aab4ad12e872e2e0e7e17bb5072971e9a260fb378f6f6abc43af68ea883"
|
|
519
554
|
}
|
|
520
555
|
],
|
|
521
|
-
"schemaDigest": "
|
|
556
|
+
"schemaDigest": "b1acb4109dac821bd00863007cb10b8ba8faa479e6feb26aaf7e28f35c288e97"
|
|
522
557
|
},
|
|
523
|
-
"platformVersion": "1.
|
|
558
|
+
"platformVersion": "1.12.1",
|
|
524
559
|
"safetyProtocols": {
|
|
525
560
|
"sandboxDrain": 3
|
|
526
561
|
},
|
|
527
562
|
"schemaVersion": 2,
|
|
528
|
-
"sourceRevision": "
|
|
563
|
+
"sourceRevision": "672aeb1f4dc6ed0fcd8f60beb0473096136c06b8",
|
|
529
564
|
"usageProtocolVersion": 2
|
|
530
565
|
}
|