@aiquants/daily-report 0.30.0 → 0.31.0
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/CHANGELOG.md +53 -0
- package/README.md +65 -32
- package/dist/client.d.mts +26 -3
- package/dist/client.d.ts +26 -3
- package/dist/client.js +4 -4
- package/dist/client.mjs +4 -4
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/server.js +4 -4
- package/dist/server.mjs +4 -4
- package/dist/styles/daily-report.standalone.css +1 -1
- package/package.json +5 -5
package/dist/server.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var Rr=e=>{throw TypeError(e)};var gr=(e,t,r)=>t.has(e)||Rr("Cannot "+r);var nt=(e,t,r)=>(gr(e,t,"read from private field"),r?r.call(e):t.get(e)),$t=(e,t,r)=>t.has(e)?Rr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Ft=(e,t,r,n)=>(gr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var te=()=>Math.floor(performance.now());var qt=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),at=class{constructor(t,r){this.config=t;this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,a=this.buckets.get(n);if(!a)return;let o=t.ttlMsOverride??this.config.defaultTtlMs;if(o-(a.expireAt-te())<o*r||this.inFlight.has(n))return;let i;i=(async()=>{let h=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===i&&this.buckets.set(n,{records:s,expireAt:te()+o,epoch:h}),s})(),this.inFlight.set(n,i),i.catch(()=>{}).finally(()=>{this.inFlight.get(n)===i&&this.inFlight.delete(n)})};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:a}=t,o=this.buckets.get(r);if(n&&(this.buckets.delete(r),this.inFlight.delete(r)),!n&&o&&o.expireAt>te())if(t.epochKey){let i=await this.epochStore.getEpoch(t.epochKey);if(i===null||o.epoch===i)return this.maybeRefreshAhead(t),a?o.records.map(h=>structuredClone(h)):o.records;this.buckets.delete(r)}else return this.maybeRefreshAhead(t),a?o.records.map(i=>structuredClone(i)):o.records;if(!n&&this.inFlight.has(r)){let i=await this.inFlight.get(r);return a?i.map(h=>structuredClone(h)):i}let l;l=(async()=>{let i=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null;t.onFetchStart?.();let h=await t.fetcher();if(n||this.inFlight.get(r)===l){let s=te()+(t.ttlMsOverride??this.config.defaultTtlMs);this.buckets.set(r,{records:h,expireAt:s,epoch:i}),this.buckets.size>500&&this.cleanExpired()}return h})(),n||this.inFlight.set(r,l);try{let i=await l;return a?i.map(h=>structuredClone(h)):i}finally{this.inFlight.get(r)===l&&this.inFlight.delete(r)}};this.clearAll=()=>{this.buckets.clear(),this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)}}cleanExpired(){let t=te();for(let[r,n]of this.buckets.entries())n.expireAt<=t&&this.buckets.delete(r)}};var xa=/^\d{4}-\d{2}-\d{2}$/,Ca=/^\d{4}\/\d{2}\/\d{2}$/,br=e=>e<10?`0${e}`:`${e}`,Sr=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=br(e.getMonth()+1),n=br(e.getDate());return`${t}-${r}-${n}`};var ue=e=>{if(e==null)return null;if(e instanceof Date)return Sr(e);let t=e.trim();if(t==="")return null;if(xa.test(t))return t;if(Ca.test(t))return t.replaceAll("/","-");let r=new Date(t);return Sr(r)};var ft="ids-stream";var Vt=e=>{let t=2166136261,r=-624069552;for(let n of e){let a=n.reportHubId;t^=a&255,t=Math.imul(t,16777619),t^=a>>>8&255,t=Math.imul(t,16777619),t^=a>>>16&255,t=Math.imul(t,16777619),t^=a>>>24&255,t=Math.imul(t,16777619),r^=a>>>24&255,r=Math.imul(r,16777619),r^=a>>>16&255,r=Math.imul(r,16777619),r^=a>>>8&255,r=Math.imul(r,16777619),r^=a&255,r=Math.imul(r,16777619);let o=n.businessDate;if(o===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let l=0;l<o.length;l++){let i=o.charCodeAt(l);t^=i&255,t=Math.imul(t,16777619),r^=i&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},Rt=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,Ar=e=>{for(let t=1;t<e.length;t++)if(Rt(e[t-1],e[t])>0)return!1;return!0};var Tr=(e,t)=>{let r=e.findIndex(n=>Rt({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var me=(e,t,r=console)=>{let n=a=>typeof a=="string"?[`${t} ${a}`]:[t,a];return{debug:(a,...o)=>{e<=0&&r.debug(...n(a),...o)},info:(a,...o)=>{e<=1&&r.info(...n(a),...o)},warn:(a,...o)=>{e<=2&&r.warn(...n(a),...o)},error:(a,...o)=>{e<=3&&r.error(...n(a),...o)}}};var Yt=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Dr=e=>Object.hasOwn(Yt,e);var Ma="download",va="thumbnail",Pa="1";var zt=e=>{let t=e.getAll(va),r=e.getAll(Ma);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Dr(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Pa?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var be=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var gt=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,a=new Map,o=l=>{let i={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(s=>[s,0]))};a.set(l,i),be(()=>{a.delete(l),i.count>0&&n(l,i)},t)};return{record:(l,i,h)=>{let s=a.get(l);if(s!==void 0){s.count+=1,s.tallies[i]+=1;return}h(),o(l)}}};var Wt="Cross-site request rejected",ka="Not Found",La=new Set(["same-origin","none"]),Na=new Set(["GET","HEAD","OPTIONS"]),_r=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}}),Oa=()=>_r(403,Wt),bt=()=>_r(404,ka),je=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:Oa}),Er=e=>new URL(e.url).pathname.endsWith(".data"),Ba=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},Ir=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Na.has(e.method)||Ba(e)):La.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},wr=["api","action","sse","attachment"],Ua=6e4,Ha="refusals",$a=32,Fa=/^[a-z-]+$/,jt=e=>{if(e===null)return"-";let t=e.slice(0,$a);return Fa.test(t)&&t===e?e:JSON.stringify(t)},xr=e=>{let t=gt({windowMs:Ua,tallies:wr,writeSuppressed:(r,{count:n,since:a,tallies:o})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${a} routes=${wr.map(l=>`${l}:${o[l]}`).join(",")}`)}});return(r,n)=>{let a=()=>{let{headers:o}=n;e.warn(`cross_site_rejected route=${r} site=${jt(o.get("Sec-Fetch-Site"))} mode=${jt(o.get("Sec-Fetch-Mode"))} dest=${jt(o.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(Ha,r,a)}};var Cr=(e,t)=>(r,n)=>{let a=n?"markAttachmentPresent":"markAttachmentMissing";e[a](r).catch(o=>{t.error(`${a} failed attachment=${r} message=${o instanceof Error?o.message:"unknown"}`)})};var qa=6e4/1e3,Va=5e3/1e3,Ya=new Map([[429,qa],[503,Va]]),ke=e=>{let t=Ya.get(e);return t===void 0?{}:{"Retry-After":String(t)}},vr="Too many requests",za="same-origin",ja="SAMEORIGIN",We=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":za,"X-Frame-Options":ja}),St=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...We});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Pr=(e,t)=>{if(e===null)return!1;for(let r of e.split(",")){let n=r.trim();if((n.startsWith("W/")?n.slice(2):n)===t)return!0}return!1},kr=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Wa=/^[\x20-\x7E]+$/,Ja=/^[\w.+-]+\/[\w.+-]+/,Jt=e=>e&&Wa.test(e)&&Ja.test(e)?e:null,Lr=e=>encodeURIComponent(e).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Nr=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),At={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},Or={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Tt=e=>typeof e=="string"&&Object.hasOwn(Or,e),Dt=e=>Or[e],Le="Attachment request failed";var Ga=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,Je=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Ga(r)}`),wt=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`);var Br=32*1024*1024,Ka=60,Xa=4,Qa=120,Za=2,eo=8*1024*1024,Re=(e,t,r)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r)return t;throw Je(e,`an integer >= ${r}`,t)},Ne=(e,t,r,n)=>t===void 0?n:Re(e,t,r),to=[["attachmentThumbnailRenderer",["readAttachment","attachmentIdCodec"]],["readAttachment",["attachmentIdCodec"]],["attachmentIdCodec",["readAttachment"]],["attachmentMaxBytes",["readAttachment"]],["attachmentRateLimitPerMinute",["readAttachment"]],["attachmentConcurrency",["readAttachment"]],["attachmentThumbnailRateLimitPerMinute",["attachmentThumbnailRenderer"]],["attachmentThumbnailConcurrency",["attachmentThumbnailRenderer"]],["attachmentThumbnailCacheBytes",["attachmentThumbnailRenderer"]]],Gt=e=>{for(let[t,r]of to){if(e[t]===void 0)continue;let n=r.find(a=>e[a]===void 0);if(n!==void 0)throw wt(n,`injected when ${t} is given`)}},Ur=(e,t)=>(Gt({attachmentIdCodec:t.idCodec,readAttachment:t.readAttachment,attachmentThumbnailRenderer:t.thumbnailRenderer,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes}),Object.freeze({originalRateLimitPerMinute:Ne("attachmentRateLimitPerMinute",e.attachmentRateLimitPerMinute,1,Ka),originalConcurrency:Ne("attachmentConcurrency",e.attachmentConcurrency,1,Xa),thumbnailRateLimitPerMinute:Ne("attachmentThumbnailRateLimitPerMinute",e.attachmentThumbnailRateLimitPerMinute,1,Qa),thumbnailConcurrency:Ne("attachmentThumbnailConcurrency",e.attachmentThumbnailConcurrency,1,Za),thumbnailCacheBytes:Ne("attachmentThumbnailCacheBytes",e.attachmentThumbnailCacheBytes,0,eo)}));var _t=e=>{let t=Re("limit",e.limit,1),r=Re("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:Re("queue.max",e.queue.max,0),maxPerOwner:Re("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:Re("queue.maxWaitMs",e.queue.maxWaitMs,1)},a=0,o=[],l=new Map,i=new Map,h=(d,S)=>d.get(S)??0,s=(d,S,b)=>{let g=h(d,S)+b;g<=0?d.delete(S):d.set(S,g)},D=d=>h(i,d)<r,p=d=>(a+=1,s(i,d,1),y(d)),_=()=>{for(;a<t;){let d=o.findIndex(b=>D(b.owner));if(d<0)return;let[S]=o.splice(d,1);s(l,S.owner,-1),S.grant(p(S.owner))}},y=d=>{let S=!1;return()=>{S||(S=!0,a-=1,s(i,d,-1),_())}};return{acquire:(d,S)=>{if(S.aborted)return Promise.resolve(null);if(a<t&&D(d))return Promise.resolve(p(d));if(n===null||o.length>=n.max||h(l,d)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:b}=n,g=E=>{let U=()=>{let O=o.indexOf(M);O<0||(o.splice(O,1),s(l,d,-1),B(),E(null))},A=be(U,b),B=()=>{clearTimeout(A),S.removeEventListener("abort",U)},M={owner:d,grant:O=>{B(),E(O)}};o.push(M),s(l,d,1),S.addEventListener("abort",U,{once:!0})};return new Promise(g)}}};var ro=1024,no=6e4,ao=e=>{Re("limitPerMinute",e,1);let t=new Map,r=(a,o)=>{o<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(o-a.lastRefillMs)*e/6e4),a.lastRefillMs=o)},n=(a,o)=>{let l=t.get(a);l&&t.delete(a);let i=l??{tokens:e,lastRefillMs:o};r(i,o),t.set(a,i);for(let h of t.keys()){if(t.size<=ro)break;t.delete(h)}return i};return{consume:(a,o)=>{let l=n(a,o);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,o,l)=>{let i=t.get(a);i&&(r(i,o),i.tokens=Math.min(e,i.tokens+l))}}},ot=e=>{let{reason:t,logger:r}=e,n=ao(e.limitPerMinute),a=e.variant===null?"":` variant=${e.variant}`,o=gt({windowMs:no,tallies:[t],writeSuppressed:(l,{count:i,since:h})=>{r.warn(`${t}_suppressed count=${i} since=${h} viewer=${l}${a}`)}});return{spend:({attachmentId:l,internalUserId:i,fail:h})=>n.consume(i,te())?null:(o.record(i,t,()=>r.warn(`429 attachment=${l} viewer=${i}${a} reason=${t}`)),h(429,vr,ke(429))),refund:(l,i)=>{n.refund(l,te(),i)}}};var oo=256*1024,Hr=6e4,io=e=>Math.ceil(e/2),so=new Uint8Array(new ArrayBuffer(0)),lo=(e,t)=>{let r=e,n=0,a,o=()=>{clearTimeout(a),r=so,t()},l=i=>{clearTimeout(a),a=be(()=>{i.error(new Error(`attachment body idle for ${Hr} ms`)),o()},Hr)};return new ReadableStream({start(i){l(i)},pull(i){let h=Math.min(n+oo,r.byteLength);if(h>n&&i.enqueue(r.slice(n,h)),n=h,n>=r.byteLength){i.close(),o();return}l(i)},cancel(){o()}},{highWaterMark:0})},$r=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:a,recordObjectState:o}=e,l=t.attachmentDelivery,i=ot({reason:"rate_limit",limitPerMinute:e.rateLimitPerMinute,logger:a,variant:null}),h=_t({limit:e.concurrency,maxHeldPerOwner:io(e.concurrency),queue:null});return async s=>{let{request:D,delivery:p,attachmentId:_,internalUserId:y,readAttachment:d,cookie:S,fail:b}=s,g=l.maxBytes,E=i.spend(s);if(E)return E;let U=await n(D),A=await t.getAttachmentForUser(U,_,y);if(!A)return a.warn(`404 attachment=${_} viewer=${y} reason=not_visible`),b(404,"Attachment not found");if(A.fileSize!=null&&A.fileSize>g)return a.warn(`413 attachment=${_} viewer=${y} reason=db_size`),b(413,"Attachment too large");let B=await h.acquire(y,D.signal);if(!B)return D.signal.aborted?(a.info(`503 attachment=${_} viewer=${y} reason=aborted`),b(503,"Attachment request aborted")):(a.warn(`503 attachment=${_} viewer=${y} reason=concurrency`),b(503,"Too many concurrent downloads",ke(503)));let M=!1;try{let O=D.method==="HEAD",P=await d(A.filePath,{maxBytes:g,head:O,principal:r(y),signal:D.signal});if(D.signal.aborted)return a.info(`503 attachment=${_} viewer=${y} reason=aborted`),b(503,"Attachment request aborted");if(!P.ok){if(!Tt(P.reason))return a.error(`500 attachment=${_} viewer=${y} reason=port_contract code=failure_reason`),b(500,Le);let q=Dt(P.reason);return P.reason==="not_found"&&o(_,!1),a.warn(`${q} attachment=${_} viewer=${y} reason=${P.reason} code=${P.code??"-"}`),b(q,At[q],ke(q))}if(P.bytes.byteLength>g)return a.error(`500 attachment=${_} viewer=${y} reason=port_contract code=over_max_bytes`),b(500,Le);let $=Jt(A.fileType)??Jt(P.contentType),I=$!==null&&kr.has($),v=I?$:"application/octet-stream",H=I&&p.kind!=="download"?"inline":"attachment",C=P.size??P.bytes.byteLength,k=new Headers({"Content-Type":v,"Content-Length":String(C),"Content-Disposition":`${H}; filename="${Nr(A.fileName)}"; filename*=UTF-8''${Lr(A.fileName)}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...We});return S&&k.append("Set-Cookie",S),o(_,!0),a.info(`200 attachment=${_} viewer=${y} type=${v} disposition=${H} bytes=${C}`),O?new Response(null,{status:200,headers:k}):(M=!0,new Response(lo(P.bytes,B),{status:200,headers:k}))}finally{M||B()}}};var he=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Ps=he.queueWaitMs+he.readMs+he.renderMs+he.transferMarginMs;import{createHash as uo}from"crypto";var it=e=>{let t=JSON.stringify(e);return`"${uo("sha256").update(t).digest("hex")}"`};import{Buffer as co}from"buffer";var Vr=new Set([194,198,202,206]),mo=new Set([192,193,194,195]),Yr=216,po=217,zr=218,yo=4,ho=64,fo=2,Fr=8,qr=28,Ce=12,Kt=8,Ro=20,jr=Ce+Kt+10,go=2,Ee=(e,t)=>e[t]<<8|e[t+1],Ge=(e,t,r)=>{let n=0;for(let a=r-1;a>=0;a-=1)n=n*256+e[t+a];return n},Te=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},Wr=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Jr=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),Gr=e=>(e.stepsLeft-=1,e.stepsLeft>=0),Kr=e=>e[0]===255&&e[1]===Yr,Xr=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!Gr(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let a=e[n];if(n+=1,a===po)return"eoi";if(a===0||a===Yr)return null;if(a===1||a>=208&&a<=215)continue;if(n+2>e.byteLength)return null;let o=Ee(e,n),l=n+o;return o<2||l>e.byteLength?null:(r.marker=a,r.body=n+2,r.length=o,r.end=l,"segment")}},bo=(e,t,r)=>{let n=e.byteLength,a=t;for(;;){let o=e.indexOf(255,a);if(o<0)return n;for(;;){if(!Gr(r))return null;if(o+1>=n)return n;let l=e[o+1];if(l===255)o+=1;else if(l===0||l>=208&&l<=215){if(o+=2,o>=n||e[o]!==255)break}else return o}a=o}},Qr=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let a=Ee(e,r+1),o=Ee(e,r+3),l=e[r+5];if(o===0||a===0||l===0||n!==8+3*l)return null;let i=[];for(let h=0;h<l;h+=1){let s=e[r+7+3*h],D=s>>4,p=s&15;if(D<1||D>4||p<1||p>4)return null;i.push({id:e[r+6+3*h],horizontal:D,vertical:p})}return{marker:t,width:o,height:a,components:i}},Zr=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>yo||r!==6+2*n?null:Array.from({length:n},(a,o)=>e[t+1+2*o])},en=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:Vr.has(e.marker)||t<e.components.length}),Xt=e=>{if(!Kr(e))return null;let t=Jr(e.byteLength),r=null;for(let n=2;;){if(Xr(e,n,t)!=="segment")return null;if(Wr(t.marker)){if(r!==null||(r=Qr(e,t),r===null))return null}else if(t.marker===zr){if(r===null)return null;let a=Zr(e,t);return a===null?null:en(r,a.length)}n=t.end}},tn=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:a})=>{let o=Math.ceil(e.width*n/(t*Fr)),l=Math.ceil(e.height*a/(r*Fr));return Math.ceil(o/n)*n*Math.ceil(l/a)*a})},rn=e=>e.multiScan?tn(e).reduce((r,n)=>r+n,0)*ho*fo:0,So=896,nn=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!Kr(e))return null;let n=co.from(e.buffer,e.byteOffset,e.byteLength),a=Jr(r),o=null,l=null,i=new Map,h=0,s=0,D=0;for(let p=2;;){let _=Xr(e,p,a);if(_===null)return null;if(_==="eoi")return l===null?null:{header:l,blockVisits:s};if(p=a.end,Wr(a.marker)){if(o!==null||!mo.has(a.marker)||(o=Qr(e,a),o===null))return null;let y=tn(o);i=new Map;for(let[d,S]of o.components.entries()){let b=i.get(S.id);i.set(S.id,b===void 0?y[d]:Math.max(b,y[d]))}h=o.components.length*(Vr.has(o.marker)?So:1)}else if(a.marker===zr){if(o===null||D===h)return null;let y=Zr(e,a);if(y===null)return null;for(let S of y){let b=i.get(S);if(b===void 0)return null;s+=b}if(D+=1,l===null&&(l=en(o,y.length)),s>t||!l.multiScan)return{header:l,blockVisits:s};let d=bo(n,a.end,a);if(d===null)return null;p=d}}},an=e=>{if(e.byteLength<24||Ee(e,8)!==0||Ee(e,10)!==13||!Te(e,12,"IHDR"))return null;let t=Ee(e,16)*65536+Ee(e,18),r=Ee(e,20)*65536+Ee(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Ao=e=>{if(Te(e,Ce,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Ge(e,26,2)&16383,r=Ge(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Te(e,Ce,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Ge(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Te(e,Ce,"VP8X")?e.byteLength<jr?null:{width:Ge(e,24,3)+1,height:Ge(e,27,3)+1}:null},on=e=>{if(an(e)===null||e.byteLength<=qr)return null;switch(e[qr]){case 0:return!1;case 1:return!0;default:return null}},sn=(e,t)=>{if(Te(e,Ce,"VP8 "))return"lossy";if(Te(e,Ce,"VP8L"))return"lossless";if(!Te(e,Ce,"VP8X")||e.byteLength<jr)return null;if((e[Ro]&go)!==0)return"animated";let r=!1,n=t;for(let a=Ce;a+Kt<=e.byteLength;){if(n-=1,n<0)return null;if(Te(e,a,"VP8L"))return"lossless";if(Te(e,a,"VP8 "))return r?"lossy-alpha":"lossy";Te(e,a,"ALPH")&&(r=!0);let o=Ge(e,a+4,4);a+=Kt+o+o%2}return null},ln={png:an,jpeg:Xt,webp:Ao};var Qt=Object.freeze(["image/webp","image/jpeg","image/png"]),Zt=1024*1024;var To=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Do={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},wo=new Set(Qt),_o=e=>typeof e=="string"&&wo.has(e),Eo=256,Et=(e,t)=>e.fileType===null||!To.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Io=[137,80,78,71,13,10,26,10],xo=[255,216,255],Co=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Mo=[82,73,70,70],vo=[87,69,66,80],st=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,a]of t.entries())if(e[r+n]!==a)return!1;return!0},er=e=>{if(st(e,Io,0))return"png";if(st(e,xo,0))return"jpeg";for(let t of Co)if(st(e,t,0))return"gif";return st(e,Mo,0)&&st(e,vo,8)?"webp":null},un=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:it([t])}},cn=(e,t)=>{if(!_o(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Zt)return"too_large";let r=Do[e.contentType];if(er(e.bytes)!==r)return"signature";let n=ln[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},dn=e=>{Re("maxBytes",e.maxBytes,0),Re("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=a=>{let o=t.get(a);o&&(t.delete(a),r-=o.weight)};return{get:a=>{let o=t.get(a);if(o)return t.delete(a),t.set(a,o),o.entry},set:(a,o)=>{n(a);let l=(o.kind==="thumbnail"?o.bytes.byteLength:0)+Eo;if(l>e.maxBytes||e.maxEntries===0)return;let i=o.kind==="thumbnail"?{kind:"thumbnail",bytes:o.bytes.slice(),contentType:o.contentType}:o;t.set(a,{entry:i,weight:l}),r+=l;for(let h of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(h)}}}};var mn=()=>{let e=new Map;return{join:(t,r,n)=>{let a=()=>{let h=new AbortController,s=()=>{e.get(t)?.controller===h&&e.delete(t)},p={promise:n(h.signal).finally(s),controller:h,waiters:0};return e.set(t,p),p},o=e.get(t)??a();o.waiters+=1;let l=()=>{o.waiters-=1,!(o.waiters>0)&&(o.controller.abort(),e.get(t)===o&&e.delete(t))};r.aborted?l():r.addEventListener("abort",l,{once:!0});let i=()=>{r.removeEventListener("abort",l)};return o.promise.finally(i)}}};var tr=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:a,onStuck:o}=e,l=te(),i=new AbortController,h=!1,s,D,p=()=>{o(te()-l)},_=A=>{s=be(()=>{h=!0,A({timedOut:!0}),D=be(p,t),i.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},y=new Promise(_),d=AbortSignal.any([r,i.signal]),S=A=>{A(n(d))},b=new Promise(S),g=A=>(clearTimeout(s),clearTimeout(D),h&&a(te()-l,A.kind==="error"?{error:A.error}:null),A),E=b.then(A=>g({kind:"value",value:A}),A=>g({kind:"error",error:A}));return{outcome:Promise.race([b.then(A=>({timedOut:!1,value:A})),y]),settled:E}};var Oe={404:"Attachment not found",500:Le,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},pn=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=cn(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Po=e=>{let t=new AbortController,r=()=>{t.abort()},n=be(r,he.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},yn=()=>{},ko=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),hn=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:a,recordObjectState:o,logger:l}=e,i=new Map,h=(y,d)=>{let S=d.then(yn,yn);i.set(y,S);let b=()=>{i.get(y)===S&&i.delete(y)};S.then(b)},s=async(y,d)=>{let S=i.get(y.key);if(S===void 0)return t.acquire(y.owner,d);let b=Po(d);try{if(await ko(S,b.signal),b.signal.aborted)return null;let g=r.get(y.key);return g!==void 0?{...g,identity:"verified"}:await t.acquire(y.owner,b.signal)}finally{b.end()}},D=(y,d)=>{if(y.fileSize===null)return d.kind==="exact"?"verified":"unrecorded";if(d.kind==="exact"?d.bytes===y.fileSize:y.fileSize>d.maxBytes)return"verified";let b=d.kind==="exact"?String(d.bytes):`>${d.maxBytes}`;return l.warn(`size_mismatch expected=${y.fileSize} got=${b} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail`),"unverified"},p=(y,d)=>(S,b)=>{let g=b===null?"":` message=${b.error instanceof Error?b.error.message:"unknown"}`;l.warn(`${y}_overrun ms=${S} attachment=${d.attachmentId} viewer=${d.owner} variant=thumbnail${g}`)},_=(y,d)=>S=>{l.warn(`${y}_stuck ms=${S} attachment=${d.attachmentId} viewer=${d.owner} variant=thumbnail`)};return async(y,d)=>{let S=await s(y,d);if(S===null)return{kind:"failure",status:503,reason:d.aborted?"aborted":"queue"};if(typeof S!="function")return S;let b=S,g=null;try{if(d.aborted)return{kind:"failure",status:503,reason:"aborted"};let E=r.get(y.key);if(E!==void 0)return{...E,identity:"verified"};let U=tr({budgetMs:he.readMs,flightSignal:d,call:V=>y.readAttachment(y.filePath,{maxBytes:n,head:!1,principal:a(y.owner),signal:V}),onOverrun:p("read",y),onStuck:_("read",y)}),A=await U.outcome;if(A.timedOut)return g=U.settled,d.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(d.aborted)return{kind:"failure",status:503,reason:"aborted"};let B=A.value;if(!B.ok&&B.reason!=="too_large")return Tt(B.reason)?(B.reason==="not_found"&&o(y.attachmentId,!1),{kind:"failure",status:Dt(B.reason),reason:B.reason,code:B.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(B.ok&&B.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let M=D(y,B.ok?{kind:"exact",bytes:B.bytes.byteLength}:{kind:"over",maxBytes:n}),O=V=>{M==="verified"&&r.set(y.key,V)},P=V=>(O(V),{...V,identity:M});if(!B.ok)return P({kind:"unrenderable",reason:"too_large"});let $=er(B.bytes);if($===null)return P({kind:"unrenderable",reason:"signature"});let I=tr({budgetMs:he.renderMs,flightSignal:d,call:V=>y.renderer.render(B.bytes,{format:$,maxWidth:y.box.maxWidth,maxHeight:y.box.maxHeight,signal:V}),onOverrun:p("render",y),onStuck:_("render",y)}),v=V=>{if(V.kind==="error")return;let ne=pn(V.value,y.box);"entry"in ne&&O(ne.entry)},H=null,C=()=>(H===null&&(H=I.settled.then(v),h(y.key,H)),H);d.addEventListener("abort",C,{once:!0});let k=await I.outcome.finally(()=>d.removeEventListener("abort",C));if(k.timedOut||d.aborted)return g=C(),d.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let q=pn(k.value,y.box);return"entry"in q?P(q.entry):q.failure}finally{g===null?b():g.then(b,b)}}};var gn=10,Lo=1/gn,fn=1-Lo,No=1024,Oo=64,Bo=8,Rn="private, no-cache",Uo="no-store",Ho=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),$o=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},bn=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:a,recordObjectState:o}=e,l=t.attachmentDelivery,i=ot({reason:"rate_limit",limitPerMinute:e.rateLimitPerMinute,logger:a,variant:"thumbnail"}),h=ot({reason:"revalidation_rate_limit",limitPerMinute:e.rateLimitPerMinute*gn,logger:a,variant:"thumbnail"}),s=_t({limit:e.concurrency,maxHeldPerOwner:e.concurrency,queue:{max:Oo,maxPerOwner:Bo,maxWaitMs:he.queueWaitMs}}),D=dn({maxBytes:e.cacheBytes,maxEntries:No}),p=mn(),_=hn({gate:s,cache:D,maxBytes:l.maxBytes,encodeUserId:r,recordObjectState:o,logger:a}),y=(b,g,E,U)=>{let A=`attachment=${b.attachmentId} viewer=${b.internalUserId} variant=thumbnail cache=${U}`;if(g.kind==="failure")return a[$o(g)](`${g.status} ${A} reason=${g.reason} code=${g.code??"-"}`),b.fail(g.status,Oe[g.status],ke(g.status));let B=Ho[g.identity];if(g.kind==="unrenderable")return a.info(`404 ${A} reason=${g.reason}${B}`),b.fail(404,Oe[404]);let M=g.identity==="verified"?{"Cache-Control":Rn,ETag:E}:{"Cache-Control":Uo},O=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...M,"Content-Security-Policy":"default-src 'none'; sandbox",...We});return b.cookie&&O.append("Set-Cookie",b.cookie),a.info(`200 ${A} type=${g.contentType} bytes=${g.bytes.byteLength}${B}`),new Response(g.bytes,{status:200,headers:O})},d=b=>i.spend(b),S=(b,g)=>g?h.spend(b):d(b);return async(b,g)=>{let{request:E,attachmentId:U,internalUserId:A,readAttachment:B,cookie:M,fail:O}=b,P=Yt[g],$=l.thumbnailRenderer;if(!$)return O(404,Oe[404]);let I=E.headers.get("If-None-Match"),v=I!==null,H=S(b,v);if(H)return H;let C=await n(E),k=await t.getAttachmentForUser(C,U,A),V=k!==null&&Et(k,l.maxBytes)?un({rendererId:$.id,box:P,attachmentId:U,filePath:k.filePath,fileType:k.fileType,fileSize:k.fileSize}):null;if(V&&Pr(I,V.etag)){let oe=new Headers({"Cache-Control":Rn,ETag:V.etag,...We});return M&&oe.append("Set-Cookie",M),a.info(`304 attachment=${U} viewer=${A} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:oe})}if(v){let oe=d(b);if(oe)return oe}if(!k)return a.warn(`404 attachment=${U} viewer=${A} variant=thumbnail reason=not_visible`),O(404,Oe[404]);if(!V)return i.refund(A,fn),a.info(`404 attachment=${U} viewer=${A} variant=thumbnail reason=not_eligible`),O(404,Oe[404]);let{key:ne,etag:G}=V,ye=D.get(ne);if(ye)return i.refund(A,fn),y(b,{...ye,identity:"verified"},G,"hit");let ve=oe=>_({key:ne,attachmentId:U,filePath:k.filePath,fileSize:k.fileSize,box:P,owner:A,readAttachment:B,renderer:$},oe),Z;try{Z=await p.join(ne,E.signal,ve)}catch(oe){return a.error(`500 attachment=${U} viewer=${A} variant=thumbnail cache=miss reason=port_exception message=${oe instanceof Error?oe.message:"unknown"}`),O(500,Oe[500])}return y(b,Z,G,"miss")}};var Fo='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',qo=()=>St(403,Wt,{cookie:null}),Sn=Object.freeze({navigable:e=>{let{kind:t}=zt(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>St(404,At[404],{cookie:null}),crossSiteRejection:qo}),An=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:a,logger:o}=e,l=r.attachmentDelivery,i=Ur(e.tuning,l),h={service:r,encodeUserId:n,resolveViewerScope:a,logger:o,recordObjectState:Cr(r,o)},s=$r({...h,rateLimitPerMinute:i.originalRateLimitPerMinute,concurrency:i.originalConcurrency}),D=bn({...h,rateLimitPerMinute:i.thumbnailRateLimitPerMinute,concurrency:i.thumbnailConcurrency,cacheBytes:i.thumbnailCacheBytes});return async({request:p,params:_})=>{let y=null,d=(S,b,g={})=>St(S,b,{cookie:y,extraHeaders:g});try{let{user:S,cookie:b}=await t(p,{failureRedirect:null});if(y=b??null,!S)return d(401,"Unauthorized");let g=zt(new URL(p.url).searchParams);if(g.kind==="invalid")return d(400,"Invalid attachment request");if(g.kind==="thumbnail"&&p.method!=="GET")return d(405,"Method not allowed",{Allow:"GET"});if(p.method!=="GET"&&p.method!=="HEAD")return d(405,"Method not allowed",{Allow:"GET, HEAD"});let{idCodec:E,readAttachment:U}=l;if(!(E&&U))return d(404,"Attachment not found");if(_.token===void 0)throw new Error(Fo);let A=E.decode(_.token);if(A===null||!Number.isSafeInteger(A)||A<=0)return d(400,"Invalid attachment token");let B=await r.getUserIdByExternalId(S.id);if(!B)return d(403,"Forbidden");let M={request:p,delivery:g,attachmentId:A,internalUserId:B,readAttachment:U,cookie:y,fail:d};return g.kind==="thumbnail"?await D(M,g.variant):await s(M)}catch(S){if(S instanceof Response)throw S;return o.error(`500 attachment=? viewer=? reason=unexpected message=${S instanceof Error?S.message:"unknown"}`),d(500,Le)}}};var Vo=me(1,"[Response]"),fe=(e,t,r,n=200,a=Vo)=>{let o=it(r),l=e.headers.get("If-None-Match");a.info(`[jsonResponseWithETag] ETag: ${o}, If-None-Match: ${l}`);let i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'",ETag:o});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&l===o?new Response(null,{status:304,headers:i}):new Response(JSON.stringify(r),{status:n,headers:i})};var xt=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Tn=Object.freeze(["GET","HEAD"]);var Ct=30,En=4e3,Yo="stream interrupted by server error",zo=/^\d{4}-\d{2}-\d{2}$/,jo=15e3,In=Symbol("ids-stream-heartbeat"),Dn=()=>{},Mt=e=>e.return(void 0).then(Dn,Dn),Wo=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(In),jo)}),stop:()=>clearTimeout(e)}},Jo=/^[0-9a-f]{1,16}$/,xn=Object.freeze({...je,frameworkDataRefusal:({params:e})=>e.endpoint===ft?bt():null}),Go=e=>{let t=e.searchParams.get("cursor_report_hub_id"),r=e.searchParams.get("cursor_business_date"),n=e.searchParams.get("cursor_snapshot"),a=n!==null&&Jo.test(n)?n:null;if(t===null)return r===null?{cursor:null,snapshot:a}:{invalid:!0};let o=Number.parseInt(t,10);return!Number.isSafeInteger(o)||String(o)!==t||o<=0?{invalid:!0}:r===null?{cursor:{businessDate:null,reportHubId:o},snapshot:a}:zo.test(r)?{cursor:{businessDate:r,reportHubId:o},snapshot:a}:{invalid:!0}};async function*wn(e,t,r,n){let a=t?Tr(e,t):0,o=!0;for(;;){let l=e.slice(a,a+(o?r:En));a+=l.length;let i=a>=e.length,h=l[l.length-1];if(yield{kind:"chunk",items:l,nextCursor:i||!h?null:{businessDate:h.businessDate,reportHubId:h.reportHubId},isLast:i,...o?{total:e.length}:{},...o?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...o&&n.restarted?{restarted:!0}:{}},o=!1,i)return}}var Cn=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform","X-Content-Type-Options":"nosniff"});return e&&t.append("Set-Cookie",e),t},_n=(e,t,r,n)=>{let a=new TextEncoder,o=!1,l=null,i=new ReadableStream({async pull(h){if(o||r.aborted){await Mt(t);try{h.close()}catch{}return}let s=Wo();try{l===null&&(l=t.next());let D=await Promise.race([l,s.fired]);if(s.stop(),D===In){if(o||r.aborted){await Mt(t);try{h.close()}catch{}return}h.enqueue(a.encode(`
|
|
2
|
-
`));return}l=null;let{value:
|
|
3
|
-
`))}catch(D){if(s.stop(),l=null,
|
|
4
|
-
`)),h.close()}catch{}}},cancel(){o=!0,Mt(t)}});return new Response(i,{status:200,headers:Cn(e)})},Mn=e=>{let{service:t,logger:r}=e;return{methods:Tn,handle:async(n,a,o,l,i)=>{let h=Go(n);if("invalid"in h)return fe(o,a,{error:{message:"Invalid cursor"}},400);let s=xt(o);if(s.aborted)return new Response(null,{status:200,headers:Cn(a)});let D=n.searchParams.get("forceRefresh")==="true",p=!1,_=null,y=null,d=new Promise((g,E)=>{_=g,y=E});d.catch(()=>{});let S=t.getDailyReportIdsByExternalId(i,l.id,{forceRefresh:D,onFetchStart:h.cursor?void 0:()=>{p=!0,t.readSseStreamAnchor().then(g=>t.getDailyReportIdsFirstPageByExternalId(i,l.id,Ct).then(E=>({items:E,streamAnchor:g}))).then(g=>_?.(g),g=>y?.(g))}});if(S.catch(()=>{}),h.cursor){let{items:g,streamAnchor:E}=await S,U=Vt(g),A=h.snapshot!==null&&h.snapshot===U;return _n(a,wn(g,A?h.cursor:null,Ct,{snapshot:U,restarted:!A,streamAnchor:E}),s,r)}let b=(async function*(){let g=await Promise.race([S.then(A=>({kind:"full",source:A}),A=>({kind:"full-error",error:A})),d.then(A=>({kind:"page",page:A}),()=>({kind:"page-error"}))]),E=null,U=!1;if(g.kind==="full")E=g.source;else if(g.kind==="page"){let{items:A,streamAnchor:B}=g.page;if(A.length<Ct){yield{kind:"chunk",items:A,nextCursor:null,isLast:!0,total:A.length,streamAnchor:B};return}yield{kind:"chunk",items:A,nextCursor:null,isLast:!1,provisional:!0},U=!0}else if(g.kind==="full-error"&&p){let A=await d.catch(()=>null);A&&A.items.length>0&&(yield{kind:"chunk",items:A.items,nextCursor:null,isLast:!1,provisional:!0})}E===null&&(E=await S),yield*wn(E.items,null,U?En:Ct,{snapshot:Vt(E.items),streamAnchor:E.streamAnchor})})();return _n(a,b,s,r)}}};import{systemSseRuntime as mi}from"@aiquants/sse";import{createSseResponse as pi,readLastEventId as yi,startSseHeartbeat as hi,terminalStreamResponse as fi}from"@aiquants/sse/server";import{z as R}from"zod";var vn=15e3,Pn="lastEventId",Ko=/^\d{1,15}-\d{1,15}$/,kn=e=>Ko.test(e),Xo=R.object({name:R.string().nullish(),affiliation:R.string().nullish()}),Qo=R.object({name:R.string().nullish(),text:R.string().nullish(),color:R.string().nullish()}),Zo=R.object({id:R.number(),name:R.string().nullish(),color:R.string().nullish()}),Ln=R.object({id:R.number(),userId:R.string().nullish(),userName:R.string().nullish(),content:R.string().nullish(),createdAt:R.string().nullish(),isMine:R.boolean()}),ei=R.object({id:R.string(),fileName:R.string(),fileType:R.string().nullable(),fileSize:R.number().nullable(),createdAt:R.string().nullable(),state:R.enum(["present","absent","unknown"]),hasThumbnail:R.boolean().default(!1)}),rr=R.object({reportHubId:R.number(),date:R.string().nullish(),createdAt:R.string().nullish(),author:R.string().nullish(),userId:R.string().nullish(),sourceType:R.string().nullish(),employeeName:R.string().nullish(),updatedBy:R.string().nullish(),updatedAt:R.string().nullish(),category:R.string().nullish(),creationCategory:R.string().nullish(),visitTimeFrom:R.string().nullish(),visitTimeTo:R.string().nullish(),customerName:R.string().nullish(),interviewers:R.array(Xo),subject:R.string().nullish(),content:R.string().nullish(),externalComments:R.array(Qo),isRead:R.boolean(),isStarred:R.boolean(),labels:R.array(Zo),postedComments:R.array(Ln),attachments:R.array(ei).default([])}),ti=R.object({type:R.literal("connected")}),vt=R.object({type:R.literal("status-update"),reportHubId:R.number(),statusType:R.enum(["star","read"]),value:R.boolean(),clientTempId:R.string(),recipientRawUserId:R.number().optional()}),nr=R.string().optional(),ar=R.object({type:R.literal("comment-add"),reportHubId:R.number(),comment:Ln,clientTempId:R.string(),recipientRawUserId:R.number().optional(),sourceType:nr}),or=R.object({type:R.literal("comment-delete"),reportHubId:R.number(),commentId:R.number(),clientTempId:R.string(),recipientRawUserId:R.number().optional(),sourceType:nr}),ir=R.object({type:R.literal("report-create"),reportHubId:R.number(),report:rr,clientTempId:R.string(),recipientRawUserId:R.number().optional()}),sr=R.object({type:R.literal("report-update"),reportHubId:R.number(),report:rr,clientTempId:R.string(),recipientRawUserId:R.number().optional()}),lr=R.object({type:R.literal("report-publish"),reportHubId:R.number(),report:rr,clientTempId:R.string(),recipientRawUserId:R.number().optional()}),ur=R.object({type:R.literal("report-delete"),reportHubId:R.number(),clientTempId:R.string(),sourceType:nr}),Nn=R.discriminatedUnion("type",[ti,vt,ar,or,ir,sr,lr,ur]);import{systemSseRuntime as ni}from"@aiquants/sse";import{createSharedSource as ai}from"@aiquants/sse/shared-source";var Be="daily-report:ids:",Ue="daily-report:business-date:",Pt=(e,t)=>`${e}st:${t}`,cr=e=>`${Be}user:${e}:`,On=(e,t)=>Pt(cr(e),t),ri=e=>`${Ue}${e}:`,Bn=(e,t)=>Pt(ri(e),t),lt=e=>`daily-report:date:${e}:user:`,Ke=(e,t)=>`${lt(e)}${t}:`,Un=(e,t,r)=>Pt(Ke(e,t),r),De=e=>`daily-report:detail:${e}:user:`,kt=(e,t)=>`${De(e)}${t}:`,Hn=(e,t,r)=>Pt(kt(e,t),r);var He=(e,t)=>{let[r,n]=e.split("-").map(Number),[a,o]=t.split("-").map(Number);return r!==a?r<a:n<=o},oi=5e3,ii=100,ut=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=t.logger??me(1,"[SSE Reader]"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return ai({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:ni,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",l=>{this._logger.error("Redis client error:",l)});let a=!1,o=this._readLoop(n,t,r,()=>a);return async()=>{if(a=!0,n.isOpen)try{await n.quit()}catch{}await o}}async _readLoop(t,r,n,a){let o=n;try{for(;!a()&&t.isOpen;){let l=await t.xRead([{key:this.config.streamKey,id:o}],{BLOCK:oi,COUNT:ii});if(l)for(let i of l)for(let h of i.messages)o=h.id,this._invalidateCaches(h.message),r.next({id:h.id,message:h.message})}}catch(l){a()||(this._logger.error("xRead loop error:",l),r.fail(l instanceof Error?l:new Error(String(l))));return}a()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){try{let r=t?.data?JSON.parse(t.data):null,n=r?.type;if((n==="report-create"||n==="report-delete"||n==="report-publish")&&this.config.cache.invalidatePrefix(Be),n==="comment-add"||n==="comment-delete"||n==="status-update"){let a=r?.reportHubId;typeof a=="number"&&this.config.cache.invalidatePrefix(De(a))}}catch{}}};import{inArray as si,sql as $n}from"drizzle-orm";var li="",ui=64,ci=e=>e.toLowerCase(),di=e=>e.trim().toLowerCase();function Fn(e){if(e==null)return null;if(!Array.isArray(e))return new Set;let t=new Set;for(let r of e){if(typeof r!="string")continue;let n=di(r);n.length>0&&t.add(n)}return t}function we(e,t){return e===null?!0:t==null?!1:e.has(ci(t))}function $e(e){return e!==null&&e.size===0}function Vn(e,t){if(t!==null)return t.size===0?$n`1 = 0`:si($n`LOWER(${e})`,[...t])}var Xe,Qe,ct=class ct{constructor(t,r){$t(this,Xe);$t(this,Qe);Ft(this,Xe,t),Ft(this,Qe,r)}get visible(){return nt(this,Xe)===null?null:new Set(nt(this,Xe))}get commentable(){return nt(this,Qe)===null?null:new Set(nt(this,Qe))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Fn(r?t.read:t),a=r?t.comment:void 0;if(a===void 0)return new ct(n,n);let o=Fn(a),l=new Set;for(let i of o??[])n.has(i)&&l.add(i);return new ct(n,l)}static unrestricted(t){return new ct(null,null)}};Xe=new WeakMap,Qe=new WeakMap;var ge=ct;function dt(e){let t=qn(e.visible),r=qn(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function qn(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(li);if(t.length<=ui)return`s:${t}`;let r=2166136261;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return`sh:${(r>>>0).toString(16)}`}var jn=Object.freeze({...je,frameworkDataRefusal:bt}),Yn=864e5,Ri={baseMs:2e3,jitterMs:8e3},Wn=6e4,dr=1e3,Jn=JSON.stringify({type:"connected"}),zn="0-0",gi=(e,t,r,n)=>{if(r===null&&n===null)return!0;let a=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return we(r,e.report.sourceType);case"comment-add":case"comment-delete":return we(n,a??"Internal");case"report-delete":return we(r,a)}},bi=["externalComments","postedComments"],Si=(e,t,r)=>{if(r===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"||we(r,e.report.sourceType))return!1;let n=t.report;for(let a of bi)n[a]=[];return!0},Ai=(e,t)=>{e.writeEvent({event:null,id:t,data:Jn})},Ti=(e,t,r,n,a)=>{if(r.data)try{let o=JSON.parse(r.data),l=Nn.safeParse(o);if(!l.success){a.error("SSE message validation failed:",l.error.format());return}let i=l.data,h=typeof o.recipientRawUserId=="number"?o.recipientRawUserId:void 0;if((i.type==="status-update"||h!==void 0)&&h!==n.internalUserId||!gi(i,o,n.visibleSet,n.commentableSet)){Ai(e,t);return}let D=Si(i,o,n.commentableSet),p;if("recipientRawUserId"in o){let{recipientRawUserId:_,...y}=o;p=JSON.stringify(y)}else D?p=JSON.stringify(o):p=r.data;e.writeEvent({event:null,id:t,data:p})}catch(o){a.error(`[SSE:${n.internalUserId}] processEntry error:`,o)}},Gn=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:a,sseReader:o,streamKey:l,logger:i}=e,h=async(s,D)=>{let{request:p,internalUserId:_,cursor:y}=D,d=D.initialScope.visible,S=D.initialScope.commentable,b=0,g=setInterval(()=>{let v=++b;n(p,"refresh").then(H=>{v===b&&(d=H.visible,S=H.commentable)})},Wn);s.onClose(()=>clearInterval(g));let E=y===null?zn:y,U=y!==null&&a!==void 0,A=[],B=null,M=v=>{He(v.id,E)||(E=v.id,Ti(s,v.id,v.message,{internalUserId:_,visibleSet:d,commentableSet:S},i))},O=async(v,H)=>{let[C]=await v.xRange(l,"-","+",{COUNT:1});return C!==void 0&&!He(C.id,H)},P=async(v,H)=>{if(await O(v,H))return!1;let C=H;for(;;){let k=await v.xRange(l,C,"+",{COUNT:dr}),q=k[0];if(q!==void 0&&q.id!==C&&await O(v,C))return!1;for(let ne of k){if(B!==null&&He(B,ne.id))return!0;M(ne)}let V=k.at(-1);if(k.length<dr||V===void 0||s.isClosed())return!0;C=V.id}},$=o.subscribe(v=>{if(!U){M(v);return}He(v.id,E)||(B===null&&(B=v.id),A.push(v))},v=>{i.error(`[SSE:${_}] Fan-Out reader error:`,v),s.close()});if(s.onClose($),y===null){await o.ready();try{let v=await a?.getClient();if(v){let H=await v.xRevRange(l,"+","-",{COUNT:1});H.length>0&&!He(H[0].id,E)&&(E=H[0].id)}}catch{}}if(s.writeEvent({event:null,id:E===zn?null:E,data:Jn}),hi(s,{intervalMs:vn,retry:Ri,runtime:mi}),y===null||a===void 0)return;await o.ready();let I=await a.getClient();if(I===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await P(I,y)){s.writeRetry(Yn),s.writeEvent({event:"resync-required",id:null,data:""}),s.close();return}U=!1;for(let v of A.splice(0))M(v)};return async({request:s,params:D})=>{let p,_=()=>{let d=new Headers;return p!==void 0&&d.append("Set-Cookie",p),d},y=d=>fi(d,{data:"",retryMs:Yn,headers:_()});try{let d=await t(s,{failureRedirect:null});p=d.cookie;let{user:S}=d;if(!S)return y("auth-required");let b=await r.getUserIdByExternalId(S.id);if(!b)return y("forbidden");if(D.endpoint!=="updates")return new Response("Not Found",{status:404,headers:_()});let g=yi(s,Pn);if(g!==null&&!kn(g))return i.warn(`[SSE:${b}] malformed resume cursor; asking the client to resync`),y("resync-required");let E=await n(s,"initial");return pi({requestSignal:xt(s),headers:_(),onError:(U,A)=>i.error(`[SSE:${b}] ${A} failed:`,U),produce:U=>h(U,{request:s,internalUserId:b,cursor:g,initialScope:E})})}catch(d){if(d instanceof Response)throw d;let S=d instanceof Error?d:new Error(String(d));return i.error(`500 sse name=${S.name} message=${S.message}`),new Response("Internal Server Error",{status:500,headers:_()})}}};var Di=(e,t)=>{let r=new Headers({"Content-Type":"application/json"});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Kn=Object.freeze(["GET"]),wi=e=>{let[t,r,n]=e.split("-").map(Number),a=new Date(0);return a.setUTCFullYear(t,r-1,n),a.getUTCFullYear()===t&&a.getUTCMonth()===r-1&&a.getUTCDate()===n};function mr(e){let{authenticate:t,service:r,encodeUserId:n,redis:a,sseReader:o,streamKey:l}=e,i=e.loginRedirectPath??"/auth/login",h=e.logger??me(3,"[DailyReportAPI]"),s=e.logger??me(3,"[DailyReportVisibility]"),D=e.logger??me(1,"[DailyReportSSE]"),p=e.logger??me(1,"[DailyReportAttachment]"),_=e.logger??me(2,"[DailyReportIsolation]"),y=async(M,O="initial")=>{let P=e.resolveVisibleSourceTypes;if(!P)return ge.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let $=await P(M,{reason:O});return $==null?ge.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):ge.restrictTo($)}catch($){return s.error("resolveVisibleSourceTypes threw; failing closed (deny all)",$),ge.restrictTo([])}},d=async({request:M})=>{let{user:O,cookie:P}=await t(M,{failureRedirect:i}),$=new Headers;P&&$.append("Set-Cookie",P);let I=await r.getUserIdByExternalId(O.id),v=I?n(I):null;return{data:{user:O,userId:v},headers:$}},S={"business-date":{methods:Kn,handle:async(M,O,P,$,I)=>{let v=ue(M.searchParams.get("businessDate")),H=M.searchParams.get("forceRefresh")==="true";if(v===null||!wi(v))return fe(P,O,{error:{message:"Invalid business date"}},400);let C=await r.getDailyReportsByBusinessDateByExternalId(I,v,$.id,{forceRefresh:H});return fe(P,O,{businessDate:v,reports:C},200)}},[ft]:Mn({service:r,logger:h}),report:{methods:Kn,handle:async(M,O,P,$,I)=>{let v=M.searchParams.get("reportHubId"),H=M.searchParams.get("forceRefresh")==="true",C=v?Number.parseInt(v,10):NaN;if(!Number.isFinite(C)||C<=0)return fe(P,O,{error:{message:"Invalid reportHubId"}},400);let k=await r.getDailyReportDetailByIdByExternalId(I,C,$.id,{snapshot:!0,forceRefresh:H});return k?fe(P,O,{report:k},200):fe(P,O,{error:{message:"Report not found"}},404)}}},b=async({request:M,params:O})=>{let{user:P,cookie:$}=await t(M,{failureRedirect:null}),I=$??null;if(!P)return fe(M,I,{error:{message:"Unauthorized"}},401);let v=O.endpoint,H=v!==void 0&&Object.hasOwn(S,v)?S[v]:void 0;if(H===void 0)return fe(M,I,{error:{message:"Unknown endpoint"}},404);if(!H.methods.includes(M.method)){let k=fe(M,I,{error:{message:"Method not allowed"}},405);return k.headers.set("Allow",H.methods.join(", ")),k}let C=te();try{let k=new URL(M.url),q=await y(M);return await H.handle(k,I,M,P,q)}catch(k){let q=te()-C,V=k instanceof Error?k:new Error(String(k));return h.error(`500 endpoint=${v} elapsed=${q}ms name=${V.name} code=${"code"in V?V.code:"N/A"} message=${V.message}`),h.error("Stack:",V.stack),fe(M,I,{error:{message:"Internal Server Error"}},500)}},g=async({request:M,params:O})=>{let{user:P,cookie:$}=await t(M,{failureRedirect:null}),I=(H,C)=>Di(H,{...C,setCookie:$});if(!P)return I({error:"Unauthorized"},{status:401});let v=te();try{if(O.endpoint!=="action")return I({error:"Unknown endpoint"},{status:404});let C=await r.getUserIdByExternalId(P.id);if(!C)return I({error:"User not found"},{status:404});let k=await y(M),q=await M.formData(),V=q.get("intent"),ne=q.get("reportHubId"),G=ne?Number(ne):NaN,ye=q.get("businessDate"),ve=Number(q.get("operationTimestamp")),Z=q.get("clientTempId");if(V==="clearCache")return e.enableDevCacheClear?(await r.clearCache(),I({status:"OK",intent:"clearCache"})):I({error:"Invalid intent"},{status:400});if(!Z)return I({error:"clientTempId required"},{status:400});if(V!=="create"&&(!G||Number.isNaN(G)))return I({error:"Invalid reportHubId"},{status:400});let oe=async(Y,K,de)=>{let mt=q.get(K);if(mt===null)return I({error:`${K} required`},{status:400});try{let Ie=await de(mt==="true");return I({status:"OK",intent:Y,updatedStatus:{isStarred:Ie.isStarred,isRead:Ie.isRead},operationTimestamp:ve,reportHubId:String(G),clientTempId:Z})}catch(Ie){if(Ie instanceof Error&&Ie.message==="Not Found")return I({error:"Report not found"},{status:404});throw Ie}};switch(V){case"create":{if(!ye)return I({error:"businessDate required"},{status:400});let Y=await r.createDailyReport(C,ye,Z);return I({status:"OK",intent:"create",report:Y,reportHubId:String(Y.reportHubId),clientTempId:Z})}case"update":{let Y=q.get("title"),K=q.get("content");try{return await r.updateDailyReport(G,C,{title:Y,content:K},Z),I({status:"OK",intent:"update",reportHubId:String(G),clientTempId:Z})}catch(de){if(de instanceof Error){if(de.message==="Unauthorized")return I({error:"Unauthorized"},{status:403});if(de.message==="Not Found")return I({error:"Report not found"},{status:404})}throw de}}case"publish":try{let Y=await r.publishDailyReport(G,C,Z);return I({status:"OK",intent:"publish",reportHubId:String(G),clientTempId:Z,report:Y})}catch(Y){if(Y instanceof Error){if(Y.message==="Unauthorized")return I({error:"Unauthorized"},{status:403});if(Y.message==="Not Found")return I({error:"Report not found"},{status:404})}throw Y}case"delete":try{return await r.deleteDailyReport(G,C,Z),I({status:"OK",intent:"delete",reportHubId:String(G),clientTempId:Z})}catch(Y){if(Y instanceof Error){if(Y.message==="Unauthorized")return I({error:"Unauthorized"},{status:403});if(Y.message==="Not Found")return I({error:"Report not found"},{status:404})}throw Y}case"toggleStar":return await oe("toggleStar","isStarred",Y=>r.setStarStatus(k,C,G,ye,Y,Z));case"toggleRead":return await oe("toggleRead","isRead",Y=>r.setReadStatus(k,C,G,ye,Y,Z));case"addComment":{let Y=q.get("content");if(!Y)return I({error:"Content required"},{status:400});try{let K=await r.addComment(k,C,G,Y,ye,Z),de={...K,userId:K.userId};return I({status:"OK",intent:"addComment",newComment:de,reportHubId:String(G),clientTempId:Z})}catch(K){if(K instanceof Error){if(K.message==="Not Found")return I({error:"Report not found"},{status:404});if(K.message.startsWith("Comments are restricted"))return I({error:"Comments are restricted for this report"},{status:403})}throw K}}case"deleteComment":{let Y=Number(q.get("commentId"));if(!Y||Number.isNaN(Y))return I({error:"Invalid commentId"},{status:400});try{return await r.deleteComment(k,C,G,Y,ye,Z),I({status:"OK",reportHubId:String(G),deletedCommentId:String(Y),clientTempId:Z})}catch(K){if(K instanceof Error){if(K.message==="Unauthorized")return I({error:"Unauthorized"},{status:403});if(K.message==="Not Found")return I({error:"Comment not found"},{status:404})}throw K}}default:return I({error:"Invalid intent"},{status:400})}}catch(H){if(H instanceof Response)throw H;let C=te()-v,k=H instanceof Error?H:new Error(String(H));return h.error(`500 action elapsed=${C}ms name=${k.name} message=${k.message}`),h.error("Stack:",k.stack),I({error:"Internal Server Error"},{status:500})}},E=Gn({authenticate:t,service:r,resolveViewerScope:y,redis:a,sseReader:o,streamKey:l,logger:D}),U=An({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:y,logger:p,tuning:e}),A=xr(_),B=(M,O,P)=>async $=>{let I=Er($.request)?O.frameworkDataRefusal($):null;if(I!==null)throw I;return Ir($.request,O)?(A(M,$.request),O.crossSiteRejection()):P($)};return{index:{loader:d},api:{loader:B("api",xn,b),action:B("action",je,g)},sse:{loader:B("sse",jn,E)},attachment:{loader:B("attachment",Sn,U)}}}import{runWithTransactionRetry as _i}from"@aiquants/mssql";import{aliasedTable as Ze,and as Q,asc as Lt,desc as et,eq as x,getColumns as Ei,inArray as Se,isNull as pe,or as tt,sql as Xn}from"drizzle-orm";var Fe=e=>Ei(e),Ii=e=>{if(e!==void 0){if(typeof e!="object"||e===null)throw Je("attachmentThumbnailRenderer","an object with id and render",e);if(e.render===void 0)throw wt("attachmentThumbnailRenderer.render","a function");if(typeof e.render!="function")throw Je("attachmentThumbnailRenderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Je("attachmentThumbnailRenderer.id","a non-blank string naming the rendering pipeline version",e.id);return e}},ce=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),a=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),o=String(r.getMonth()+1).padStart(2,"0"),l=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${a}-${o}-${l}`;let i=String(r.getHours()).padStart(2,"0"),h=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${a}-${o}-${l} ${i}:${h}:${s}`};function pr(e){let{db:t,tables:r,userTable:n,resolveUserId:a,encodeUserId:o,redis:l,cache:i,epochs:h}=e,{hub:s,internal:D,comment:p,label:_,hubLabel:y,userStatus:d}=r,S=e.externalSources??[],b=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],g=b[0]??"\u4E0B\u66F8\u304D",E=e.logger??me(1,"[DailyReportService]");Gt({attachmentIdCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,attachmentThumbnailRenderer:e.attachmentThumbnailRenderer,attachmentMaxBytes:e.attachmentMaxBytes});let U=Object.freeze({idCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,thumbnailRenderer:Ii(e.attachmentThumbnailRenderer),maxBytes:Ne("attachmentMaxBytes",e.attachmentMaxBytes,1,Br)}),A=u=>_i(c=>t.transaction(m=>c(()=>u(m))),e.transactionRetry),B=e.idsTtlMs??18e4,M="daily-report:ids:epoch",O=e.businessDateTtlMs??3e5,P="daily-report:date-epoch:",$="daily-report:detail-epoch:",v=`${e.streamKey??"daily-report:sse-stream"}:v2`,H=e.streamMaxLen??1e4,C=u=>h.incrementEpoch(u),k=u=>Vn(s.sourceType,u),q=async(u,c)=>{let m=await l?.getClient();if(!m){E.warn(`[SSE] Redis client unavailable (${c})`);return}let f=te();try{await m.xAdd(v,"*",{data:JSON.stringify(u)},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:H}});let T=te()-f;T>1e3&&E.warn(`[SSE] Slow publish (${c}): ${T}ms`)}catch(T){E.error(`[SSE] Redis publish failed (${c}):`,T)}},V=async()=>{try{let u=await l?.getClient();if(u===void 0)return null;let[c]=await u.xRevRange(v,"+","-",{COUNT:1});return c===void 0?null:c.id}catch(u){return E.error("[DailyReportService] SSE stream anchor read failed",u),null}},ne=u=>u==null||u===""?null:/^\d+$/.test(u)?o(Number(u)):u,G=()=>{let u={};for(let c of S)u[`ext_${c.sourceType}`]=Fe(c.table);return u},ye=u=>{let c=u;for(let m of S)c=c.leftJoin(m.table,Q(x(s.sourceType,m.sourceType),x(s.sourceIdNum,m.idColumn)));return c},ve=(u,c,m)=>{let{hub:f,internal:T}=c,N=f.summary,w=[],L=null,F=null,W=null,z=null,X=null,ie=null,Ye=[],xe=S.find(j=>j.sourceType===f.sourceType),ze=xe?c[`ext_${xe.sourceType}`]:void 0;if(xe&&ze){let j=xe.mapRow(ze);j.content!==void 0&&(N=j.content),j.employeeName!==void 0&&(ie=j.employeeName),j.category!==void 0&&(L=j.category),j.creationCategory!==void 0&&(F=j.creationCategory),j.visitTimeFrom!==void 0&&(W=j.visitTimeFrom),j.visitTimeTo!==void 0&&(z=j.visitTimeTo),j.customerName!==void 0&&(X=j.customerName),j.interviewers!==void 0&&(w=j.interviewers),j.externalComments!==void 0&&(Ye=j.externalComments)}else f.sourceType==="Internal"&&T&&(N=T.body);let _e=(c.labels??[]).map(j=>({id:j.id,name:j.name,color:j.color})),se=c.postedCommentRows??[],ee=we(u.commentable,f.sourceType),le=F?b.includes(F):!1,Ht=Ve?.[0]??null;return le&&Ht&&!_e.some(j=>j.id===Ht)&&_e.push({id:Ht,name:g,color:null}),{reportHubId:f.id,date:ce(f.businessDate,"YYYY-MM-DD"),author:c.creatorName??ne(f.createdBy)??"",userId:f.userId?o(f.userId):"",sourceType:f.sourceType??"Internal",createdAt:ce(f.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:ce(f.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:ne(f.updatedBy),employeeName:ie??c.creatorName??ne(f.createdBy),category:L,creationCategory:F,visitTimeFrom:W,visitTimeTo:z,customerName:X,interviewers:w,subject:f.title,content:N,externalComments:ee?Ye:[],isRead:c.isRead??!1,isStarred:c.isStarred??!1,labels:_e,postedComments:se.filter(j=>ee||m!==void 0&&j.userId===m).map(j=>({...j,userId:o(j.userId),isMine:m?j.userId===m:!1})),attachments:c.attachments}},Z=async(u,c)=>{let m=Ze(y,"draft_label"),f=await Pe();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).leftJoin(m,Q(x(m.hubId,s.id),Se(m.labelId,f))).where(Q(pe(s.deletedAt),tt(x(s.userId,c),pe(s.userId),pe(m.hubId)),k(u.visible))).orderBy(et(s.businessDate),et(s.id))).map(N=>({...N,businessDate:ce(N.businessDate,"YYYY-MM-DD")}))},oe=async(u,c,m)=>{let f=await de(c);if(!f)return[];if($e(u.visible))return[];let T=Ze(y,"draft_label"),N=await Pe();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(m).from(s).leftJoin(T,Q(x(T.hubId,s.id),Se(T.labelId,N))).where(Q(pe(s.deletedAt),tt(x(s.userId,f),pe(s.userId),pe(T.hubId)),k(u.visible))).orderBy(et(s.businessDate),et(s.id))).map(L=>({...L,businessDate:ce(L.businessDate,"YYYY-MM-DD")}))},Y=async(u,c)=>{let m=await ye(t.select({hub:Fe(s),internal:Fe(D),creatorName:n.displayName,...G()}).from(s)).leftJoin(D,x(s.id,D.hubId)).leftJoin(n,x(s.userId,n.id)).where(Q(x(s.businessDate,Xn`${c}`),pe(s.deletedAt),k(u.visible))).orderBy(et(s.id)),f=await yt(m.map(T=>T.hub.id));return m.map(T=>ve(u,{...T,attachments:f.get(T.hub.id)??[]}))},K=new Map,de=async u=>{if(!e.disableUserIdCache&&K.has(u))return K.get(u)??null;let c=await a(u);return c!==null&&!e.disableUserIdCache&&K.set(u,c),c},mt=async(u,c,{forceRefresh:m=!1,snapshot:f=!1,ttlMsOverride:T,onFetchStart:N}={})=>{let w=await de(c);if(!w)return{items:[],streamAnchor:null};if($e(u.visible))return{items:[],streamAnchor:await V()};let L=On(w,dt(u)),[F]=await i.getOrFetch({cacheKey:L,fetcher:async()=>{let W=await V(),z=await Z(u,w);return Ar(z)?[{items:z,streamAnchor:W}]:(E.warn("[DailyReportService] ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)"),[{items:[...z].sort(Rt),streamAnchor:W}])},onFetchStart:N,forceRefresh:m,snapshot:f,ttlMsOverride:T??B,epochKey:M,refreshAheadRatio:.5});if(F===void 0)throw new Error("[DailyReportService] ids cache returned no record");return F},Ie=(u,c,{forceRefresh:m=!1,snapshot:f=!1,ttlMsOverride:T}={})=>{let N=ue(c);return N?$e(u.visible)?Promise.resolve([]):i.getOrFetch({cacheKey:Bn(N,dt(u)),fetcher:()=>Y(u,N),forceRefresh:m,snapshot:f,ttlMsOverride:T??O}):Promise.resolve([])},Ve=null,pt=async()=>(Ve!==null||(Ve=(await t.select({id:_.id}).from(_).where(Se(_.name,b)).orderBy(_.id)).map(c=>c.id)),Ve),Pe=async()=>{let u=await pt();return u.length>0?u:[-1]},Ot=async()=>{let u=await pt();if(u.length===0)return null;let[c]=await t.select({id:_.id}).top(1).from(_).where(x(_.name,g));return c?.id??u[0]},ha=(u,c)=>c!=null?"absent":u!=null?"present":"unknown",yt=async u=>{let c=new Map,m=r.attachment,f=U.idCodec;if(u.length===0||!m||!f)return c;let T=U.thumbnailRenderer!==void 0&&U.readAttachment!==void 0,N=await t.select({id:m.id,hubId:m.hubId,fileName:m.fileName,fileType:m.fileType,fileSize:m.fileSize,createdAt:m.createdAt,objectCheckedAt:m.objectCheckedAt,objectMissingAt:m.objectMissingAt}).from(m).where(Se(m.hubId,u)).orderBy(Lt(m.createdAt),Lt(m.id));for(let w of N){let L=w.fileType?String(w.fileType):null,F=w.fileSize!=null?Number(w.fileSize):null,W=ha(w.objectCheckedAt,w.objectMissingAt),z={id:f.encode(Number(w.id)),fileName:String(w.fileName),fileType:L,fileSize:F,createdAt:ce(w.createdAt,"YYYY-MM-DD HH:mm:ss"),state:W,hasThumbnail:T&&W!=="absent"&&Et({fileType:L,fileSize:F},U.maxBytes)},X=c.get(Number(w.hubId));X?X.push(z):c.set(Number(w.hubId),[z])}return c},fa=async(u,c,m)=>{let f=r.attachment;if(!f||$e(u.visible))return null;let T=await Pe(),N=Ze(y,"draft_label");return(await t.select({fileName:f.fileName,filePath:f.filePath,fileType:f.fileType,fileSize:f.fileSize}).top(1).from(f).innerJoin(s,x(s.id,f.hubId)).leftJoin(N,Q(x(N.hubId,s.id),Se(N.labelId,T))).where(Q(x(f.id,c),pe(s.deletedAt),tt(x(s.userId,m),pe(N.hubId)),k(u.visible))))[0]??null},Ra=async u=>{let c=r.attachment;if(!c)return;let m=new Date;try{await t.update(c).set({objectCheckedAt:m,objectMissingAt:m,updatedAt:m}).where(x(c.id,u))}catch(f){E.error("markAttachmentMissing failed",f)}},ga=async u=>{let c=r.attachment;if(!c)return;let m=new Date;try{await t.update(c).set({objectCheckedAt:m,objectMissingAt:null,updatedAt:m}).where(x(c.id,u))}catch(f){E.error("markAttachmentPresent failed",f)}},ba=async(u,c,m,{forceRefresh:f=!1,snapshot:T=!1,ttlMsOverride:N}={})=>{let w=await de(m);if(!w)return[];let L=ue(c);if(!L)return[];if($e(u.visible))return[];let F=Un(L,w,dt(u));return i.getOrFetch({cacheKey:F,fetcher:async()=>{let W=await Pe(),z=Ze(y,"draft_label"),X=await ye(t.select({hub:Fe(s),internal:Fe(D),isRead:d.isRead,isStarred:d.isStarred,creatorName:n.displayName,...G()}).from(s)).leftJoin(D,x(s.id,D.hubId)).leftJoin(d,Q(x(s.id,d.hubId),x(d.userId,w))).leftJoin(z,Q(x(z.hubId,s.id),Se(z.labelId,W))).leftJoin(n,x(s.userId,n.id)).where(Q(x(s.businessDate,Xn`${L}`),pe(s.deletedAt),tt(x(s.userId,w),pe(z.hubId)),k(u.visible))).orderBy(et(s.id));if(X.length===0)return[];let ie=X.map(ee=>ee.hub.id),Ye=await t.select({hubId:y.hubId,id:_.id,name:_.name,color:_.color}).from(y).innerJoin(_,x(y.labelId,_.id)).where(Se(y.hubId,ie)),xe=await t.select({hubId:p.hubId,id:p.id,body:p.body,createdAt:p.createdAt,userId:p.userId,userName:n.displayName}).from(p).leftJoin(n,x(p.userId,n.id)).where(Se(p.hubId,ie)).orderBy(Lt(p.createdAt)),ze=await yt(ie),_e=new Map,se=new Map;for(let ee of Ye){let le=_e.get(ee.hubId);le||(le=[],_e.set(ee.hubId,le)),le.push({id:ee.id,name:ee.name,color:ee.color})}for(let ee of xe){let le=se.get(ee.hubId);le||(le=[],se.set(ee.hubId,le)),le.push({id:ee.id,content:ee.body,createdAt:ce(ee.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ee.userId,userName:ee.userName||""})}return X.map(ee=>{let le=ee.hub.id;return ve(u,{...ee,attachments:ze.get(le)??[],labels:_e.get(le)||[],postedCommentRows:se.get(le)||[]},w)})},forceRefresh:f,snapshot:T,ttlMsOverride:N??O,epochKey:`${P}${L}`})},rt=async(u,c,m,{forceRefresh:f=!1,snapshot:T=!1,ttlMsOverride:N}={})=>{if($e(u.visible))return null;let w=Hn(c,m,dt(u));return(await i.getOrFetch({cacheKey:w,fetcher:async()=>{let F=await Pe(),W=Ze(y,"draft_label"),z=await ye(t.select({hub:Fe(s),internal:Fe(D),isRead:d.isRead,isStarred:d.isStarred,creatorName:n.displayName,...G()}).from(s)).leftJoin(D,x(s.id,D.hubId)).leftJoin(d,Q(x(s.id,d.hubId),x(d.userId,m))).leftJoin(W,Q(x(W.hubId,s.id),Se(W.labelId,F))).leftJoin(n,x(s.userId,n.id)).where(Q(x(s.id,c),pe(s.deletedAt),tt(x(s.userId,m),pe(W.hubId)),k(u.visible)));if(z.length===0)return[];let X=z[0].hub.id,ie=await t.select({id:_.id,name:_.name,color:_.color}).from(y).innerJoin(_,x(y.labelId,_.id)).where(x(y.hubId,X)),Ye=await t.select({id:p.id,body:p.body,createdAt:p.createdAt,userId:p.userId,userName:n.displayName}).from(p).leftJoin(n,x(p.userId,n.id)).where(x(p.hubId,X)).orderBy(Lt(p.createdAt)),xe=await yt([X]),ze=ie.map(se=>({id:se.id,name:se.name,color:se.color})),_e=Ye.map(se=>({id:se.id,content:se.body,createdAt:ce(se.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:se.userId,userName:se.userName||""}));return[ve(u,{...z[0],attachments:xe.get(X)??[],labels:ze,postedCommentRows:_e},m)]},forceRefresh:f,snapshot:T,ttlMsOverride:N??O,epochKey:`${$}${c}`}))[0]??null},Sa=async(u,c,m,f={})=>{let T=await de(m);return T?rt(u,c,T,f):null},Aa=async(u,c)=>{let m=await Pe(),f=Ze(y,"draft_label"),[T]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).leftJoin(f,Q(x(f.hubId,s.id),Se(f.labelId,m))).where(Q(x(s.id,u),tt(x(s.userId,c),pe(f.hubId))));return T??null},Bt=async(u,c,m)=>{let f=await Aa(c,m);if(!f||f.deletedAt||!we(u.visible,f.sourceType))throw new Error("Not Found")},Ta=async(u,c,m,f,T,N)=>{await Bt(u,m,c);let w=await t.select().top(1).from(d).where(Q(x(d.hubId,m),x(d.userId,c))),L;if(w.length>0?w[0].isStarred!==T?L=(await t.update(d).set({isStarred:T,updatedAt:new Date,updatedBy:String(c)}).output().where(Q(x(d.hubId,m),x(d.userId,c))))[0]:L=w[0]:L=(await t.insert(d).output().values({hubId:m,userId:c,isStarred:T,isRead:!1,createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)}))[0],f){let F=ue(f);F&&(i.invalidatePrefix(Ke(F,c)),await C(`${P}${F}`))}return i.invalidatePrefix(kt(m,c)),await C(`${$}${m}`),await q(vt.parse({type:"status-update",reportHubId:m,recipientRawUserId:c,statusType:"star",value:T,clientTempId:N}),"setStarStatus"),L},Da=async(u,c,m,f,T,N)=>{await Bt(u,m,c);let w=await t.select().top(1).from(d).where(Q(x(d.hubId,m),x(d.userId,c))),L;if(w.length>0?w[0].isRead!==T?L=(await t.update(d).set({isRead:T,updatedAt:new Date,updatedBy:String(c)}).output().where(Q(x(d.hubId,m),x(d.userId,c))))[0]:L=w[0]:L=(await t.insert(d).output().values({hubId:m,userId:c,isRead:T,isStarred:!1,createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)}))[0],f){let F=ue(f);F&&(i.invalidatePrefix(Ke(F,c)),await C(`${P}${F}`))}return i.invalidatePrefix(kt(m,c)),await C(`${$}${m}`),await q(vt.parse({type:"status-update",reportHubId:m,recipientRawUserId:c,statusType:"read",value:T,clientTempId:N}),"setReadStatus"),L},yr=async(u,c)=>{if(c===null)return;let m=await Pe(),[f]=await t.select({hubId:y.hubId}).top(1).from(y).where(Q(x(y.hubId,u),Se(y.labelId,m)));return f?c:void 0},wa=async(u,c,m,f,T,N)=>{let[w]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where(x(s.id,m));if(!w||w.deletedAt)throw new Error("Not Found");if(await Bt(u,m,c),!we(u.commentable,w.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(w.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let L=await yr(m,w.userId),[F]=await t.insert(p).output().values({hubId:m,userId:c,body:f,createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)}),[W]=await t.select({displayName:n.displayName}).top(1).from(n).where(x(n.id,c)),z=W?.displayName??"";if(T){let ie=ue(T);ie&&(i.invalidatePrefix(lt(ie)),await C(`${P}${ie}`))}i.invalidatePrefix(De(m)),await C(`${$}${m}`);let X={id:F.id,userId:o(F.userId),userName:z,content:F.body,createdAt:ce(F.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await q(ar.parse({type:"comment-add",reportHubId:m,comment:X,clientTempId:N,recipientRawUserId:L,sourceType:w.sourceType}),"addComment"),X},_a=async(u,c)=>await u.select().top(1).from(p).where(x(p.id,c)),Ea=async(u,c,m,f,T,N)=>{let w=await _a(t,f);if(w.length===0)throw new Error("Not Found");if(w[0].hubId!==m)throw new Error("Not Found");let[L]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where(x(s.id,w[0].hubId));if(!(L&&we(u.visible,L.sourceType)))throw new Error("Not Found");if(w[0].userId!==c)throw new Error("Unauthorized");let F=await yr(m,L.userId);if(await t.delete(p).where(x(p.id,f)),T){let W=ue(T);W&&(i.invalidatePrefix(lt(W)),await C(`${P}${W}`))}i.invalidatePrefix(De(m)),await C(`${$}${m}`),await q(or.parse({type:"comment-delete",reportHubId:m,commentId:f,clientTempId:N,recipientRawUserId:F,sourceType:L?.sourceType}),"deleteComment")},Ia=async(u,c,m)=>{E.info("createDailyReport called",{userId:u,businessDate:c});let[f]=await t.select({displayName:n.displayName}).from(n).where(x(n.id,u)),T=f?.displayName??o(u);try{let N=await A(async F=>{E.info("Starting transaction");let W=`internal-temp-${Date.now()}-${Math.random()}`,[z]=await F.insert(s).output().values({sourceType:"Internal",sourceId:W,businessDate:new Date(c),userId:u,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)});await F.update(s).set({sourceId:String(z.id)}).where(x(s.id,z.id)),E.info("Hub created",z),await F.insert(D).values({hubId:z.id,body:"",createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}),E.info("Internal created"),E.info("Calling getDraftLabelId");let X=await Ot();E.info("draftLabelId",X);let ie=[];return X&&(await F.insert(y).values({hubId:z.id,labelId:X,createdAt:new Date,createdBy:String(u)}),ie.push({id:X,name:g,color:null})),E.info("Label assigned"),{reportHubId:z.id,date:c,createdAt:ce(z.createdAt,"YYYY-MM-DD HH:mm:ss"),author:T,userId:o(u),sourceType:"Internal",employeeName:T,updatedBy:o(u),updatedAt:ce(z.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:z.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:ie,postedComments:[],attachments:[]}}),w=ue(c);w&&i.invalidatePrefix(Ke(w,u)),i.invalidatePrefix(Ue),i.invalidatePrefix(cr(u)),await C(M),w&&await C(`${P}${w}`);let L=await rt(ge.unrestricted("post-write self read: the writer always sees the row they just wrote"),N.reportHubId,u,{forceRefresh:!0});if(L){let F=await pt(),W=L.labels.some(z=>F.includes(z.id));await q(ir.parse({type:"report-create",reportHubId:L.reportHubId,report:L,clientTempId:m,recipientRawUserId:W?u:void 0}),"createDailyReport")}return L??N}catch(N){throw E.error("Error in createDailyReport",N),N}},ht=async(u,c)=>await u.select().top(1).from(s).where(x(s.id,c)),Ut=async(u,c,m)=>{await u.update(s).set(m).where(x(s.id,c))},hr=async(u,c,m)=>{await u.update(D).set(m).where(x(D.hubId,c))},fr=async(u,c,m)=>{await u.delete(y).where(Q(x(y.hubId,c),x(y.labelId,m)))};return{streamKey:v,streamMaxLen:H,attachmentDelivery:U,clearCache:async()=>{i.clearAll(),K.clear(),Ve=null,h&&await C(M),E.info("[DailyReportService] Server-side DB/SQL caches cleared successfully.")},invalidateHubReadCaches:async(u,c)=>{i.invalidatePrefix(Ue),i.invalidatePrefix(Be),await C(M);for(let m of new Set(u))i.invalidatePrefix(De(m)),await C(`${$}${m}`);for(let m of new Set(c)){let f=ue(m);f&&await C(`${P}${f}`)}},getUserIdByExternalId:de,getDailyReportIdsByExternalId:mt,getDailyReportIdsFirstPageByExternalId:oe,readSseStreamAnchor:V,getDailyReportsByBusinessDate:Ie,getDailyReportsByBusinessDateByExternalId:ba,getDailyReportDetailById:rt,getDailyReportDetailByIdByExternalId:Sa,getDraftLabelId:Ot,getAttachmentsByHubIds:yt,getAttachmentForUser:fa,markAttachmentMissing:Ra,markAttachmentPresent:ga,setStarStatus:Ta,setReadStatus:Da,addComment:wa,deleteComment:Ea,createDailyReport:Ia,updateDailyReport:async(u,c,m,f)=>{let T=await ht(t,u);if(!T.length||T[0].deletedAt)throw new Error("Not Found");if(T[0].userId!==c)throw new Error("Unauthorized");await A(async L=>{m.title!==void 0&&await Ut(L,u,{title:m.title,updatedAt:new Date,updatedBy:String(c)}),m.content!==void 0&&await hr(L,u,{body:m.content,updatedAt:new Date,updatedBy:String(c)})}),i.invalidatePrefix(De(u)),i.invalidatePrefix(Ue),await C(`${$}${u}`);let N=ue(ce(T[0].businessDate,"YYYY-MM-DD"));N&&(i.invalidatePrefix(lt(N)),await C(`${P}${N}`));let w=await rt(ge.unrestricted("post-write self read: the writer always sees the row they just wrote"),u,c,{forceRefresh:!0});if(w){let L=await pt(),F=w.labels.some(W=>L.includes(W.id));await q(sr.parse({type:"report-update",reportHubId:w.reportHubId,report:w,clientTempId:f,recipientRawUserId:F?c:void 0}),"updateDailyReport")}},publishDailyReport:async(u,c,m)=>{let f=await ht(t,u);if(!f.length)throw new Error("Not Found");if(f[0].userId!==c)throw new Error("Unauthorized");let T=await Ot();if(!T)return null;if(await fr(t,u,T),i.invalidatePrefix(De(u)),i.invalidatePrefix(Ue),i.invalidatePrefix(Be),await C(M),f[0].businessDate){let L=ue(ce(f[0].businessDate,"YYYY-MM-DD"));L&&await C(`${P}${L}`)}let N=ue(ce(f[0].businessDate,"YYYY-MM-DD"));N&&i.invalidatePrefix(Ke(N,c));let w=await rt(ge.unrestricted("post-write self read: the writer always sees the row they just wrote"),u,c,{forceRefresh:!0});return w&&await q(lr.parse({type:"report-publish",reportHubId:w.reportHubId,report:w,clientTempId:m}),"publishDailyReport"),w??null},deleteDailyReport:async(u,c,m)=>{let f=await ht(t,u);if(!f.length||f[0].deletedAt)throw new Error("Not Found");if(f[0].userId!==c)throw new Error("Unauthorized");if(await Ut(t,u,{deletedAt:new Date,deletedBy:String(c),updatedAt:new Date,updatedBy:String(c)}),i.invalidatePrefix(De(u)),i.invalidatePrefix(Ue),i.invalidatePrefix(Be),await C(M),f[0].businessDate){let T=ue(ce(f[0].businessDate,"YYYY-MM-DD"));T&&await C(`${P}${T}`)}await q(ur.parse({type:"report-delete",reportHubId:u,clientTempId:m,sourceType:f[0].sourceType}),"deleteDailyReport")},findDailyReportHubById:ht,updateDailyReportHub:Ut,updateDailyReportInternal:hr,deleteDailyReportLabel:fr}}var xi=me(1,"[DailyReportExternalSource]"),Ci=(e,t,r,n=xi)=>{if(!e)return[];try{let a=JSON.parse(e);return Array.isArray(a)?a.map(r).filter(o=>o!==null):(n.warn(`Unexpected ${t} format: not an array`),[])}catch(a){return n.warn(`Failed to parse ${t}:`,a),[]}};import{desc as Qn,sql as Mi}from"drizzle-orm";import{bigint as re,bit as Zn,date as vi,datetime2 as ae,foreignKey as Ae,index as Me,int as Pi,mssqlSchema as ki,nvarchar as J,primaryKey as qe,uniqueIndex as Li}from"drizzle-orm/mssql-core";function Ni(e,t){let r=ki(e),n=t.userTable,a=r.table("DailyReportHub",{id:re("id",{mode:"number"}).identity().notNull(),sourceType:J("source_type",{length:20}).notNull(),sourceId:J("source_id",{length:100}).notNull(),sourceIdNum:re("source_id_num",{mode:"number"}).generatedAlwaysAs(Mi`TRY_CAST(source_id AS BIGINT)`),businessDate:vi("business_date"),userId:re("user_id",{mode:"number"}),title:J("title",{length:200}),summary:J("summary",{length:"max"}),createdAt:ae("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull(),updatedAt:ae("updated_at").notNull(),updatedBy:J("updated_by",{length:50}).notNull(),deletedAt:ae("deleted_at"),deletedBy:J("deleted_by",{length:50})},p=>[qe({name:`${e}_DailyReportHub_pk`,columns:[p.id]}),Ae({name:`${e}_DailyReportHub_user_id_fk`,columns:[p.userId],foreignColumns:[n.id]}),Me(`${e}_DailyReportHub_business_date_index`).on(p.businessDate),Me(`${e}_DailyReportHub_updated_at_index`).on(p.updatedAt),Me(`${e}_DailyReportHub_source_index`).on(p.sourceType,p.sourceId),Me(`${e}_DailyReportHub_user_id_index`).on(p.userId),Me(`${e}_DailyReportHub_business_date_id_index`).on(Qn(p.businessDate),Qn(p.id)),Me(`${e}_DailyReportHub_deleted_at_index`).on(p.deletedAt)]),o=r.table("DailyReportInternal",{hubId:re("hub_id",{mode:"number"}).notNull(),body:J("body",{length:"max"}),metadata:J("metadata",{length:"max"}),createdAt:ae("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull(),updatedAt:ae("updated_at").notNull(),updatedBy:J("updated_by",{length:50}).notNull()},p=>[qe({name:`${e}_DailyReportInternal_pk`,columns:[p.hubId]}),Ae({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[p.hubId],foreignColumns:[a.id]})]),l=r.table("DailyReportComment",{id:re("id",{mode:"number"}).identity().notNull(),hubId:re("hub_id",{mode:"number"}).notNull(),userId:re("user_id",{mode:"number"}).notNull(),body:J("body",{length:"max"}).notNull(),createdAt:ae("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull(),updatedAt:ae("updated_at").notNull(),updatedBy:J("updated_by",{length:50}).notNull()},p=>[qe({name:`${e}_DailyReportComment_pk`,columns:[p.id]}),Ae({name:`${e}_DailyReportComment_hub_id_fk`,columns:[p.hubId],foreignColumns:[a.id]}),Ae({name:`${e}_DailyReportComment_user_id_fk`,columns:[p.userId],foreignColumns:[n.id]}),Me(`${e}_DailyReportComment_hub_id_index`).on(p.hubId)]),i=r.table("DailyReportLabel",{id:re("id",{mode:"number"}).identity().notNull(),userId:re("user_id",{mode:"number"}),name:J("name",{length:50}).notNull(),color:J("color",{length:20}),sortOrder:Pi("sort_order"),createdAt:ae("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull(),updatedAt:ae("updated_at").notNull(),updatedBy:J("updated_by",{length:50}).notNull()},p=>[qe({name:`${e}_DailyReportLabel_pk`,columns:[p.id]}),Ae({name:`${e}_DailyReportLabel_user_id_fk`,columns:[p.userId],foreignColumns:[n.id]})]),h=r.table("DailyReportHub_Label",{hubId:re("hub_id",{mode:"number"}).notNull(),labelId:re("label_id",{mode:"number"}).notNull(),createdAt:ae("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull()},p=>[qe({name:`${e}_DailyReportHub_Label_pk`,columns:[p.hubId,p.labelId]}),Ae({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[p.hubId],foreignColumns:[a.id]}),Ae({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[p.labelId],foreignColumns:[i.id]})]),s=r.table("DailyReportUserStatus",{hubId:re("hub_id",{mode:"number"}).notNull(),userId:re("user_id",{mode:"number"}).notNull(),isRead:Zn("is_read").default(!1).notNull(),isStarred:Zn("is_starred").default(!1).notNull(),createdAt:ae("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull(),updatedAt:ae("updated_at").notNull(),updatedBy:J("updated_by",{length:50}).notNull()},p=>[qe({name:`${e}_DailyReportUserStatus_pk`,columns:[p.hubId,p.userId]}),Ae({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[p.hubId],foreignColumns:[a.id]}),Ae({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[p.userId],foreignColumns:[n.id]})]),D=r.table("DailyReportAttachment",{id:re("id",{mode:"number"}).identity().notNull(),hubId:re("hub_id",{mode:"number"}).notNull(),uploadedBy:re("uploaded_by",{mode:"number"}),sourceKey:J("source_key",{length:200}).notNull(),fileName:J("file_name",{length:255}).notNull(),filePath:J("file_path",{length:"max"}).notNull(),fileType:J("file_type",{length:100}),fileSize:re("file_size",{mode:"number"}),objectCheckedAt:ae("object_checked_at"),objectMissingAt:ae("object_missing_at"),createdAt:ae("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull(),updatedAt:ae("updated_at").notNull(),updatedBy:J("updated_by",{length:50}).notNull()},p=>[qe({name:`${e}_DailyReportAttachment_pk`,columns:[p.id]}),Ae({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[p.hubId],foreignColumns:[a.id]}),Ae({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[p.uploadedBy],foreignColumns:[n.id]}),Li(`${e}_DailyReportAttachment_source_unique`).on(p.hubId,p.sourceKey),Me(`${e}_DailyReportAttachment_hub_id_index`).on(p.hubId,p.createdAt)]);return{hub:a,internal:o,comment:l,attachment:D,label:i,hubLabel:h,userStatus:s}}var Oi=5e7,ca=2e8,Bi=1,da=Object.freeze({fixedBytes:4*1024*1024,pipelineRows:2048,wholeImageBuffer:Object.freeze({"jpeg-single-scan":Object.freeze({kind:"none"}),"jpeg-multi-scan":Object.freeze({kind:"jpeg-coefficients"}),png:Object.freeze({kind:"none"}),"png-interlaced":Object.freeze({kind:"decoded-raster"}),gif:Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-lossy":Object.freeze({kind:"none"}),"webp-lossy-alpha":Object.freeze({kind:"canvas",bytesPerPixel:5}),"webp-lossless":Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-animated":Object.freeze({kind:"canvas",bytesPerPixel:9})})}),ea=125,ta=4,ra=16,na=50,aa=2,Nt=Object.freeze({renderMs:he.renderMs,nanosecondsPerBlockVisit:ea,margin:ta,maxBlockVisits:Math.floor(he.renderMs*1e6/(ea*ta)),walkBudgetMs:ra,nanosecondsPerWalkStep:na,walkMargin:aa,maxWalkSteps:Math.floor(ra*1e6/(na*aa))}),Ui=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),oa=75,ia=4,sa="#ffffff",Hi=1,$i={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Fi=[/out of memory/i,/insufficient memory/i,/memory allocation|allocation failed/i,/(?:cannot|could not|unable to|failed to) allocate/i,/picture memory error/i,/unable to create thread|error creating thread|resource temporarily unavailable/i,/too many open files|no space left on device/i,/\b(?:ENOMEM|EAGAIN|EMFILE|ENFILE|ENOSPC)\b/],la=Object.freeze({ok:!1,reason:"failed"}),ua=Object.freeze({ok:!1,reason:"unsupported"}),ma=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:rn(e)}),pa=(e,t)=>{switch(t){case"jpeg":{let r=Xt(e);return r===null?null:ma(r)}case"png":{let r=on(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=sn(e,Nt.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},ya=(e,t)=>{let r=Ui.get(t.depth);if(r===void 0)return null;let n=t.channels*r,a=da,o=a.wholeImageBuffer[e.layout];return(o.kind==="none"?0:o.kind==="decoded-raster"?t.width*t.height*n:o.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*o.bytesPerPixel)+a.pipelineRows*t.width*n+a.fixedBytes},qi=(e,t,r)=>{let n=pa(e,t);return n===null?null:ya(n,r)},Vi=e=>e!==null&&e<=ca,Yi=(e,t)=>{if(t!=="jpeg")return pa(e,t);let r=nn(e,Nt);return r===null||r.blockVisits>Nt.maxBlockVisits?null:ma(r.header)},zi=e=>{let t=e instanceof Error?e.message:"";return Fi.some(r=>r.test(t))?"failed":"unsupported"},ji=e=>{e.cache(!1),e.concurrency(Bi),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values($i)});let t=async(n,a,o,l,i)=>{let h=Yi(n,a);if(h===null)return ua;try{let s=e(n,{limitInputPixels:Oi,animated:!1});if(!Vi(ya(h,await s.metadata())))return ua;if(i.aborted)return la;let D=await s.rotate().resize({width:o,height:l,fit:"inside",withoutEnlargement:!0}).flatten({background:sa}).webp({quality:oa,effort:ia}).toBuffer();return{ok:!0,bytes:new Uint8Array(D),contentType:"image/webp"}}catch(s){return{ok:!1,reason:zi(s)}}},r=async(n,{format:a,maxWidth:o,maxHeight:l,signal:i})=>i.aborted?la:t(n,a,o,l,i);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${oa}-e${ia}/flatten-${sa}/v${Hi}`,render:r}};function Iu(e){e.redis||(e.logger??console).warn("[DailyReport] redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=qt(e.redis),r=new at({defaultTtlMs:e.cacheDefaultTtlMs??6e4},t),n=pr({...e,cache:r,epochs:t}),a=new ut({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),o=mr({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes,redis:e.redis,sseReader:a,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:a,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(l=>l.sourceType)])],...o}}export{Zt as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,Qt as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,ca as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,Nt as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,da as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,dr as DAILY_REPORT_SSE_CATCH_UP_BATCH,Wn as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,ut as DailyReportSseReader,ge as DailyReportViewerScope,at as SqlResultCache,mr as createDailyReportHandlers,Iu as createDailyReportServer,pr as createDailyReportService,qt as createEpochStore,ji as createSharpThumbnailRenderer,Ni as defineDailyReportSchema,it as generateETag,He as isStreamIdLte,fe as jsonResponseWithETag,qi as predictSharpThumbnailWorkingSetBytes,Ci as transformJsonArray};
|
|
1
|
+
var Dr=e=>{throw TypeError(e)};var _r=(e,t,r)=>t.has(e)||Dr("Cannot "+r);var ot=(e,t,r)=>(_r(e,t,"read from private field"),r?r.call(e):t.get(e)),Vt=(e,t,r)=>t.has(e)?Dr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),zt=(e,t,r,n)=>(_r(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Q=()=>Math.floor(performance.now());var jt=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),at=class{constructor(t,r){this.config=t;this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.config.defaultTtlMs;if(a-(o.expireAt-Q())<a*r||this.inFlight.has(n))return;let i;i=(async()=>{let h=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===i&&this.buckets.set(n,{records:s,expireAt:Q()+a,epoch:h}),s})(),this.inFlight.set(n,i),i.catch(()=>{}).finally(()=>{this.inFlight.get(n)===i&&this.inFlight.delete(n)})};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o}=t,a=this.buckets.get(r);if(n&&(this.buckets.delete(r),this.inFlight.delete(r)),!n&&a&&a.expireAt>Q())if(t.epochKey){let i=await this.epochStore.getEpoch(t.epochKey);if(i===null||a.epoch===i)return this.maybeRefreshAhead(t),o?a.records.map(h=>structuredClone(h)):a.records;this.buckets.delete(r)}else return this.maybeRefreshAhead(t),o?a.records.map(i=>structuredClone(i)):a.records;if(!n&&this.inFlight.has(r)){let i=await this.inFlight.get(r);return o?i.map(h=>structuredClone(h)):i}let l;l=(async()=>{let i=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null;t.onFetchStart?.();let h=await t.fetcher();if(n||this.inFlight.get(r)===l){let s=Q()+(t.ttlMsOverride??this.config.defaultTtlMs);this.buckets.set(r,{records:h,expireAt:s,epoch:i}),this.buckets.size>500&&this.cleanExpired()}return h})(),n||this.inFlight.set(r,l);try{let i=await l;return o?i.map(h=>structuredClone(h)):i}finally{this.inFlight.get(r)===l&&this.inFlight.delete(r)}};this.clearAll=()=>{this.buckets.clear(),this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)}}cleanExpired(){let t=Q();for(let[r,n]of this.buckets.entries())n.expireAt<=t&&this.buckets.delete(r)}};var Lo=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Er=e=>e<10?`0${e}`:`${e}`,No=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Er(e.getMonth()+1),n=Er(e.getDate());return`${t}-${r}-${n}`},it=e=>{let t=Lo.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),l=Number(n),i=Number(o);if(a<1)return null;let h=new Date(0);return h.setUTCFullYear(a,l-1,i),h.getUTCFullYear()!==a||h.getUTCMonth()!==l-1||h.getUTCDate()!==i?null:`${r}-${n}-${o}`},gt=e=>it(e)===e;var pe=e=>e==null?null:e instanceof Date?No(e):it(e);var bt="ids-stream";var Wt=e=>{let t=2166136261,r=-624069552;for(let n of e){let o=n.reportHubId;t^=o&255,t=Math.imul(t,16777619),t^=o>>>8&255,t=Math.imul(t,16777619),t^=o>>>16&255,t=Math.imul(t,16777619),t^=o>>>24&255,t=Math.imul(t,16777619),r^=o>>>24&255,r=Math.imul(r,16777619),r^=o>>>16&255,r=Math.imul(r,16777619),r^=o>>>8&255,r=Math.imul(r,16777619),r^=o&255,r=Math.imul(r,16777619);let a=n.businessDate;if(a===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let l=0;l<a.length;l++){let i=a.charCodeAt(l);t^=i&255,t=Math.imul(t,16777619),r^=i&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},St=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,wr=e=>{for(let t=1;t<e.length;t++)if(St(e[t-1],e[t])>0)return!1;return!0};var Ir=(e,t)=>{let r=e.findIndex(n=>St({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var se=(e,t,r=console)=>{let n=o=>typeof o=="string"?[`${t} ${o}`]:[t,o];return{debug:(o,...a)=>{e<=0&&r.debug(...n(o),...a)},info:(o,...a)=>{e<=1&&r.info(...n(o),...a)},warn:(o,...a)=>{e<=2&&r.warn(...n(o),...a)},error:(o,...a)=>{e<=3&&r.error(...n(o),...a)}}};var At=Object.freeze({"business-date":"json",[bt]:"stream",report:"json"}),xr=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Jt=e=>e!==void 0&&Object.hasOwn(At,e);var Kt=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Cr=e=>Object.hasOwn(Kt,e);var Oo="download",Bo="thumbnail",Uo="1";var Gt=e=>{let t=e.getAll(Bo),r=e.getAll(Oo);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Cr(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Uo?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var fe=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Tt=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=l=>{let i={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(s=>[s,0]))};o.set(l,i),fe(()=>{o.delete(l),i.count>0&&n(l,i)},t)};return{record:(l,i,h)=>{let s=o.get(l);if(s!==void 0){s.count+=1,s.tallies[i]+=1;return}h(),a(l)}}};var Qt="Cross-site request rejected",Ho="Not Found",$o=new Set(["same-origin","none"]),Fo=new Set(["GET","HEAD","OPTIONS"]),vr=["api","action","sse","attachment"],Pr=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}}),qo=()=>Pr(403,Qt),Dt=()=>Pr(404,Ho),st=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:qo}),Mr=e=>new URL(e.url).pathname.endsWith(".data"),Yo=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},kr=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Fo.has(e.method)||Yo(e)):$o.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},Vo=6e4,zo="refusals",jo=32,Wo=/^[a-z-]+$/,Xt=e=>{if(e===null)return"-";let t=e.slice(0,jo);return Wo.test(t)&&t===e?e:JSON.stringify(t)},Lr=e=>{let t=Tt({windowMs:Vo,tallies:vr,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${vr.map(l=>`${l}:${a[l]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${Xt(a.get("Sec-Fetch-Site"))} mode=${Xt(a.get("Sec-Fetch-Mode"))} dest=${Xt(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(zo,r,o)}};var Jo=/^[1-9][0-9]*$/,Ko=/^(?:0|[1-9][0-9]*)$/,Zt=e=>Number.isSafeInteger(e)&&e>0,Je=e=>{if(e===null||!Jo.test(e))return null;let t=Number(e);return Zt(t)?t:null},Nr=e=>{if(e===null||!Ko.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Le=(e,t)=>{let r=e.get(t);return r===null||typeof r=="string"?r:""};var Or=(e,t)=>(r,n)=>{let o=n?"markAttachmentPresent":"markAttachmentMissing";e[o](r).catch(a=>{t.error(`${o} failed attachment=${r} message=${a instanceof Error?a.message:"unknown"}`)})};var Go=6e4/1e3,Xo=5e3/1e3,Qo=new Map([[429,Go],[503,Xo]]),Ne=e=>{let t=Qo.get(e);return t===void 0?{}:{"Retry-After":String(t)}},Ur="Too many requests",Zo="same-origin",ea="SAMEORIGIN",Ke=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Zo,"X-Frame-Options":ea}),_t=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Ke});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Hr=(e,t)=>{if(e===null)return!1;for(let r of e.split(",")){let n=r.trim();if((n.startsWith("W/")?n.slice(2):n)===t)return!0}return!1},$r=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),ta=/^[\x20-\x7E]+$/,ra=/^[\w.+-]+\/[\w.+-]+/,er=e=>e&&ta.test(e)&&ra.test(e)?e:null,Fr=e=>encodeURIComponent(e).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),qr=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),Et={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},Yr={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},wt=e=>typeof e=="string"&&Object.hasOwn(Yr,e),It=e=>Yr[e],Ce="Attachment request failed";var na=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,Oe=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${na(r)}`),xt=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`);var Vr=32*1024*1024,oa=60,aa=4,ia=120,sa=2,la=8*1024*1024,ye=(e,t,r)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r)return t;throw Oe(e,`an integer >= ${r}`,t)},Be=(e,t,r,n)=>t===void 0?n:ye(e,t,r),ua=[["attachmentThumbnailRenderer",["readAttachment","attachmentIdCodec"]],["readAttachment",["attachmentIdCodec"]],["attachmentIdCodec",["readAttachment"]],["attachmentMaxBytes",["readAttachment"]],["attachmentRateLimitPerMinute",["readAttachment"]],["attachmentConcurrency",["readAttachment"]],["attachmentThumbnailRateLimitPerMinute",["attachmentThumbnailRenderer"]],["attachmentThumbnailConcurrency",["attachmentThumbnailRenderer"]],["attachmentThumbnailCacheBytes",["attachmentThumbnailRenderer"]]],tr=e=>{for(let[t,r]of ua){if(e[t]===void 0)continue;let n=r.find(o=>e[o]===void 0);if(n!==void 0)throw xt(n,`injected when ${t} is given`)}},zr=(e,t)=>(tr({attachmentIdCodec:t.idCodec,readAttachment:t.readAttachment,attachmentThumbnailRenderer:t.thumbnailRenderer,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes}),Object.freeze({originalRateLimitPerMinute:Be("attachmentRateLimitPerMinute",e.attachmentRateLimitPerMinute,1,oa),originalConcurrency:Be("attachmentConcurrency",e.attachmentConcurrency,1,aa),thumbnailRateLimitPerMinute:Be("attachmentThumbnailRateLimitPerMinute",e.attachmentThumbnailRateLimitPerMinute,1,ia),thumbnailConcurrency:Be("attachmentThumbnailConcurrency",e.attachmentThumbnailConcurrency,1,sa),thumbnailCacheBytes:Be("attachmentThumbnailCacheBytes",e.attachmentThumbnailCacheBytes,0,la)}));var Ct=e=>{let t=ye("limit",e.limit,1),r=ye("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ye("queue.max",e.queue.max,0),maxPerOwner:ye("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ye("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],l=new Map,i=new Map,h=(d,S)=>d.get(S)??0,s=(d,S,b)=>{let g=h(d,S)+b;g<=0?d.delete(S):d.set(S,g)},D=d=>h(i,d)<r,y=d=>(o+=1,s(i,d,1),p(d)),E=()=>{for(;o<t;){let d=a.findIndex(b=>D(b.owner));if(d<0)return;let[S]=a.splice(d,1);s(l,S.owner,-1),S.grant(y(S.owner))}},p=d=>{let S=!1;return()=>{S||(S=!0,o-=1,s(i,d,-1),E())}};return{acquire:(d,S)=>{if(S.aborted)return Promise.resolve(null);if(o<t&&D(d))return Promise.resolve(y(d));if(n===null||a.length>=n.max||h(l,d)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:b}=n,g=w=>{let H=()=>{let C=a.indexOf(x);C<0||(a.splice(C,1),s(l,d,-1),U(),w(null))},A=fe(H,b),U=()=>{clearTimeout(A),S.removeEventListener("abort",H)},x={owner:d,grant:C=>{U(),w(C)}};a.push(x),s(l,d,1),S.addEventListener("abort",H,{once:!0})};return new Promise(g)}}};var ca=1024,da=6e4,ma=e=>{ye("limitPerMinute",e,1);let t=new Map,r=(o,a)=>{a<=o.lastRefillMs||(o.tokens=Math.min(e,o.tokens+(a-o.lastRefillMs)*e/6e4),o.lastRefillMs=a)},n=(o,a)=>{let l=t.get(o);l&&t.delete(o);let i=l??{tokens:e,lastRefillMs:a};r(i,a),t.set(o,i);for(let h of t.keys()){if(t.size<=ca)break;t.delete(h)}return i};return{consume:(o,a)=>{let l=n(o,a);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(o,a,l)=>{let i=t.get(o);i&&(r(i,a),i.tokens=Math.min(e,i.tokens+l))}}},lt=e=>{let{reason:t,logger:r}=e,n=ma(e.limitPerMinute),o=e.variant===null?"":` variant=${e.variant}`,a=Tt({windowMs:da,tallies:[t],writeSuppressed:(l,{count:i,since:h})=>{r.warn(`${t}_suppressed count=${i} since=${h} viewer=${l}${o}`)}});return{spend:({attachmentId:l,internalUserId:i,fail:h})=>n.consume(i,Q())?null:(a.record(i,t,()=>r.warn(`429 attachment=${l} viewer=${i}${o} reason=${t}`)),h(429,Ur,Ne(429))),refund:(l,i)=>{n.refund(l,Q(),i)}}};var pa=256*1024,jr=6e4,ya=e=>Math.ceil(e/2),ha=new Uint8Array(new ArrayBuffer(0)),fa=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=ha,t()},l=i=>{clearTimeout(o),o=fe(()=>{i.error(new Error(`attachment body idle for ${jr} ms`)),a()},jr)};return new ReadableStream({start(i){l(i)},pull(i){let h=Math.min(n+pa,r.byteLength);if(h>n&&i.enqueue(r.slice(n,h)),n=h,n>=r.byteLength){i.close(),a();return}l(i)},cancel(){a()}},{highWaterMark:0})},Wr=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,l=t.attachmentDelivery,i=lt({reason:"rate_limit",limitPerMinute:e.rateLimitPerMinute,logger:o,variant:null}),h=Ct({limit:e.concurrency,maxHeldPerOwner:ya(e.concurrency),queue:null});return async s=>{let{request:D,delivery:y,attachmentId:E,internalUserId:p,readAttachment:d,cookie:S,fail:b}=s,g=l.maxBytes,w=i.spend(s);if(w)return w;let H=await n(D),A=await t.getAttachmentForUser(H,E,p);if(!A)return o.warn(`404 attachment=${E} viewer=${p} reason=not_visible`),b(404,"Attachment not found");if(A.fileSize!=null&&A.fileSize>g)return o.warn(`413 attachment=${E} viewer=${p} reason=db_size`),b(413,"Attachment too large");let U=await h.acquire(p,D.signal);if(!U)return D.signal.aborted?(o.info(`503 attachment=${E} viewer=${p} reason=aborted`),b(503,"Attachment request aborted")):(o.warn(`503 attachment=${E} viewer=${p} reason=concurrency`),b(503,"Too many concurrent downloads",Ne(503)));let x=!1;try{let C=await d(A.filePath,{maxBytes:g,head:D.method==="HEAD",principal:r(p),signal:D.signal});if(D.signal.aborted)return o.info(`503 attachment=${E} viewer=${p} reason=aborted`),b(503,"Attachment request aborted");if(!C.ok){if(!wt(C.reason))return o.error(`500 attachment=${E} viewer=${p} reason=port_contract code=failure_reason`),b(500,Ce);let Y=It(C.reason);return C.reason==="not_found"&&a(E,!1),o.warn(`${Y} attachment=${E} viewer=${p} reason=${C.reason} code=${C.code??"-"}`),b(Y,Et[Y],Ne(Y))}if(C.bytes.byteLength>g)return o.error(`500 attachment=${E} viewer=${p} reason=port_contract code=over_max_bytes`),b(500,Ce);let N=D.method==="HEAD";if(!N&&C.size!==void 0&&C.size!==C.bytes.byteLength)return o.error(`500 attachment=${E} viewer=${p} reason=port_contract code=size_mismatch`),b(500,Ce);let F=er(A.fileType)??er(C.contentType),v=F!==null&&$r.has(F),M=v?F:"application/octet-stream",L=v&&y.kind!=="download"?"inline":"attachment",P=N?C.size:C.bytes.byteLength,k=new Headers({"Content-Type":M,"Content-Disposition":`${L}; filename="${qr(A.fileName)}"; filename*=UTF-8''${Fr(A.fileName)}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Ke});return P!==void 0&&k.set("Content-Length",String(P)),S&&k.append("Set-Cookie",S),a(E,!0),o.info(`200 attachment=${E} viewer=${p} type=${M} disposition=${L} bytes=${P??"-"}`),N?new Response(null,{status:200,headers:k}):(x=!0,new Response(fa(C.bytes,U),{status:200,headers:k}))}finally{x||U()}}};var ce=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),js=ce.queueWaitMs+ce.readMs+ce.renderMs+ce.transferMarginMs;import{createHash as Ra}from"crypto";var ut=e=>{let t=JSON.stringify(e);return`"${Ra("sha256").update(t).digest("hex")}"`};import{Buffer as ga}from"buffer";var Gr=new Set([194,198,202,206]),ba=new Set([192,193,194,195]),Xr=216,Sa=217,Qr=218,Aa=4,Ta=64,Da=2,Jr=8,Kr=28,ve=12,rr=8,_a=20,Zr=ve+rr+10,Ea=2,_e=(e,t)=>e[t]<<8|e[t+1],Ge=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},Se=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},en=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,tn=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),rn=e=>(e.stepsLeft-=1,e.stepsLeft>=0),nn=e=>e[0]===255&&e[1]===Xr,on=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!rn(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let o=e[n];if(n+=1,o===Sa)return"eoi";if(o===0||o===Xr)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=_e(e,n),l=n+a;return a<2||l>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=l,"segment")}},wa=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!rn(r))return null;if(a+1>=n)return n;let l=e[a+1];if(l===255)a+=1;else if(l===0||l>=208&&l<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},an=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=_e(e,r+1),a=_e(e,r+3),l=e[r+5];if(a===0||o===0||l===0||n!==8+3*l)return null;let i=[];for(let h=0;h<l;h+=1){let s=e[r+7+3*h],D=s>>4,y=s&15;if(D<1||D>4||y<1||y>4)return null;i.push({id:e[r+6+3*h],horizontal:D,vertical:y})}return{marker:t,width:a,height:o,components:i}},sn=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>Aa||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},ln=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:Gr.has(e.marker)||t<e.components.length}),nr=e=>{if(!nn(e))return null;let t=tn(e.byteLength),r=null;for(let n=2;;){if(on(e,n,t)!=="segment")return null;if(en(t.marker)){if(r!==null||(r=an(e,t),r===null))return null}else if(t.marker===Qr){if(r===null)return null;let o=sn(e,t);return o===null?null:ln(r,o.length)}n=t.end}},un=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:o})=>{let a=Math.ceil(e.width*n/(t*Jr)),l=Math.ceil(e.height*o/(r*Jr));return Math.ceil(a/n)*n*Math.ceil(l/o)*o})},cn=e=>e.multiScan?un(e).reduce((r,n)=>r+n,0)*Ta*Da:0,Ia=896,dn=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!nn(e))return null;let n=ga.from(e.buffer,e.byteOffset,e.byteLength),o=tn(r),a=null,l=null,i=new Map,h=0,s=0,D=0;for(let y=2;;){let E=on(e,y,o);if(E===null)return null;if(E==="eoi")return l===null?null:{header:l,blockVisits:s};if(y=o.end,en(o.marker)){if(a!==null||!ba.has(o.marker)||(a=an(e,o),a===null))return null;let p=un(a);i=new Map;for(let[d,S]of a.components.entries()){let b=i.get(S.id);i.set(S.id,b===void 0?p[d]:Math.max(b,p[d]))}h=a.components.length*(Gr.has(a.marker)?Ia:1)}else if(o.marker===Qr){if(a===null||D===h)return null;let p=sn(e,o);if(p===null)return null;for(let S of p){let b=i.get(S);if(b===void 0)return null;s+=b}if(D+=1,l===null&&(l=ln(a,p.length)),s>t||!l.multiScan)return{header:l,blockVisits:s};let d=wa(n,o.end,o);if(d===null)return null;y=d}}},mn=e=>{if(e.byteLength<24||_e(e,8)!==0||_e(e,10)!==13||!Se(e,12,"IHDR"))return null;let t=_e(e,16)*65536+_e(e,18),r=_e(e,20)*65536+_e(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},xa=e=>{if(Se(e,ve,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Ge(e,26,2)&16383,r=Ge(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Se(e,ve,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Ge(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Se(e,ve,"VP8X")?e.byteLength<Zr?null:{width:Ge(e,24,3)+1,height:Ge(e,27,3)+1}:null},pn=e=>{if(mn(e)===null||e.byteLength<=Kr)return null;switch(e[Kr]){case 0:return!1;case 1:return!0;default:return null}},yn=(e,t)=>{if(Se(e,ve,"VP8 "))return"lossy";if(Se(e,ve,"VP8L"))return"lossless";if(!Se(e,ve,"VP8X")||e.byteLength<Zr)return null;if((e[_a]&Ea)!==0)return"animated";let r=!1,n=t;for(let o=ve;o+rr<=e.byteLength;){if(n-=1,n<0)return null;if(Se(e,o,"VP8L"))return"lossless";if(Se(e,o,"VP8 "))return r?"lossy-alpha":"lossy";Se(e,o,"ALPH")&&(r=!0);let a=Ge(e,o+4,4);o+=rr+a+a%2}return null},hn={png:mn,jpeg:nr,webp:xa};var or=Object.freeze(["image/webp","image/jpeg","image/png"]),ar=1024*1024;var Ca=new Set(["image/png","image/jpeg","image/gif","image/webp"]),va={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Pa=new Set(or),Ma=e=>typeof e=="string"&&Pa.has(e),ka=256,vt=(e,t)=>e.fileType===null||!Ca.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,La=[137,80,78,71,13,10,26,10],Na=[255,216,255],Oa=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Ba=[82,73,70,70],Ua=[87,69,66,80],ct=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,o]of t.entries())if(e[r+n]!==o)return!1;return!0},ir=e=>{if(ct(e,La,0))return"png";if(ct(e,Na,0))return"jpeg";for(let t of Oa)if(ct(e,t,0))return"gif";return ct(e,Ba,0)&&ct(e,Ua,8)?"webp":null},fn=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:ut([t])}},Rn=(e,t)=>{if(!Ma(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>ar)return"too_large";let r=va[e.contentType];if(ir(e.bytes)!==r)return"signature";let n=hn[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},gn=e=>{ye("maxBytes",e.maxBytes,0),ye("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let l=(a.kind==="thumbnail"?a.bytes.byteLength:0)+ka;if(l>e.maxBytes||e.maxEntries===0)return;let i=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:i,weight:l}),r+=l;for(let h of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(h)}}}};var bn=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let h=new AbortController,s=()=>{e.get(t)?.controller===h&&e.delete(t)},y={promise:n(h.signal).finally(s),controller:h,waiters:0};return e.set(t,y),y},a=e.get(t)??o();a.waiters+=1;let l=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?l():r.addEventListener("abort",l,{once:!0});let i=()=>{r.removeEventListener("abort",l)};return a.promise.finally(i)}}};var sr=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,l=Q(),i=new AbortController,h=!1,s,D,y=()=>{a(Q()-l)},E=A=>{s=fe(()=>{h=!0,A({timedOut:!0}),D=fe(y,t),i.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},p=new Promise(E),d=AbortSignal.any([r,i.signal]),S=A=>{A(n(d))},b=new Promise(S),g=A=>(clearTimeout(s),clearTimeout(D),h&&o(Q()-l,A.kind==="error"?{error:A.error}:null),A),w=b.then(A=>g({kind:"value",value:A}),A=>g({kind:"error",error:A}));return{outcome:Promise.race([b.then(A=>({timedOut:!1,value:A})),p]),settled:w}};var Ue={404:"Attachment not found",500:Ce,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Sn=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=Rn(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Ha=e=>{let t=new AbortController,r=()=>{t.abort()},n=fe(r,ce.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},An=()=>{},$a=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),Tn=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:l}=e,i=new Map,h=(p,d)=>{let S=d.then(An,An);i.set(p,S);let b=()=>{i.get(p)===S&&i.delete(p)};S.then(b)},s=async(p,d)=>{let S=i.get(p.key);if(S===void 0)return t.acquire(p.owner,d);let b=Ha(d);try{if(await $a(S,b.signal),b.signal.aborted)return null;let g=r.get(p.key);return g!==void 0?{...g,identity:"verified"}:await t.acquire(p.owner,b.signal)}finally{b.end()}},D=(p,d)=>{if(p.fileSize===null)return d.kind==="exact"?"verified":"unrecorded";if(d.kind==="exact"?d.bytes===p.fileSize:p.fileSize>d.maxBytes)return"verified";let b=d.kind==="exact"?String(d.bytes):`>${d.maxBytes}`;return l.warn(`size_mismatch expected=${p.fileSize} got=${b} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`),"unverified"},y=(p,d)=>(S,b)=>{let g=b===null?"":` message=${b.error instanceof Error?b.error.message:"unknown"}`;l.warn(`${p}_overrun ms=${S} attachment=${d.attachmentId} viewer=${d.owner} variant=thumbnail${g}`)},E=(p,d)=>S=>{l.warn(`${p}_stuck ms=${S} attachment=${d.attachmentId} viewer=${d.owner} variant=thumbnail`)};return async(p,d)=>{let S=await s(p,d);if(S===null)return{kind:"failure",status:503,reason:d.aborted?"aborted":"queue"};if(typeof S!="function")return S;let b=S,g=null;try{if(d.aborted)return{kind:"failure",status:503,reason:"aborted"};let w=r.get(p.key);if(w!==void 0)return{...w,identity:"verified"};let H=sr({budgetMs:ce.readMs,flightSignal:d,call:V=>p.readAttachment(p.filePath,{maxBytes:n,head:!1,principal:o(p.owner),signal:V}),onOverrun:y("read",p),onStuck:E("read",p)}),A=await H.outcome;if(A.timedOut)return g=H.settled,d.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(d.aborted)return{kind:"failure",status:503,reason:"aborted"};let U=A.value;if(!U.ok&&U.reason!=="too_large")return wt(U.reason)?(U.reason==="not_found"&&a(p.attachmentId,!1),{kind:"failure",status:It(U.reason),reason:U.reason,code:U.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(U.ok&&U.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let x=D(p,U.ok?{kind:"exact",bytes:U.bytes.byteLength}:{kind:"over",maxBytes:n}),C=V=>{x==="verified"&&r.set(p.key,V)},N=V=>(C(V),{...V,identity:x});if(!U.ok)return N({kind:"unrenderable",reason:"too_large"});let F=ir(U.bytes);if(F===null)return N({kind:"unrenderable",reason:"signature"});let v=sr({budgetMs:ce.renderMs,flightSignal:d,call:V=>p.renderer.render(U.bytes,{format:F,maxWidth:p.box.maxWidth,maxHeight:p.box.maxHeight,signal:V}),onOverrun:y("render",p),onStuck:E("render",p)}),M=V=>{if(V.kind==="error")return;let W=Sn(V.value,p.box);"entry"in W&&C(W.entry)},L=null,P=()=>(L===null&&(L=v.settled.then(M),h(p.key,L)),L);d.addEventListener("abort",P,{once:!0});let k=await v.outcome.finally(()=>d.removeEventListener("abort",P));if(k.timedOut||d.aborted)return g=P(),d.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let Y=Sn(k.value,p.box);return"entry"in Y?N(Y.entry):Y.failure}finally{g===null?b():g.then(b,b)}}};var En=10,Fa=1/En,Dn=1-Fa,qa=1024,Ya=64,Va=8,_n="private, no-cache",za="no-store",ja=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Wa=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},wn=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,l=t.attachmentDelivery,i=lt({reason:"rate_limit",limitPerMinute:e.rateLimitPerMinute,logger:o,variant:"thumbnail"}),h=lt({reason:"revalidation_rate_limit",limitPerMinute:e.rateLimitPerMinute*En,logger:o,variant:"thumbnail"}),s=Ct({limit:e.concurrency,maxHeldPerOwner:e.concurrency,queue:{max:Ya,maxPerOwner:Va,maxWaitMs:ce.queueWaitMs}}),D=gn({maxBytes:e.cacheBytes,maxEntries:qa}),y=bn(),E=Tn({gate:s,cache:D,maxBytes:l.maxBytes,encodeUserId:r,recordObjectState:a,logger:o}),p=(b,g,w,H)=>{let A=`attachment=${b.attachmentId} viewer=${b.internalUserId} variant=thumbnail cache=${H}`;if(g.kind==="failure")return o[Wa(g)](`${g.status} ${A} reason=${g.reason} code=${g.code??"-"}`),b.fail(g.status,Ue[g.status],Ne(g.status));let U=ja[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${A} reason=${g.reason}${U}`),b.fail(404,Ue[404]);let x=g.identity==="verified"?{"Cache-Control":_n,ETag:w}:{"Cache-Control":za},C=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...x,"Content-Security-Policy":"default-src 'none'; sandbox",...Ke});return b.cookie&&C.append("Set-Cookie",b.cookie),o.info(`200 ${A} type=${g.contentType} bytes=${g.bytes.byteLength}${U}`),new Response(g.bytes,{status:200,headers:C})},d=b=>i.spend(b),S=(b,g)=>g?h.spend(b):d(b);return async(b,g)=>{let{request:w,attachmentId:H,internalUserId:A,readAttachment:U,cookie:x,fail:C}=b,N=Kt[g],F=l.thumbnailRenderer;if(!F)return C(404,Ue[404]);let v=w.headers.get("If-None-Match"),M=v!==null,L=S(b,M);if(L)return L;let P=await n(w),k=await t.getAttachmentForUser(P,H,A),V=k!==null&&vt(k,l.maxBytes)?fn({rendererId:F.id,box:N,attachmentId:H,filePath:k.filePath,fileType:k.fileType,fileSize:k.fileSize}):null;if(V&&Hr(v,V.etag)){let $=new Headers({"Cache-Control":_n,ETag:V.etag,...Ke});return x&&$.append("Set-Cookie",x),o.info(`304 attachment=${H} viewer=${A} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:$})}if(M){let $=d(b);if($)return $}if(!k)return o.warn(`404 attachment=${H} viewer=${A} variant=thumbnail reason=not_visible`),C(404,Ue[404]);if(!V)return i.refund(A,Dn),o.info(`404 attachment=${H} viewer=${A} variant=thumbnail reason=not_eligible`),C(404,Ue[404]);let{key:W,etag:Ee}=V,Z=D.get(W);if(Z)return i.refund(A,Dn),p(b,{...Z,identity:"verified"},Ee,"hit");let be=$=>E({key:W,attachmentId:H,filePath:k.filePath,fileSize:k.fileSize,box:N,owner:A,readAttachment:U,renderer:F},$),Me;try{Me=await y.join(W,w.signal,be)}catch($){return o.error(`500 attachment=${H} viewer=${A} variant=thumbnail cache=miss reason=port_exception message=${$ instanceof Error?$.message:"unknown"}`),C(500,Ue[500])}return p(b,Me,Ee,"miss")}};var Ja='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Ka=()=>_t(403,Qt,{cookie:null}),In=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Gt(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>_t(404,Et[404],{cookie:null}),crossSiteRejection:Ka}),xn=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,l=r.attachmentDelivery,i=zr(e.tuning,l),h={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:Or(r,a)},s=Wr({...h,rateLimitPerMinute:i.originalRateLimitPerMinute,concurrency:i.originalConcurrency}),D=wn({...h,rateLimitPerMinute:i.thumbnailRateLimitPerMinute,concurrency:i.thumbnailConcurrency,cacheBytes:i.thumbnailCacheBytes});return async({request:y,params:E})=>{let p=null,d=(S,b,g={})=>_t(S,b,{cookie:p,extraHeaders:g});try{let{user:S,cookie:b}=await t(y,{failureRedirect:null});if(p=b??null,!S)return d(401,"Unauthorized");let g=Gt(new URL(y.url).searchParams);if(g.kind==="invalid")return d(400,"Invalid attachment request");if(g.kind==="thumbnail"&&y.method!=="GET")return d(405,"Method not allowed",{Allow:"GET"});if(y.method!=="GET"&&y.method!=="HEAD")return d(405,"Method not allowed",{Allow:"GET, HEAD"});let{idCodec:w,readAttachment:H}=l;if(!(w&&H))return d(404,"Attachment not found");if(E.token===void 0)throw new Error(Ja);let A=w.decode(E.token);if(A===null||!Zt(A))return d(400,"Invalid attachment token");let U=await r.getUserIdByExternalId(S.id);if(!U)return d(403,"Forbidden");let x={request:y,delivery:g,attachmentId:A,internalUserId:U,readAttachment:H,cookie:p,fail:d};return g.kind==="thumbnail"?await D(x,g.variant):await s(x)}catch(S){if(S instanceof Response)throw S;return a.error(`500 attachment=? viewer=? reason=unexpected message=${S instanceof Error?S.message:"unknown"}`),d(500,Ce)}}};var Ga=se(1,"[Response]"),de=(e,t,r,n=200,o=Ga)=>{let a=ut(r),l=e.headers.get("If-None-Match");o.info(`[jsonResponseWithETag] ETag: ${a}, If-None-Match: ${l}`);let i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'",ETag:a});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&l===a?new Response(null,{status:304,headers:i}):new Response(JSON.stringify(r),{status:n,headers:i})};var Mt=e=>e.method==="HEAD"?AbortSignal.abort():e.signal;var kt=30,Mn=4e3,Xa="stream interrupted by server error",Qa=15e3,kn=Symbol("ids-stream-heartbeat"),Cn=()=>{},Lt=e=>e.return(void 0).then(Cn,Cn),Za=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(kn),Qa)}),stop:()=>clearTimeout(e)}},ei=/^[0-9a-f]{1,16}$/,ti=e=>{let t=e.searchParams.get("cursor_report_hub_id"),r=e.searchParams.get("cursor_business_date"),n=e.searchParams.get("cursor_snapshot"),o=n!==null&&ei.test(n)?n:null;if(t===null)return r===null?{cursor:null,snapshot:o}:{invalid:!0};let a=Je(t);return a===null?{invalid:!0}:r===null?{cursor:{businessDate:null,reportHubId:a},snapshot:o}:gt(r)?{cursor:{businessDate:r,reportHubId:a},snapshot:o}:{invalid:!0}};async function*vn(e,t,r,n){let o=t?Ir(e,t):0,a=!0;for(;;){let l=e.slice(o,o+(a?r:Mn));o+=l.length;let i=o>=e.length,h=l[l.length-1];if(yield{kind:"chunk",items:l,nextCursor:i||!h?null:{businessDate:h.businessDate,reportHubId:h.reportHubId},isLast:i,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,i)return}}var Ln=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform","X-Content-Type-Options":"nosniff"});return e&&t.append("Set-Cookie",e),t},Pn=(e,t,r,n)=>{let o=new TextEncoder,a=!1,l=null,i=new ReadableStream({async pull(h){if(a||r.aborted){await Lt(t);try{h.close()}catch{}return}let s=Za();try{l===null&&(l=t.next());let D=await Promise.race([l,s.fired]);if(s.stop(),D===kn){if(a||r.aborted){await Lt(t);try{h.close()}catch{}return}h.enqueue(o.encode(`
|
|
2
|
+
`));return}l=null;let{value:y,done:E}=D;if(E){h.close();return}if(a||r.aborted){await Lt(t);try{h.close()}catch{}return}h.enqueue(o.encode(`${JSON.stringify(y)}
|
|
3
|
+
`))}catch(D){if(s.stop(),l=null,a||r.aborted)return;n.error(`ids-stream emission failed: ${D instanceof Error?D.message:String(D)}`);try{let y={kind:"error",error:Xa};h.enqueue(o.encode(`${JSON.stringify(y)}
|
|
4
|
+
`)),h.close()}catch{}}},cancel(){a=!0,Lt(t)}});return new Response(i,{status:200,headers:Ln(e)})},Nn=e=>{let{service:t,logger:r}=e;return async(n,o,a,l,i)=>{let h=ti(n);if("invalid"in h)return de(a,o,{error:{message:"Invalid cursor"}},400);let s=Mt(a);if(s.aborted)return new Response(null,{status:200,headers:Ln(o)});let D=n.searchParams.get("forceRefresh")==="true",y=!1,E=null,p=null,d=new Promise((g,w)=>{E=g,p=w});d.catch(()=>{});let S=t.getDailyReportIdsByExternalId(i,l.id,{forceRefresh:D,onFetchStart:h.cursor?void 0:()=>{y=!0,t.readSseStreamAnchor().then(g=>t.getDailyReportIdsFirstPageByExternalId(i,l.id,kt).then(w=>({items:w,streamAnchor:g}))).then(g=>E?.(g),g=>p?.(g))}});if(S.catch(()=>{}),h.cursor){let{items:g,streamAnchor:w}=await S,H=Wt(g),A=h.snapshot!==null&&h.snapshot===H;return Pn(o,vn(g,A?h.cursor:null,kt,{snapshot:H,restarted:!A,streamAnchor:w}),s,r)}let b=(async function*(){let g=await Promise.race([S.then(A=>({kind:"full",source:A}),A=>({kind:"full-error",error:A})),d.then(A=>({kind:"page",page:A}),()=>({kind:"page-error"}))]),w=null,H=!1;if(g.kind==="full")w=g.source;else if(g.kind==="page"){let{items:A,streamAnchor:U}=g.page;if(A.length<kt){yield{kind:"chunk",items:A,nextCursor:null,isLast:!0,total:A.length,streamAnchor:U};return}yield{kind:"chunk",items:A,nextCursor:null,isLast:!1,provisional:!0},H=!0}else if(g.kind==="full-error"&&y){let A=await d.catch(()=>null);A&&A.items.length>0&&(yield{kind:"chunk",items:A.items,nextCursor:null,isLast:!1,provisional:!0})}w===null&&(w=await S),yield*vn(w.items,null,H?Mn:kt,{snapshot:Wt(w.items),streamAnchor:w.streamAnchor})})();return Pn(o,b,s,r)}};import{systemSseRuntime as gi}from"@aiquants/sse";import{createSseResponse as bi,readLastEventId as Si,startSseHeartbeat as Ai,terminalStreamResponse as Ti}from"@aiquants/sse/server";import{z as R}from"zod";var On=15e3,Bn="lastEventId",ri=/^\d{1,15}-\d{1,15}$/,Un=e=>ri.test(e),ni=R.object({name:R.string().nullish(),affiliation:R.string().nullish()}),oi=R.object({name:R.string().nullish(),text:R.string().nullish(),color:R.string().nullish()}),ai=R.object({id:R.number(),name:R.string().nullish(),color:R.string().nullish()}),Hn=R.object({id:R.number(),userId:R.string().nullish(),userName:R.string().nullish(),content:R.string().nullish(),createdAt:R.string().nullish(),isMine:R.boolean()}),ii=R.object({id:R.string(),fileName:R.string(),fileType:R.string().nullable(),fileSize:R.number().nullable(),createdAt:R.string().nullable(),state:R.enum(["present","absent","unknown"]),hasThumbnail:R.boolean().default(!1)}),lr=R.object({reportHubId:R.number(),date:R.string().nullish(),createdAt:R.string().nullish(),author:R.string().nullish(),userId:R.string().nullish(),sourceType:R.string().nullish(),employeeName:R.string().nullish(),updatedBy:R.string().nullish(),updatedAt:R.string().nullish(),category:R.string().nullish(),creationCategory:R.string().nullish(),visitTimeFrom:R.string().nullish(),visitTimeTo:R.string().nullish(),customerName:R.string().nullish(),interviewers:R.array(ni),subject:R.string().nullish(),content:R.string().nullish(),externalComments:R.array(oi),isRead:R.boolean(),isStarred:R.boolean(),labels:R.array(ai),postedComments:R.array(Hn),attachments:R.array(ii).default([])}),si=R.object({type:R.literal("connected")}),Nt=R.object({type:R.literal("status-update"),reportHubId:R.number(),statusType:R.enum(["star","read"]),value:R.boolean(),clientTempId:R.string(),recipientRawUserId:R.number().optional()}),ur=R.string().optional(),cr=R.object({type:R.literal("comment-add"),reportHubId:R.number(),comment:Hn,clientTempId:R.string(),recipientRawUserId:R.number().optional(),sourceType:ur}),dr=R.object({type:R.literal("comment-delete"),reportHubId:R.number(),commentId:R.number(),clientTempId:R.string(),recipientRawUserId:R.number().optional(),sourceType:ur}),mr=R.object({type:R.literal("report-create"),reportHubId:R.number(),report:lr,clientTempId:R.string(),recipientRawUserId:R.number().optional()}),pr=R.object({type:R.literal("report-update"),reportHubId:R.number(),report:lr,clientTempId:R.string(),recipientRawUserId:R.number().optional()}),yr=R.object({type:R.literal("report-publish"),reportHubId:R.number(),report:lr,clientTempId:R.string(),recipientRawUserId:R.number().optional()}),hr=R.object({type:R.literal("report-delete"),reportHubId:R.number(),clientTempId:R.string(),sourceType:ur}),$n=R.discriminatedUnion("type",[si,Nt,cr,dr,mr,pr,yr,hr]);import{systemSseRuntime as ui}from"@aiquants/sse";import{createSharedSource as ci}from"@aiquants/sse/shared-source";var He="daily-report:ids:",$e="daily-report:business-date:",Ot=(e,t)=>`${e}st:${t}`,fr=e=>`${He}user:${e}:`,Fn=(e,t)=>Ot(fr(e),t),li=e=>`${$e}${e}:`,qn=(e,t)=>Ot(li(e),t),dt=e=>`daily-report:date:${e}:user:`,Xe=(e,t)=>`${dt(e)}${t}:`,Yn=(e,t,r)=>Ot(Xe(e,t),r),Ae=e=>`daily-report:detail:${e}:user:`,Bt=(e,t)=>`${Ae(e)}${t}:`,Vn=(e,t,r)=>Ot(Bt(e,t),r);var Fe=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},di=5e3,mi=100,mt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=t.logger??se(1,"[SSE Reader]"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return ci({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:ui,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",l=>{this._logger.error("Redis client error:",l)});let o=!1,a=this._readLoop(n,t,r,()=>o);return async()=>{if(o=!0,n.isOpen)try{await n.quit()}catch{}await a}}async _readLoop(t,r,n,o){let a=n;try{for(;!o()&&t.isOpen;){let l=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:di,COUNT:mi});if(l)for(let i of l)for(let h of i.messages)a=h.id,this._invalidateCaches(h.message),r.next({id:h.id,message:h.message})}}catch(l){o()||(this._logger.error("xRead loop error:",l),r.fail(l instanceof Error?l:new Error(String(l))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){try{let r=t?.data?JSON.parse(t.data):null,n=r?.type;if((n==="report-create"||n==="report-delete"||n==="report-publish")&&this.config.cache.invalidatePrefix(He),n==="comment-add"||n==="comment-delete"||n==="status-update"){let o=r?.reportHubId;typeof o=="number"&&this.config.cache.invalidatePrefix(Ae(o))}}catch{}}};import{inArray as pi,sql as zn}from"drizzle-orm";var yi="",hi=64,fi=e=>e.toLowerCase(),Ri=e=>e.trim().toLowerCase();function jn(e){if(e==null)return null;if(!Array.isArray(e))return new Set;let t=new Set;for(let r of e){if(typeof r!="string")continue;let n=Ri(r);n.length>0&&t.add(n)}return t}function Te(e,t){return e===null?!0:t==null?!1:e.has(fi(t))}function qe(e){return e!==null&&e.size===0}function Jn(e,t){if(t!==null)return t.size===0?zn`1 = 0`:pi(zn`LOWER(${e})`,[...t])}var Qe,Ze,pt=class pt{constructor(t,r){Vt(this,Qe);Vt(this,Ze);zt(this,Qe,t),zt(this,Ze,r)}get visible(){return ot(this,Qe)===null?null:new Set(ot(this,Qe))}get commentable(){return ot(this,Ze)===null?null:new Set(ot(this,Ze))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=jn(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new pt(n,n);let a=jn(o),l=new Set;for(let i of a??[])n.has(i)&&l.add(i);return new pt(n,l)}static unrestricted(t){return new pt(null,null)}};Qe=new WeakMap,Ze=new WeakMap;var he=pt;function yt(e){let t=Wn(e.visible),r=Wn(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Wn(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(yi);if(t.length<=hi)return`s:${t}`;let r=2166136261;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return`sh:${(r>>>0).toString(16)}`}var Xn=Object.freeze({...st,route:"sse",frameworkDataRefusal:Dt}),Kn=864e5,Di={baseMs:2e3,jitterMs:8e3},Qn=6e4,Rr=1e3,Zn=JSON.stringify({type:"connected"}),Gn="0-0",_i=(e,t,r,n)=>{if(r===null&&n===null)return!0;let o=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Te(r,e.report.sourceType);case"comment-add":case"comment-delete":return Te(n,o??"Internal");case"report-delete":return Te(r,o)}},Ei=["externalComments","postedComments"],wi=(e,t,r)=>{if(r===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"||Te(r,e.report.sourceType))return!1;let n=t.report;for(let o of Ei)n[o]=[];return!0},Ii=(e,t)=>{e.writeEvent({event:null,id:t,data:Zn})},xi=(e,t,r,n,o)=>{if(r.data)try{let a=JSON.parse(r.data),l=$n.safeParse(a);if(!l.success){o.error("SSE message validation failed:",l.error.format());return}let i=l.data,h=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((i.type==="status-update"||h!==void 0)&&h!==n.internalUserId||!_i(i,a,n.visibleSet,n.commentableSet)){Ii(e,t);return}let D=wi(i,a,n.commentableSet),y;if("recipientRawUserId"in a){let{recipientRawUserId:E,...p}=a;y=JSON.stringify(p)}else D?y=JSON.stringify(a):y=r.data;e.writeEvent({event:null,id:t,data:y})}catch(a){o.error(`[SSE:${n.internalUserId}] processEntry error:`,a)}},eo=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:l,logger:i}=e,h=async(s,D)=>{let{request:y,internalUserId:E,cursor:p}=D,d=D.initialScope.visible,S=D.initialScope.commentable,b=0,g=setInterval(()=>{let M=++b;n(y,"refresh").then(L=>{M===b&&(d=L.visible,S=L.commentable)})},Qn);s.onClose(()=>clearInterval(g));let w=p===null?Gn:p,H=p!==null&&o!==void 0,A=[],U=null,x=M=>{Fe(M.id,w)||(w=M.id,xi(s,M.id,M.message,{internalUserId:E,visibleSet:d,commentableSet:S},i))},C=async(M,L)=>{let[P]=await M.xRange(l,"-","+",{COUNT:1});return P!==void 0&&!Fe(P.id,L)},N=async(M,L)=>{if(await C(M,L))return!1;let P=L;for(;;){let k=await M.xRange(l,P,"+",{COUNT:Rr}),Y=k[0];if(Y!==void 0&&Y.id!==P&&await C(M,P))return!1;for(let W of k){if(U!==null&&Fe(U,W.id))return!0;x(W)}let V=k.at(-1);if(k.length<Rr||V===void 0||s.isClosed())return!0;P=V.id}},F=a.subscribe(M=>{if(!H){x(M);return}Fe(M.id,w)||(U===null&&(U=M.id),A.push(M))},M=>{i.error(`[SSE:${E}] Fan-Out reader error:`,M),s.close()});if(s.onClose(F),p===null){await a.ready();try{let M=await o?.getClient();if(M){let L=await M.xRevRange(l,"+","-",{COUNT:1});L.length>0&&!Fe(L[0].id,w)&&(w=L[0].id)}}catch{}}if(s.writeEvent({event:null,id:w===Gn?null:w,data:Zn}),Ai(s,{intervalMs:On,retry:Di,runtime:gi}),p===null||o===void 0)return;await a.ready();let v=await o.getClient();if(v===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await N(v,p)){s.writeRetry(Kn),s.writeEvent({event:"resync-required",id:null,data:""}),s.close();return}H=!1;for(let M of A.splice(0))x(M)};return async({request:s,params:D})=>{let y,E=()=>{let d=new Headers;return y!==void 0&&d.append("Set-Cookie",y),d},p=d=>Ti(d,{data:"",retryMs:Kn,headers:E()});try{let d=await t(s,{failureRedirect:null});y=d.cookie;let{user:S}=d;if(!S)return p("auth-required");let b=await r.getUserIdByExternalId(S.id);if(!b)return p("forbidden");if(D.endpoint!=="updates")return new Response("Not Found",{status:404,headers:E()});let g=Si(s,Bn);if(g!==null&&!Un(g))return i.warn(`[SSE:${b}] malformed resume cursor; asking the client to resync`),p("resync-required");let w=await n(s,"initial");return bi({requestSignal:Mt(s),headers:E(),onError:(H,A)=>i.error(`[SSE:${b}] ${A} failed:`,H),produce:H=>h(H,{request:s,internalUserId:b,cursor:g,initialScope:w})})}catch(d){if(d instanceof Response)throw d;let S=d instanceof Error?d:new Error(String(d));return i.error(`500 sse name=${S.name} message=${S.message}`),new Response("Internal Server Error",{status:500,headers:E()})}}};var Ci=(e,t)=>{let r=new Headers({"Content-Type":"application/json"});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},vi=Object.freeze({...st,route:"api",frameworkDataRefusal:({params:e})=>Jt(e.endpoint)&&At[e.endpoint]==="stream"?Dt():null}),Pi=Object.freeze({...st,route:"action"}),Mi=new Set(["update","publish","delete","toggleStar","toggleRead","addComment"]),ki=e=>e!==null&&Mi.has(e),Li=e=>{let t=Le(e,"intent"),r=Le(e,"businessDate"),n=r===null?null:it(r);if(r!==null&&n===null)return{error:"Invalid businessDate"};let o=Le(e,"operationTimestamp"),a=Nr(o);if(o!==null&&a===null)return{error:"Invalid operationTimestamp"};if(t==="clearCache")return{command:{intent:t}};let l=Le(e,"clientTempId");if(!l)return{error:"clientTempId required"};if(t==="create")return n===null?{error:"businessDate required"}:{command:{intent:t,clientTempId:l,businessDate:n,operationTimestamp:a}};let i=Je(Le(e,"reportHubId"));if(i===null)return{error:"Invalid reportHubId"};if(t==="deleteComment"){let h=Je(Le(e,"commentId"));return h===null?{error:"Invalid commentId"}:{command:{intent:t,clientTempId:l,businessDate:n,operationTimestamp:a,reportHubId:i,commentId:h}}}return ki(t)?{command:{intent:t,clientTempId:l,businessDate:n,operationTimestamp:a,reportHubId:i}}:{error:"Invalid intent"}},Ni=async e=>{try{return await e.formData()}catch{return null}};function gr(e){let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:l}=e,i=e.loginRedirectPath??"/auth/login",h=e.logger??se(3,"[DailyReportAPI]"),s=e.logger??se(3,"[DailyReportVisibility]"),D=e.logger??se(1,"[DailyReportSSE]"),y=e.logger??se(1,"[DailyReportAttachment]"),E=e.logger??se(2,"[DailyReportIsolation]"),p=async(x,C="initial")=>{let N=e.resolveVisibleSourceTypes;if(!N)return he.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let F=await N(x,{reason:C});return F==null?he.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):he.restrictTo(F)}catch(F){return s.error("resolveVisibleSourceTypes threw; failing closed (deny all)",F),he.restrictTo([])}},d=async({request:x})=>{let{user:C,cookie:N}=await t(x,{failureRedirect:i}),F=new Headers;N&&F.append("Set-Cookie",N);let v=await r.getUserIdByExternalId(C.id),M=v?n(v):null;return{data:{user:C,userId:M},headers:F}},S={"business-date":async(x,C,N,F,v)=>{let M=x.searchParams.get("businessDate"),L=M===null?null:it(M);if(L===null)return de(N,C,{error:{message:"Invalid business date"}},400);let P=x.searchParams.get("forceRefresh")==="true",k=await r.getDailyReportsByBusinessDateByExternalId(v,L,F.id,{forceRefresh:P});return de(N,C,{businessDate:L,reports:k},200)},[bt]:Nn({service:r,logger:h}),report:async(x,C,N,F,v)=>{let M=Je(x.searchParams.get("reportHubId"));if(M===null)return de(N,C,{error:{message:"Invalid reportHubId"}},400);let L=x.searchParams.get("forceRefresh")==="true",P=await r.getDailyReportDetailByIdByExternalId(v,M,F.id,{snapshot:!0,forceRefresh:L});return P?de(N,C,{report:P},200):de(N,C,{error:{message:"Report not found"}},404)}},b=async({request:x,params:C})=>{let{user:N,cookie:F}=await t(x,{failureRedirect:null}),v=F??null;if(!N)return de(x,v,{error:{message:"Unauthorized"}},401);let M=C.endpoint;if(!Jt(M))return de(x,v,{error:{message:"Unknown endpoint"}},404);let L=xr[At[M]];if(!L.includes(x.method)){let k=de(x,v,{error:{message:"Method not allowed"}},405);return k.headers.set("Allow",L.join(", ")),k}let P=Q();try{let k=new URL(x.url),Y=await p(x);return await S[M](k,v,x,N,Y)}catch(k){let Y=Q()-P,V=k instanceof Error?k:new Error(String(k));return h.error(`500 endpoint=${M} elapsed=${Y}ms name=${V.name} code=${"code"in V?V.code:"N/A"} message=${V.message}`),h.error("Stack:",V.stack),de(x,v,{error:{message:"Internal Server Error"}},500)}},g=async({request:x,params:C})=>{let{user:N,cookie:F}=await t(x,{failureRedirect:null}),v=(L,P)=>Ci(L,{...P,setCookie:F});if(!N)return v({error:"Unauthorized"},{status:401});let M=Q();try{if(C.endpoint!=="action")return v({error:"Unknown endpoint"},{status:404});let L=await Ni(x);if(L===null)return v({error:"Invalid form"},{status:400});let P=Li(L);if("error"in P)return v({error:P.error},{status:400});let{command:k}=P,Y=await r.getUserIdByExternalId(N.id);if(!Y)return v({error:"User not found"},{status:404});let V=await p(x);if(k.intent==="clearCache")return e.enableDevCacheClear?(await r.clearCache(),v({status:"OK",intent:"clearCache"})):v({error:"Invalid intent"},{status:400});let{clientTempId:W,operationTimestamp:Ee}=k;if(k.intent==="create"){let $=await r.createDailyReport(Y,k.businessDate,W);return v({status:"OK",intent:"create",report:$,reportHubId:String($.reportHubId),clientTempId:W})}let{reportHubId:Z,businessDate:be}=k,Me=async($,te,ue)=>{let we=L.get(te);if(we===null)return v({error:`${te} required`},{status:400});try{let Ie=await ue(we==="true");return v({status:"OK",intent:$,updatedStatus:{isStarred:Ie.isStarred,isRead:Ie.isRead},operationTimestamp:Ee,reportHubId:String(Z),clientTempId:W})}catch(Ie){if(Ie instanceof Error&&Ie.message==="Not Found")return v({error:"Report not found"},{status:404});throw Ie}};switch(k.intent){case"update":{let $=L.get("title"),te=L.get("content");try{return await r.updateDailyReport(Z,Y,{title:$,content:te},W),v({status:"OK",intent:"update",reportHubId:String(Z),clientTempId:W})}catch(ue){if(ue instanceof Error){if(ue.message==="Unauthorized")return v({error:"Unauthorized"},{status:403});if(ue.message==="Not Found")return v({error:"Report not found"},{status:404})}throw ue}}case"publish":try{let $=await r.publishDailyReport(Z,Y,W);return v({status:"OK",intent:"publish",reportHubId:String(Z),clientTempId:W,report:$})}catch($){if($ instanceof Error){if($.message==="Unauthorized")return v({error:"Unauthorized"},{status:403});if($.message==="Not Found")return v({error:"Report not found"},{status:404})}throw $}case"delete":try{return await r.deleteDailyReport(Z,Y,W),v({status:"OK",intent:"delete",reportHubId:String(Z),clientTempId:W})}catch($){if($ instanceof Error){if($.message==="Unauthorized")return v({error:"Unauthorized"},{status:403});if($.message==="Not Found")return v({error:"Report not found"},{status:404})}throw $}case"toggleStar":return await Me("toggleStar","isStarred",$=>r.setStarStatus(V,Y,Z,be,$,W));case"toggleRead":return await Me("toggleRead","isRead",$=>r.setReadStatus(V,Y,Z,be,$,W));case"addComment":{let $=L.get("content");if(!$)return v({error:"Content required"},{status:400});try{let te=await r.addComment(V,Y,Z,$,be,W),ue={...te,userId:te.userId};return v({status:"OK",intent:"addComment",newComment:ue,reportHubId:String(Z),clientTempId:W})}catch(te){if(te instanceof Error){if(te.message==="Not Found")return v({error:"Report not found"},{status:404});if(te.message.startsWith("Comments are restricted"))return v({error:"Comments are restricted for this report"},{status:403})}throw te}}case"deleteComment":{let{commentId:$}=k;try{return await r.deleteComment(V,Y,Z,$,be,W),v({status:"OK",reportHubId:String(Z),deletedCommentId:String($),clientTempId:W})}catch(te){if(te instanceof Error){if(te.message==="Unauthorized")return v({error:"Unauthorized"},{status:403});if(te.message==="Not Found")return v({error:"Comment not found"},{status:404})}throw te}}}}catch(L){if(L instanceof Response)throw L;let P=Q()-M,k=L instanceof Error?L:new Error(String(L));return h.error(`500 action elapsed=${P}ms name=${k.name} message=${k.message}`),h.error("Stack:",k.stack),v({error:"Internal Server Error"},{status:500})}},w=eo({authenticate:t,service:r,resolveViewerScope:p,redis:o,sseReader:a,streamKey:l,logger:D}),H=xn({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:p,logger:y,tuning:e}),A=Lr(E),U=(x,C)=>async N=>{let F=Mr(N.request)?x.frameworkDataRefusal(N):null;if(F!==null)throw F;return kr(N.request,x)?(A(x.route,N.request),x.crossSiteRejection()):C(N)};return{index:{loader:d},api:{loader:U(vi,b),action:U(Pi,g)},sse:{loader:U(Xn,w)},attachment:{loader:U(In,H)}}}import{runWithTransactionRetry as Oi}from"@aiquants/mssql";import{aliasedTable as et,and as G,asc as Ut,desc as tt,eq as I,getColumns as Bi,inArray as Re,isNull as le,or as rt,sql as to}from"drizzle-orm";var Ye=e=>Bi(e),Ui=e=>{if(e!==void 0){if(typeof e!="object"||e===null)throw Oe("attachmentThumbnailRenderer","an object with id and render",e);if(e.render===void 0)throw xt("attachmentThumbnailRenderer.render","a function");if(typeof e.render!="function")throw Oe("attachmentThumbnailRenderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Oe("attachmentThumbnailRenderer.id","a non-blank string naming the rendering pipeline version",e.id);return e}},ie=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),l=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${l}`;let i=String(r.getHours()).padStart(2,"0"),h=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${l} ${i}:${h}:${s}`};function br(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:l,cache:i,epochs:h}=e,{hub:s,internal:D,comment:y,label:E,hubLabel:p,userStatus:d}=r,S=e.externalSources??[],b=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],g=b[0]??"\u4E0B\u66F8\u304D",w=e.logger??se(1,"[DailyReportService]");tr({attachmentIdCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,attachmentThumbnailRenderer:e.attachmentThumbnailRenderer,attachmentMaxBytes:e.attachmentMaxBytes});let H=Object.freeze({idCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,thumbnailRenderer:Ui(e.attachmentThumbnailRenderer),maxBytes:Be("attachmentMaxBytes",e.attachmentMaxBytes,1,Vr)}),A=c=>Oi(u=>t.transaction(m=>u(()=>c(m))),e.transactionRetry),U=e.idsTtlMs??18e4,x="daily-report:ids:epoch",C=e.businessDateTtlMs??3e5,N="daily-report:date-epoch:",F="daily-report:detail-epoch:",M=`${e.streamKey??"daily-report:sse-stream"}:v2`,L=e.streamMaxLen??1e4,P=c=>h.incrementEpoch(c),k=c=>Jn(s.sourceType,c),Y=async(c,u)=>{let m=await l?.getClient();if(!m){w.warn(`[SSE] Redis client unavailable (${u})`);return}let f=Q();try{await m.xAdd(M,"*",{data:JSON.stringify(c)},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:L}});let T=Q()-f;T>1e3&&w.warn(`[SSE] Slow publish (${u}): ${T}ms`)}catch(T){w.error(`[SSE] Redis publish failed (${u}):`,T)}},V=async()=>{try{let c=await l?.getClient();if(c===void 0)return null;let[u]=await c.xRevRange(M,"+","-",{COUNT:1});return u===void 0?null:u.id}catch(c){return w.error("[DailyReportService] SSE stream anchor read failed",c),null}},W=c=>c==null||c===""?null:/^\d+$/.test(c)?a(Number(c)):c,Ee=()=>{let c={};for(let u of S)c[`ext_${u.sourceType}`]=Ye(u.table);return c},Z=c=>{let u=c;for(let m of S)u=u.leftJoin(m.table,G(I(s.sourceType,m.sourceType),I(s.sourceIdNum,m.idColumn)));return u},be=(c,u,m)=>{let{hub:f,internal:T}=u,B=f.summary,_=[],O=null,q=null,z=null,K=null,ee=null,me=null,je=[],xe=S.find(j=>j.sourceType===f.sourceType),We=xe?u[`ext_${xe.sourceType}`]:void 0;if(xe&&We){let j=xe.mapRow(We);j.content!==void 0&&(B=j.content),j.employeeName!==void 0&&(me=j.employeeName),j.category!==void 0&&(O=j.category),j.creationCategory!==void 0&&(q=j.creationCategory),j.visitTimeFrom!==void 0&&(z=j.visitTimeFrom),j.visitTimeTo!==void 0&&(K=j.visitTimeTo),j.customerName!==void 0&&(ee=j.customerName),j.interviewers!==void 0&&(_=j.interviewers),j.externalComments!==void 0&&(je=j.externalComments)}else f.sourceType==="Internal"&&T&&(B=T.body);let De=(u.labels??[]).map(j=>({id:j.id,name:j.name,color:j.color})),oe=u.postedCommentRows??[],X=Te(c.commentable,f.sourceType),ae=q?b.includes(q):!1,Yt=ze?.[0]??null;return ae&&Yt&&!De.some(j=>j.id===Yt)&&De.push({id:Yt,name:g,color:null}),{reportHubId:f.id,date:ie(f.businessDate,"YYYY-MM-DD"),author:u.creatorName??W(f.createdBy)??"",userId:f.userId?a(f.userId):"",sourceType:f.sourceType??"Internal",createdAt:ie(f.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:ie(f.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:W(f.updatedBy),employeeName:me??u.creatorName??W(f.createdBy),category:O,creationCategory:q,visitTimeFrom:z,visitTimeTo:K,customerName:ee,interviewers:_,subject:f.title,content:B,externalComments:X?je:[],isRead:u.isRead??!1,isStarred:u.isStarred??!1,labels:De,postedComments:oe.filter(j=>X||m!==void 0&&j.userId===m).map(j=>({...j,userId:a(j.userId),isMine:m?j.userId===m:!1})),attachments:u.attachments}},Me=async(c,u)=>{let m=et(p,"draft_label"),f=await ke();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).leftJoin(m,G(I(m.hubId,s.id),Re(m.labelId,f))).where(G(le(s.deletedAt),rt(I(s.userId,u),le(s.userId),le(m.hubId)),k(c.visible))).orderBy(tt(s.businessDate),tt(s.id))).map(B=>({...B,businessDate:ie(B.businessDate,"YYYY-MM-DD")}))},$=async(c,u,m)=>{let f=await we(u);if(!f)return[];if(qe(c.visible))return[];let T=et(p,"draft_label"),B=await ke();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(m).from(s).leftJoin(T,G(I(T.hubId,s.id),Re(T.labelId,B))).where(G(le(s.deletedAt),rt(I(s.userId,f),le(s.userId),le(T.hubId)),k(c.visible))).orderBy(tt(s.businessDate),tt(s.id))).map(O=>({...O,businessDate:ie(O.businessDate,"YYYY-MM-DD")}))},te=async(c,u)=>{let m=await Z(t.select({hub:Ye(s),internal:Ye(D),creatorName:n.displayName,...Ee()}).from(s)).leftJoin(D,I(s.id,D.hubId)).leftJoin(n,I(s.userId,n.id)).where(G(I(s.businessDate,to`${u}`),le(s.deletedAt),k(c.visible))).orderBy(tt(s.id)),f=await ft(m.map(T=>T.hub.id));return m.map(T=>be(c,{...T,attachments:f.get(T.hub.id)??[]}))},ue=new Map,we=async c=>{if(!e.disableUserIdCache&&ue.has(c))return ue.get(c)??null;let u=await o(c);return u!==null&&!e.disableUserIdCache&&ue.set(c,u),u},Ie=async(c,u,{forceRefresh:m=!1,snapshot:f=!1,ttlMsOverride:T,onFetchStart:B}={})=>{let _=await we(u);if(!_)return{items:[],streamAnchor:null};if(qe(c.visible))return{items:[],streamAnchor:await V()};let O=Fn(_,yt(c)),[q]=await i.getOrFetch({cacheKey:O,fetcher:async()=>{let z=await V(),K=await Me(c,_);return wr(K)?[{items:K,streamAnchor:z}]:(w.warn("[DailyReportService] ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)"),[{items:[...K].sort(St),streamAnchor:z}])},onFetchStart:B,forceRefresh:m,snapshot:f,ttlMsOverride:T??U,epochKey:x,refreshAheadRatio:.5});if(q===void 0)throw new Error("[DailyReportService] ids cache returned no record");return q},So=(c,u,{forceRefresh:m=!1,snapshot:f=!1,ttlMsOverride:T}={})=>{let B=pe(u);return B?qe(c.visible)?Promise.resolve([]):i.getOrFetch({cacheKey:qn(B,yt(c)),fetcher:()=>te(c,B),forceRefresh:m,snapshot:f,ttlMsOverride:T??C}):Promise.resolve([])},ze=null,ht=async()=>(ze!==null||(ze=(await t.select({id:E.id}).from(E).where(Re(E.name,b)).orderBy(E.id)).map(u=>u.id)),ze),ke=async()=>{let c=await ht();return c.length>0?c:[-1]},$t=async()=>{let c=await ht();if(c.length===0)return null;let[u]=await t.select({id:E.id}).top(1).from(E).where(I(E.name,g));return u?.id??c[0]},Ao=(c,u)=>u!=null?"absent":c!=null?"present":"unknown",ft=async c=>{let u=new Map,m=r.attachment,f=H.idCodec;if(c.length===0||!m||!f)return u;let T=H.thumbnailRenderer!==void 0&&H.readAttachment!==void 0,B=await t.select({id:m.id,hubId:m.hubId,fileName:m.fileName,fileType:m.fileType,fileSize:m.fileSize,createdAt:m.createdAt,objectCheckedAt:m.objectCheckedAt,objectMissingAt:m.objectMissingAt}).from(m).where(Re(m.hubId,c)).orderBy(Ut(m.createdAt),Ut(m.id));for(let _ of B){let O=_.fileType?String(_.fileType):null,q=_.fileSize!=null?Number(_.fileSize):null,z=Ao(_.objectCheckedAt,_.objectMissingAt),K={id:f.encode(Number(_.id)),fileName:String(_.fileName),fileType:O,fileSize:q,createdAt:ie(_.createdAt,"YYYY-MM-DD HH:mm:ss"),state:z,hasThumbnail:T&&z!=="absent"&&vt({fileType:O,fileSize:q},H.maxBytes)},ee=u.get(Number(_.hubId));ee?ee.push(K):u.set(Number(_.hubId),[K])}return u},To=async(c,u,m)=>{let f=r.attachment;if(!f||qe(c.visible))return null;let T=await ke(),B=et(p,"draft_label");return(await t.select({fileName:f.fileName,filePath:f.filePath,fileType:f.fileType,fileSize:f.fileSize}).top(1).from(f).innerJoin(s,I(s.id,f.hubId)).leftJoin(B,G(I(B.hubId,s.id),Re(B.labelId,T))).where(G(I(f.id,u),le(s.deletedAt),rt(I(s.userId,m),le(B.hubId)),k(c.visible))))[0]??null},Do=async c=>{let u=r.attachment;if(!u)return;let m=new Date;try{await t.update(u).set({objectCheckedAt:m,objectMissingAt:m,updatedAt:m}).where(I(u.id,c))}catch(f){w.error("markAttachmentMissing failed",f)}},_o=async c=>{let u=r.attachment;if(!u)return;let m=new Date;try{await t.update(u).set({objectCheckedAt:m,objectMissingAt:null,updatedAt:m}).where(I(u.id,c))}catch(f){w.error("markAttachmentPresent failed",f)}},Eo=async(c,u,m,{forceRefresh:f=!1,snapshot:T=!1,ttlMsOverride:B}={})=>{let _=await we(m);if(!_)return[];let O=pe(u);if(!O)return[];if(qe(c.visible))return[];let q=Yn(O,_,yt(c));return i.getOrFetch({cacheKey:q,fetcher:async()=>{let z=await ke(),K=et(p,"draft_label"),ee=await Z(t.select({hub:Ye(s),internal:Ye(D),isRead:d.isRead,isStarred:d.isStarred,creatorName:n.displayName,...Ee()}).from(s)).leftJoin(D,I(s.id,D.hubId)).leftJoin(d,G(I(s.id,d.hubId),I(d.userId,_))).leftJoin(K,G(I(K.hubId,s.id),Re(K.labelId,z))).leftJoin(n,I(s.userId,n.id)).where(G(I(s.businessDate,to`${O}`),le(s.deletedAt),rt(I(s.userId,_),le(K.hubId)),k(c.visible))).orderBy(tt(s.id));if(ee.length===0)return[];let me=ee.map(X=>X.hub.id),je=await t.select({hubId:p.hubId,id:E.id,name:E.name,color:E.color}).from(p).innerJoin(E,I(p.labelId,E.id)).where(Re(p.hubId,me)),xe=await t.select({hubId:y.hubId,id:y.id,body:y.body,createdAt:y.createdAt,userId:y.userId,userName:n.displayName}).from(y).leftJoin(n,I(y.userId,n.id)).where(Re(y.hubId,me)).orderBy(Ut(y.createdAt)),We=await ft(me),De=new Map,oe=new Map;for(let X of je){let ae=De.get(X.hubId);ae||(ae=[],De.set(X.hubId,ae)),ae.push({id:X.id,name:X.name,color:X.color})}for(let X of xe){let ae=oe.get(X.hubId);ae||(ae=[],oe.set(X.hubId,ae)),ae.push({id:X.id,content:X.body,createdAt:ie(X.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:X.userId,userName:X.userName||""})}return ee.map(X=>{let ae=X.hub.id;return be(c,{...X,attachments:We.get(ae)??[],labels:De.get(ae)||[],postedCommentRows:oe.get(ae)||[]},_)})},forceRefresh:f,snapshot:T,ttlMsOverride:B??C,epochKey:`${N}${O}`})},nt=async(c,u,m,{forceRefresh:f=!1,snapshot:T=!1,ttlMsOverride:B}={})=>{if(qe(c.visible))return null;let _=Vn(u,m,yt(c));return(await i.getOrFetch({cacheKey:_,fetcher:async()=>{let q=await ke(),z=et(p,"draft_label"),K=await Z(t.select({hub:Ye(s),internal:Ye(D),isRead:d.isRead,isStarred:d.isStarred,creatorName:n.displayName,...Ee()}).from(s)).leftJoin(D,I(s.id,D.hubId)).leftJoin(d,G(I(s.id,d.hubId),I(d.userId,m))).leftJoin(z,G(I(z.hubId,s.id),Re(z.labelId,q))).leftJoin(n,I(s.userId,n.id)).where(G(I(s.id,u),le(s.deletedAt),rt(I(s.userId,m),le(z.hubId)),k(c.visible)));if(K.length===0)return[];let ee=K[0].hub.id,me=await t.select({id:E.id,name:E.name,color:E.color}).from(p).innerJoin(E,I(p.labelId,E.id)).where(I(p.hubId,ee)),je=await t.select({id:y.id,body:y.body,createdAt:y.createdAt,userId:y.userId,userName:n.displayName}).from(y).leftJoin(n,I(y.userId,n.id)).where(I(y.hubId,ee)).orderBy(Ut(y.createdAt)),xe=await ft([ee]),We=me.map(oe=>({id:oe.id,name:oe.name,color:oe.color})),De=je.map(oe=>({id:oe.id,content:oe.body,createdAt:ie(oe.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:oe.userId,userName:oe.userName||""}));return[be(c,{...K[0],attachments:xe.get(ee)??[],labels:We,postedCommentRows:De},m)]},forceRefresh:f,snapshot:T,ttlMsOverride:B??C,epochKey:`${F}${u}`}))[0]??null},wo=async(c,u,m,f={})=>{let T=await we(m);return T?nt(c,u,T,f):null},Io=async(c,u)=>{let m=await ke(),f=et(p,"draft_label"),[T]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).leftJoin(f,G(I(f.hubId,s.id),Re(f.labelId,m))).where(G(I(s.id,c),rt(I(s.userId,u),le(f.hubId))));return T??null},Ft=async(c,u,m)=>{let f=await Io(u,m);if(!f||f.deletedAt||!Te(c.visible,f.sourceType))throw new Error("Not Found")},xo=async(c,u,m,f,T,B)=>{await Ft(c,m,u);let _=await t.select().top(1).from(d).where(G(I(d.hubId,m),I(d.userId,u))),O;if(_.length>0?_[0].isStarred!==T?O=(await t.update(d).set({isStarred:T,updatedAt:new Date,updatedBy:String(u)}).output().where(G(I(d.hubId,m),I(d.userId,u))))[0]:O=_[0]:O=(await t.insert(d).output().values({hubId:m,userId:u,isStarred:T,isRead:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],f){let q=pe(f);q&&(i.invalidatePrefix(Xe(q,u)),await P(`${N}${q}`))}return i.invalidatePrefix(Bt(m,u)),await P(`${F}${m}`),await Y(Nt.parse({type:"status-update",reportHubId:m,recipientRawUserId:u,statusType:"star",value:T,clientTempId:B}),"setStarStatus"),O},Co=async(c,u,m,f,T,B)=>{await Ft(c,m,u);let _=await t.select().top(1).from(d).where(G(I(d.hubId,m),I(d.userId,u))),O;if(_.length>0?_[0].isRead!==T?O=(await t.update(d).set({isRead:T,updatedAt:new Date,updatedBy:String(u)}).output().where(G(I(d.hubId,m),I(d.userId,u))))[0]:O=_[0]:O=(await t.insert(d).output().values({hubId:m,userId:u,isRead:T,isStarred:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],f){let q=pe(f);q&&(i.invalidatePrefix(Xe(q,u)),await P(`${N}${q}`))}return i.invalidatePrefix(Bt(m,u)),await P(`${F}${m}`),await Y(Nt.parse({type:"status-update",reportHubId:m,recipientRawUserId:u,statusType:"read",value:T,clientTempId:B}),"setReadStatus"),O},Sr=async(c,u)=>{if(u===null)return;let m=await ke(),[f]=await t.select({hubId:p.hubId}).top(1).from(p).where(G(I(p.hubId,c),Re(p.labelId,m)));return f?u:void 0},vo=async(c,u,m,f,T,B)=>{let[_]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where(I(s.id,m));if(!_||_.deletedAt)throw new Error("Not Found");if(await Ft(c,m,u),!Te(c.commentable,_.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(_.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let O=await Sr(m,_.userId),[q]=await t.insert(y).output().values({hubId:m,userId:u,body:f,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}),[z]=await t.select({displayName:n.displayName}).top(1).from(n).where(I(n.id,u)),K=z?.displayName??"";if(T){let me=pe(T);me&&(i.invalidatePrefix(dt(me)),await P(`${N}${me}`))}i.invalidatePrefix(Ae(m)),await P(`${F}${m}`);let ee={id:q.id,userId:a(q.userId),userName:K,content:q.body,createdAt:ie(q.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await Y(cr.parse({type:"comment-add",reportHubId:m,comment:ee,clientTempId:B,recipientRawUserId:O,sourceType:_.sourceType}),"addComment"),ee},Po=async(c,u)=>await c.select().top(1).from(y).where(I(y.id,u)),Mo=async(c,u,m,f,T,B)=>{let _=await Po(t,f);if(_.length===0)throw new Error("Not Found");if(_[0].hubId!==m)throw new Error("Not Found");let[O]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where(I(s.id,_[0].hubId));if(!(O&&Te(c.visible,O.sourceType)))throw new Error("Not Found");if(_[0].userId!==u)throw new Error("Unauthorized");let q=await Sr(m,O.userId);if(await t.delete(y).where(I(y.id,f)),T){let z=pe(T);z&&(i.invalidatePrefix(dt(z)),await P(`${N}${z}`))}i.invalidatePrefix(Ae(m)),await P(`${F}${m}`),await Y(dr.parse({type:"comment-delete",reportHubId:m,commentId:f,clientTempId:B,recipientRawUserId:q,sourceType:O?.sourceType}),"deleteComment")},ko=async(c,u,m)=>{if(!gt(u))throw Oe("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",u);w.info("createDailyReport called",{userId:c,businessDate:u});let[f]=await t.select({displayName:n.displayName}).from(n).where(I(n.id,c)),T=f?.displayName??a(c);try{let B=await A(async O=>{w.info("Starting transaction");let q=`internal-temp-${Date.now()}-${Math.random()}`,[z]=await O.insert(s).output().values({sourceType:"Internal",sourceId:q,businessDate:new Date(`${u}T00:00:00Z`),userId:c,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)});await O.update(s).set({sourceId:String(z.id)}).where(I(s.id,z.id)),w.info("Hub created",z),await O.insert(D).values({hubId:z.id,body:"",createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)}),w.info("Internal created"),w.info("Calling getDraftLabelId");let K=await $t();w.info("draftLabelId",K);let ee=[];return K&&(await O.insert(p).values({hubId:z.id,labelId:K,createdAt:new Date,createdBy:String(c)}),ee.push({id:K,name:g,color:null})),w.info("Label assigned"),{reportHubId:z.id,date:u,createdAt:ie(z.createdAt,"YYYY-MM-DD HH:mm:ss"),author:T,userId:a(c),sourceType:"Internal",employeeName:T,updatedBy:a(c),updatedAt:ie(z.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:z.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:ee,postedComments:[],attachments:[]}});i.invalidatePrefix(Xe(u,c)),i.invalidatePrefix($e),i.invalidatePrefix(fr(c)),await P(x),await P(`${N}${u}`);let _=await nt(he.unrestricted("post-write self read: the writer always sees the row they just wrote"),B.reportHubId,c,{forceRefresh:!0});if(_){let O=await ht(),q=_.labels.some(z=>O.includes(z.id));await Y(mr.parse({type:"report-create",reportHubId:_.reportHubId,report:_,clientTempId:m,recipientRawUserId:q?c:void 0}),"createDailyReport")}return _??B}catch(B){throw w.error("Error in createDailyReport",B),B}},Rt=async(c,u)=>await c.select().top(1).from(s).where(I(s.id,u)),qt=async(c,u,m)=>{await c.update(s).set(m).where(I(s.id,u))},Ar=async(c,u,m)=>{await c.update(D).set(m).where(I(D.hubId,u))},Tr=async(c,u,m)=>{await c.delete(p).where(G(I(p.hubId,u),I(p.labelId,m)))};return{streamKey:M,streamMaxLen:L,attachmentDelivery:H,clearCache:async()=>{i.clearAll(),ue.clear(),ze=null,h&&await P(x),w.info("[DailyReportService] Server-side DB/SQL caches cleared successfully.")},invalidateHubReadCaches:async(c,u)=>{i.invalidatePrefix($e),i.invalidatePrefix(He),await P(x);for(let m of new Set(c))i.invalidatePrefix(Ae(m)),await P(`${F}${m}`);for(let m of new Set(u)){let f=pe(m);f&&await P(`${N}${f}`)}},getUserIdByExternalId:we,getDailyReportIdsByExternalId:Ie,getDailyReportIdsFirstPageByExternalId:$,readSseStreamAnchor:V,getDailyReportsByBusinessDate:So,getDailyReportsByBusinessDateByExternalId:Eo,getDailyReportDetailById:nt,getDailyReportDetailByIdByExternalId:wo,getDraftLabelId:$t,getAttachmentsByHubIds:ft,getAttachmentForUser:To,markAttachmentMissing:Do,markAttachmentPresent:_o,setStarStatus:xo,setReadStatus:Co,addComment:vo,deleteComment:Mo,createDailyReport:ko,updateDailyReport:async(c,u,m,f)=>{let T=await Rt(t,c);if(!T.length||T[0].deletedAt)throw new Error("Not Found");if(T[0].userId!==u)throw new Error("Unauthorized");await A(async O=>{m.title!==void 0&&await qt(O,c,{title:m.title,updatedAt:new Date,updatedBy:String(u)}),m.content!==void 0&&await Ar(O,c,{body:m.content,updatedAt:new Date,updatedBy:String(u)})}),i.invalidatePrefix(Ae(c)),i.invalidatePrefix($e),await P(`${F}${c}`);let B=pe(ie(T[0].businessDate,"YYYY-MM-DD"));B&&(i.invalidatePrefix(dt(B)),await P(`${N}${B}`));let _=await nt(he.unrestricted("post-write self read: the writer always sees the row they just wrote"),c,u,{forceRefresh:!0});if(_){let O=await ht(),q=_.labels.some(z=>O.includes(z.id));await Y(pr.parse({type:"report-update",reportHubId:_.reportHubId,report:_,clientTempId:f,recipientRawUserId:q?u:void 0}),"updateDailyReport")}},publishDailyReport:async(c,u,m)=>{let f=await Rt(t,c);if(!f.length)throw new Error("Not Found");if(f[0].userId!==u)throw new Error("Unauthorized");let T=await $t();if(!T)return null;if(await Tr(t,c,T),i.invalidatePrefix(Ae(c)),i.invalidatePrefix($e),i.invalidatePrefix(He),await P(x),f[0].businessDate){let O=pe(ie(f[0].businessDate,"YYYY-MM-DD"));O&&await P(`${N}${O}`)}let B=pe(ie(f[0].businessDate,"YYYY-MM-DD"));B&&i.invalidatePrefix(Xe(B,u));let _=await nt(he.unrestricted("post-write self read: the writer always sees the row they just wrote"),c,u,{forceRefresh:!0});return _&&await Y(yr.parse({type:"report-publish",reportHubId:_.reportHubId,report:_,clientTempId:m}),"publishDailyReport"),_??null},deleteDailyReport:async(c,u,m)=>{let f=await Rt(t,c);if(!f.length||f[0].deletedAt)throw new Error("Not Found");if(f[0].userId!==u)throw new Error("Unauthorized");if(await qt(t,c,{deletedAt:new Date,deletedBy:String(u),updatedAt:new Date,updatedBy:String(u)}),i.invalidatePrefix(Ae(c)),i.invalidatePrefix($e),i.invalidatePrefix(He),await P(x),f[0].businessDate){let T=pe(ie(f[0].businessDate,"YYYY-MM-DD"));T&&await P(`${N}${T}`)}await Y(hr.parse({type:"report-delete",reportHubId:c,clientTempId:m,sourceType:f[0].sourceType}),"deleteDailyReport")},findDailyReportHubById:Rt,updateDailyReportHub:qt,updateDailyReportInternal:Ar,deleteDailyReportLabel:Tr}}var Hi=se(1,"[DailyReportExternalSource]"),$i=(e,t,r,n=Hi)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(n.warn(`Unexpected ${t} format: not an array`),[])}catch(o){return n.warn(`Failed to parse ${t}:`,o),[]}};import{desc as ro,sql as Fi}from"drizzle-orm";import{bigint as re,bit as no,date as qi,datetime2 as ne,foreignKey as ge,index as Pe,int as Yi,mssqlSchema as Vi,nvarchar as J,primaryKey as Ve,uniqueIndex as zi}from"drizzle-orm/mssql-core";function ji(e,t){let r=Vi(e),n=t.userTable,o=r.table("DailyReportHub",{id:re("id",{mode:"number"}).identity().notNull(),sourceType:J("source_type",{length:20}).notNull(),sourceId:J("source_id",{length:100}).notNull(),sourceIdNum:re("source_id_num",{mode:"number"}).generatedAlwaysAs(Fi`TRY_CAST(source_id AS BIGINT)`),businessDate:qi("business_date"),userId:re("user_id",{mode:"number"}),title:J("title",{length:200}),summary:J("summary",{length:"max"}),createdAt:ne("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull(),updatedAt:ne("updated_at").notNull(),updatedBy:J("updated_by",{length:50}).notNull(),deletedAt:ne("deleted_at"),deletedBy:J("deleted_by",{length:50})},y=>[Ve({name:`${e}_DailyReportHub_pk`,columns:[y.id]}),ge({name:`${e}_DailyReportHub_user_id_fk`,columns:[y.userId],foreignColumns:[n.id]}),Pe(`${e}_DailyReportHub_business_date_index`).on(y.businessDate),Pe(`${e}_DailyReportHub_updated_at_index`).on(y.updatedAt),Pe(`${e}_DailyReportHub_source_index`).on(y.sourceType,y.sourceId),Pe(`${e}_DailyReportHub_user_id_index`).on(y.userId),Pe(`${e}_DailyReportHub_business_date_id_index`).on(ro(y.businessDate),ro(y.id)),Pe(`${e}_DailyReportHub_deleted_at_index`).on(y.deletedAt)]),a=r.table("DailyReportInternal",{hubId:re("hub_id",{mode:"number"}).notNull(),body:J("body",{length:"max"}),metadata:J("metadata",{length:"max"}),createdAt:ne("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull(),updatedAt:ne("updated_at").notNull(),updatedBy:J("updated_by",{length:50}).notNull()},y=>[Ve({name:`${e}_DailyReportInternal_pk`,columns:[y.hubId]}),ge({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[y.hubId],foreignColumns:[o.id]})]),l=r.table("DailyReportComment",{id:re("id",{mode:"number"}).identity().notNull(),hubId:re("hub_id",{mode:"number"}).notNull(),userId:re("user_id",{mode:"number"}).notNull(),body:J("body",{length:"max"}).notNull(),createdAt:ne("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull(),updatedAt:ne("updated_at").notNull(),updatedBy:J("updated_by",{length:50}).notNull()},y=>[Ve({name:`${e}_DailyReportComment_pk`,columns:[y.id]}),ge({name:`${e}_DailyReportComment_hub_id_fk`,columns:[y.hubId],foreignColumns:[o.id]}),ge({name:`${e}_DailyReportComment_user_id_fk`,columns:[y.userId],foreignColumns:[n.id]}),Pe(`${e}_DailyReportComment_hub_id_index`).on(y.hubId)]),i=r.table("DailyReportLabel",{id:re("id",{mode:"number"}).identity().notNull(),userId:re("user_id",{mode:"number"}),name:J("name",{length:50}).notNull(),color:J("color",{length:20}),sortOrder:Yi("sort_order"),createdAt:ne("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull(),updatedAt:ne("updated_at").notNull(),updatedBy:J("updated_by",{length:50}).notNull()},y=>[Ve({name:`${e}_DailyReportLabel_pk`,columns:[y.id]}),ge({name:`${e}_DailyReportLabel_user_id_fk`,columns:[y.userId],foreignColumns:[n.id]})]),h=r.table("DailyReportHub_Label",{hubId:re("hub_id",{mode:"number"}).notNull(),labelId:re("label_id",{mode:"number"}).notNull(),createdAt:ne("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull()},y=>[Ve({name:`${e}_DailyReportHub_Label_pk`,columns:[y.hubId,y.labelId]}),ge({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[y.hubId],foreignColumns:[o.id]}),ge({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[y.labelId],foreignColumns:[i.id]})]),s=r.table("DailyReportUserStatus",{hubId:re("hub_id",{mode:"number"}).notNull(),userId:re("user_id",{mode:"number"}).notNull(),isRead:no("is_read").default(!1).notNull(),isStarred:no("is_starred").default(!1).notNull(),createdAt:ne("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull(),updatedAt:ne("updated_at").notNull(),updatedBy:J("updated_by",{length:50}).notNull()},y=>[Ve({name:`${e}_DailyReportUserStatus_pk`,columns:[y.hubId,y.userId]}),ge({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[y.hubId],foreignColumns:[o.id]}),ge({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[y.userId],foreignColumns:[n.id]})]),D=r.table("DailyReportAttachment",{id:re("id",{mode:"number"}).identity().notNull(),hubId:re("hub_id",{mode:"number"}).notNull(),uploadedBy:re("uploaded_by",{mode:"number"}),sourceKey:J("source_key",{length:200}).notNull(),fileName:J("file_name",{length:255}).notNull(),filePath:J("file_path",{length:"max"}).notNull(),fileType:J("file_type",{length:100}),fileSize:re("file_size",{mode:"number"}),objectCheckedAt:ne("object_checked_at"),objectMissingAt:ne("object_missing_at"),createdAt:ne("created_at").notNull(),createdBy:J("created_by",{length:50}).notNull(),updatedAt:ne("updated_at").notNull(),updatedBy:J("updated_by",{length:50}).notNull()},y=>[Ve({name:`${e}_DailyReportAttachment_pk`,columns:[y.id]}),ge({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[y.hubId],foreignColumns:[o.id]}),ge({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[y.uploadedBy],foreignColumns:[n.id]}),zi(`${e}_DailyReportAttachment_source_unique`).on(y.hubId,y.sourceKey),Pe(`${e}_DailyReportAttachment_hub_id_index`).on(y.hubId,y.createdAt)]);return{hub:o,internal:a,comment:l,attachment:D,label:i,hubLabel:h,userStatus:s}}var Wi=5e7,ho=2e8,Ji=1,fo=Object.freeze({fixedBytes:4*1024*1024,pipelineRows:2048,wholeImageBuffer:Object.freeze({"jpeg-single-scan":Object.freeze({kind:"none"}),"jpeg-multi-scan":Object.freeze({kind:"jpeg-coefficients"}),png:Object.freeze({kind:"none"}),"png-interlaced":Object.freeze({kind:"decoded-raster"}),gif:Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-lossy":Object.freeze({kind:"none"}),"webp-lossy-alpha":Object.freeze({kind:"canvas",bytesPerPixel:5}),"webp-lossless":Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-animated":Object.freeze({kind:"canvas",bytesPerPixel:9})})}),oo=125,ao=4,io=16,so=50,lo=2,Ht=Object.freeze({renderMs:ce.renderMs,nanosecondsPerBlockVisit:oo,margin:ao,maxBlockVisits:Math.floor(ce.renderMs*1e6/(oo*ao)),walkBudgetMs:io,nanosecondsPerWalkStep:so,walkMargin:lo,maxWalkSteps:Math.floor(io*1e6/(so*lo))}),Ki=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),uo=75,co=4,mo="#ffffff",Gi=1,Xi={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Qi=[/out of memory/i,/insufficient memory/i,/memory allocation|allocation failed/i,/(?:cannot|could not|unable to|failed to) allocate/i,/picture memory error/i,/unable to create thread|error creating thread|resource temporarily unavailable/i,/too many open files|no space left on device/i,/\b(?:ENOMEM|EAGAIN|EMFILE|ENFILE|ENOSPC)\b/],po=Object.freeze({ok:!1,reason:"failed"}),yo=Object.freeze({ok:!1,reason:"unsupported"}),Ro=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:cn(e)}),go=(e,t)=>{switch(t){case"jpeg":{let r=nr(e);return r===null?null:Ro(r)}case"png":{let r=pn(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=yn(e,Ht.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},bo=(e,t)=>{let r=Ki.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=fo,a=o.wholeImageBuffer[e.layout];return(a.kind==="none"?0:a.kind==="decoded-raster"?t.width*t.height*n:a.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*a.bytesPerPixel)+o.pipelineRows*t.width*n+o.fixedBytes},Zi=(e,t,r)=>{let n=go(e,t);return n===null?null:bo(n,r)},es=e=>e!==null&&e<=ho,ts=(e,t)=>{if(t!=="jpeg")return go(e,t);let r=dn(e,Ht);return r===null||r.blockVisits>Ht.maxBlockVisits?null:Ro(r.header)},rs=e=>{let t=e instanceof Error?e.message:"";return Qi.some(r=>r.test(t))?"failed":"unsupported"},ns=e=>{e.cache(!1),e.concurrency(Ji),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Xi)});let t=async(n,o,a,l,i)=>{let h=ts(n,o);if(h===null)return yo;try{let s=e(n,{limitInputPixels:Wi,animated:!1});if(!es(bo(h,await s.metadata())))return yo;if(i.aborted)return po;let D=await s.rotate().resize({width:a,height:l,fit:"inside",withoutEnlargement:!0}).flatten({background:mo}).webp({quality:uo,effort:co}).toBuffer();return{ok:!0,bytes:new Uint8Array(D),contentType:"image/webp"}}catch(s){return{ok:!1,reason:rs(s)}}},r=async(n,{format:o,maxWidth:a,maxHeight:l,signal:i})=>i.aborted?po:t(n,o,a,l,i);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${uo}-e${co}/flatten-${mo}/v${Gi}`,render:r}};function zu(e){e.redis||(e.logger??console).warn("[DailyReport] redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=jt(e.redis),r=new at({defaultTtlMs:e.cacheDefaultTtlMs??6e4},t),n=br({...e,cache:r,epochs:t}),o=new mt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=gr({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(l=>l.sourceType)])],...a}}export{ar as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,or as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,ho as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,Ht as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,fo as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,Rr as DAILY_REPORT_SSE_CATCH_UP_BATCH,Qn as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,mt as DailyReportSseReader,he as DailyReportViewerScope,at as SqlResultCache,gr as createDailyReportHandlers,zu as createDailyReportServer,br as createDailyReportService,jt as createEpochStore,ns as createSharpThumbnailRenderer,ji as defineDailyReportSchema,ut as generateETag,Fe as isStreamIdLte,de as jsonResponseWithETag,Zi as predictSharpThumbnailWorkingSetBytes,$i as transformJsonArray};
|
|
5
5
|
/* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */
|