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