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