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