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