@aiquants/daily-report 0.35.0 → 0.37.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,12 +1,12 @@
1
- "use strict";var fr=Object.defineProperty;var wi=Object.getOwnPropertyDescriptor;var _i=Object.getOwnPropertyNames;var xi=Object.prototype.hasOwnProperty;var ln=e=>{throw TypeError(e)};var Ci=(e,t)=>{for(var r in t)fr(e,r,{get:t[r],enumerable:!0})},Pi=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _i(t))!xi.call(e,o)&&o!==r&&fr(e,o,{get:()=>t[o],enumerable:!(n=wi(t,o))||n.enumerable});return e};var Mi=e=>Pi(fr({},"__esModule",{value:!0}),e);var cn=(e,t,r)=>t.has(e)||ln("Cannot "+r);var gt=(e,t,r)=>(cn(e,t,"read from private field"),r?r.call(e):t.get(e)),Rr=(e,t,r)=>t.has(e)?ln("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),gr=(e,t,r,n)=>(cn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var xc={};Ci(xc,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>Qt,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>Gt,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>tn,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Lt,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>rn,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>cr,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>Wr,DailyReportSseReader:()=>ut,DailyReportViewerScope:()=>Ee,SqlResultCache:()=>rt,createDailyReportHandlers:()=>ur,createDailyReportServer:()=>_c,createDailyReportService:()=>mr,createEpochStore:()=>kt,createSharpThumbnailRenderer:()=>Ga,defineDailyReportSchema:()=>Na,defineDailyReportSearchSchema:()=>Oa,generateETag:()=>Jt,isStreamIdLte:()=>qe,jsonResponseWithETag:()=>ae,parseClientTempId:()=>Yt,predictSharpThumbnailWorkingSetBytes:()=>Ja,readDailyReportSseStreamEntry:()=>lt,transformJsonArray:()=>va});module.exports=Mi(xc);var ce=()=>Math.floor(performance.now());var kt=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{}}}),bt=(e,t)=>t?e.map(r=>structuredClone(r)):e,rt=class{constructor(t,r){this.config=t;this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.config.defaultTtlMs;if(a-(o.expireAt-ce())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let p=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===l&&this.buckets.set(n,{records:s,expireAt:ce()+a,epoch:p}),s})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n}=t,o;o=(async()=>{let i=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null;for(let p of r)p();let l=await t.fetcher();if(this.inFlight.get(n)===o){let p=ce()+(t.ttlMsOverride??this.config.defaultTtlMs);this.buckets.set(n,{records:l,expireAt:p,epoch:i}),this.buckets.size>500&&this.cleanExpired()}return l})(),this.inFlight.set(n,o);let a=()=>{this.inFlight.get(n)===o&&this.inFlight.delete(n)};return o.then(a,a),o};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o}=t;if(n)return this.buckets.delete(r),bt(await this.forcedFetch(t),o);let a=this.buckets.get(r);if(a&&a.expireAt>ce())if(t.epochKey){let l=await this.epochStore.getEpoch(t.epochKey);if(l===null||a.epoch===l)return this.maybeRefreshAhead(t),bt(a.records,o);this.buckets.delete(r)}else return this.maybeRefreshAhead(t),bt(a.records,o);let i=this.inFlight.get(r);return bt(i!==void 0?await i:await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};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=ce();for(let[r,n]of this.buckets.entries())n.expireAt<=t&&this.buckets.delete(r)}};var un="ids-stream";var Ut=e=>{let t=2166136261,r=-624069552;for(let n of e){let o=n.reportHubId;t^=o&255,t=Math.imul(t,16777619),t^=o>>>8&255,t=Math.imul(t,16777619),t^=o>>>16&255,t=Math.imul(t,16777619),t^=o>>>24&255,t=Math.imul(t,16777619),r^=o>>>24&255,r=Math.imul(r,16777619),r^=o>>>16&255,r=Math.imul(r,16777619),r^=o>>>8&255,r=Math.imul(r,16777619),r^=o&255,r=Math.imul(r,16777619);let a=n.businessDate;if(a===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let i=0;i<a.length;i++){let l=a.charCodeAt(i);t^=l&255,t=Math.imul(t,16777619),r^=l&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},Bt=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,dn=e=>{for(let t=1;t<e.length;t++)if(Bt(e[t-1],e[t])>0)return!1;return!0},mn=(e,t)=>{let r=e.findIndex(n=>Bt({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var Re=Object.freeze({businessDate:"business-date",idsStream:un,report:"report",search:"search",reports:"reports",action:"action"}),Ae=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var Li=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var pn=e=>e<10?`0${e}`:`${e}`,vi=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=pn(e.getMonth()+1),n=pn(e.getDate());return`${t}-${r}-${n}`},nt=e=>{let t=Li.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let p=new Date(0);return p.setUTCFullYear(a,i-1,l),p.getUTCFullYear()!==a||p.getUTCMonth()!==i-1||p.getUTCDate()!==l?null:`${r}-${n}-${o}`},Ht=e=>nt(e)===e;var we=e=>e==null?null:e instanceof Date?vi(e):nt(e);var Ni=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,ie=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Ni(r)}`),ot=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),br=(e,t,r)=>ie(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),de=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw ie(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},Qe=(e,t,r,n)=>t===void 0?n:de(e,t,r);var yn=(e,t,r=console)=>{let n=o=>typeof o=="string"?[`${t} ${o}`]:[t,o];return{debug:(o,...a)=>{e<=0&&r.debug(...n(o),...a)},info:(o,...a)=>{e<=1&&r.info(...n(o),...a)},warn:(o,...a)=>{e<=2&&r.warn(...n(o),...a)},error:(o,...a)=>{e<=3&&r.error(...n(o),...a)}}},he=(e,t,r)=>e===void 0?yn(t,r):yn(0,r,e);var hn=require("zod"),at=e=>Number.isSafeInteger(e)&&e>0,ge=hn.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var fn=e=>e==="intersection"||e==="union",Pe=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Sr=e=>({ids:e.map(t=>t.reportHubId),businessDates:e.map(t=>t.businessDate),sourceTypes:e.map(t=>t.sourceType)});var Oi=/^[1-9][0-9]*$/,ki=/^(?:0|[1-9][0-9]*)$/,Me=e=>{if(e===null||!Oi.test(e))return null;let t=Number(e);return at(t)?t:null},Dr=e=>{if(e===null||!ki.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Tr=e=>e==="true"?!0:e==="false"?!1:null,St=e=>e===null?!1:Tr(e);var Yi=require("zod");var $t=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;var _=require("zod");var Rn=15e3,gn="lastEventId",Ui=/^\d{1,15}-\d{1,15}$/,bn=e=>Ui.test(e),Bi=_.z.object({name:_.z.string().nullish(),affiliation:_.z.string().nullish()}),Hi=_.z.object({name:_.z.string().nullish(),text:_.z.string().nullish(),color:_.z.string().nullish()}),$i=_.z.object({id:ge,name:_.z.string().nullish(),color:_.z.string().nullish()}),Sn=_.z.object({id:ge,userId:_.z.string().nullish(),userName:_.z.string().nullish(),content:_.z.string().nullish(),createdAt:_.z.string().nullish(),isMine:_.z.boolean()}),Fi=_.z.object({id:_.z.string(),fileName:_.z.string(),fileType:_.z.string().nullable(),fileSize:_.z.number().nullable(),createdAt:_.z.string().nullable(),state:_.z.enum(["present","absent","unknown"]),hasThumbnail:_.z.boolean().default(!1)}),Ar=_.z.object({reportHubId:ge,date:_.z.string().nullish(),createdAt:_.z.string().nullish(),author:_.z.string().nullish(),userId:_.z.string().nullish(),sourceType:_.z.string().nullish(),employeeName:_.z.string().nullish(),updatedBy:_.z.string().nullish(),updatedAt:_.z.string().nullish(),category:_.z.string().nullish(),creationCategory:_.z.string().nullish(),visitTimeFrom:_.z.string().nullish(),visitTimeTo:_.z.string().nullish(),customerName:_.z.string().nullish(),interviewers:_.z.array(Bi),subject:_.z.string().nullish(),content:_.z.string().nullish(),externalComments:_.z.array(Hi),isRead:_.z.boolean(),isStarred:_.z.boolean(),labels:_.z.array($i),postedComments:_.z.array(Sn),attachments:_.z.array(Fi).default([])}),Xe=_.z.string().regex($t),Vi=_.z.object({type:_.z.literal("connected")}),Ft=_.z.object({type:_.z.literal("status-update"),reportHubId:ge,statusType:_.z.enum(["star","read"]),value:_.z.boolean(),clientTempId:Xe,recipientRawUserId:ge.optional()}),Ir=_.z.string().optional(),Er=_.z.object({type:_.z.literal("comment-add"),reportHubId:ge,comment:Sn,clientTempId:Xe,recipientRawUserId:ge.optional(),sourceType:Ir}),wr=_.z.object({type:_.z.literal("comment-delete"),reportHubId:ge,commentId:ge,clientTempId:Xe,recipientRawUserId:ge.optional(),sourceType:Ir}),_r=_.z.object({type:_.z.literal("report-create"),reportHubId:ge,report:Ar,clientTempId:Xe,recipientRawUserId:ge.optional()}),xr=_.z.object({type:_.z.literal("report-update"),reportHubId:ge,report:Ar,clientTempId:Xe,recipientRawUserId:ge.optional()}),Cr=_.z.object({type:_.z.literal("report-publish"),reportHubId:ge,report:Ar,clientTempId:Xe,recipientRawUserId:ge.optional()}),Pr=_.z.object({type:_.z.literal("report-delete"),reportHubId:ge,clientTempId:Xe,sourceType:Ir}),Dn=_.z.discriminatedUnion("type",[Vi,Ft,Er,wr,_r,xr,Cr,Pr]);var _e=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var Vt=Math.max(1,Math.floor(10.556701030927835));var Le=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Ne=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(s=>[s,0]))};o.set(i,l),Le(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,p)=>{let s=o.get(i);if(s!==void 0){s.count+=1,s.tallies[l]+=1;return}p(),a(i)}}};var Yt=e=>e!==null&&$t.test(e)?e:null,Tn=e=>fn(e)?e:null,An=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Pe.maxDetailIds)return null;let r=[];for(let n of t){let o=Me(n);if(o===null||r.includes(o))return null;r.push(o)}return r},In=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var wn=Object.freeze({status:400,error:"Invalid form"}),_n=e=>({status:413,error:"Form too large",measuredBy:e}),qi=(e,t,r)=>{let n=0;return e.pipeThrough(new TransformStream({transform(o,a){if(n+=o.byteLength,n>t){r(),a.error(new Error(`action form body exceeds ${t} bytes`));return}a.enqueue(o)}}))},ji=async e=>{let t=Dr(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:_n("declared")};let r=!1,n=e.body===null?null:qi(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let i;try{i=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?_n("counted"):wn}}let l=In(i);return l===null?{refusal:wn}:{fields:l}},xn=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=Tr(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},Pn=Object.freeze({update:(e,t,r)=>{let n=e.get(_e.title),o=e.get(_e.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:xn("toggleStar",_e.isStarred),toggleRead:xn("toggleRead",_e.isRead),addComment:(e,t)=>{let r=e.get(_e.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Me(e.get(_e.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),zi=e=>Object.hasOwn(Pn,e),Wi=(e,t)=>{let r=e.get(_e.intent),n=e.get(_e.businessDate),o=n===null?null:nt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(_e.operationTimestamp),i=Dr(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(_e.clientTempId);if(!l)return{error:"clientTempId required"};let p=Yt(l);if(p===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:p,businessDate:o,operationTimestamp:i}};let s=Me(e.get(_e.reportHubId));return s===null?{error:"Invalid reportHubId"}:r===null||!zi(r)?{error:"Invalid intent"}:Pn[r](e,{clientTempId:p,businessDate:o,operationTimestamp:i,reportHubId:s},t)},Mn=async(e,t)=>{let r=await ji(e);if("refusal"in r)return r;let n=Wi(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Ki=6e4,Ji="form_too_large",Cn=["declared","counted"],Ln=e=>{let t=Ne({windowMs:Ki,tallies:Cn,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Cn.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(Ji,r,n)}};var Dt=Object.freeze({[Re.businessDate]:{body:"json",admission:["cache","refresh-bucket"]},[Re.idsStream]:{body:"stream",admission:["cache","stream-slots","refresh-bucket"]},[Re.report]:{body:"json",admission:["cache","refresh-bucket"]},[Re.search]:{body:"json",admission:["search-limiter"]},[Re.reports]:{body:"json",admission:["search-limiter"]}}),vn=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Mr=e=>e!==void 0&&Object.hasOwn(Dt,e);var Lr=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Nn=e=>Object.hasOwn(Lr,e);var Gi="download",Qi="thumbnail",Xi="1";var vr=e=>{let t=e.getAll(Qi),r=e.getAll(Gi);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Nn(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Xi?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var Or="Cross-site request rejected",Zi="Not Found",es=new Set(["same-origin","none"]),ts=new Set(["GET","HEAD","OPTIONS"]),On=["api","action","sse","attachment"],kn=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}}),rs=()=>kn(403,Or),qt=()=>kn(404,Zi),Tt=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:rs}),Un=e=>new URL(e.url).pathname.endsWith(".data"),ns=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},Bn=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(ts.has(e.method)||ns(e)):es.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},os=6e4,as="refusals",is=32,ss=/^[a-z-]+$/,Nr=e=>{if(e===null)return"-";let t=e.slice(0,is);return ss.test(t)&&t===e?e:JSON.stringify(t)},Hn=e=>{let t=Ne({windowMs:os,tallies:On,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${On.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${Nr(a.get("Sec-Fetch-Site"))} mode=${Nr(a.get("Sec-Fetch-Mode"))} dest=${Nr(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(as,r,o)}};var $n=(e,t)=>(r,n)=>{let o=n?"markAttachmentPresent":"markAttachmentMissing";e[o](r).catch(a=>{t.error(`${o} failed attachment=${r} message=${a instanceof Error?a.message:"unknown"}`)})};var ls="same-origin",cs="SAMEORIGIN",it=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":ls,"X-Frame-Options":cs}),jt=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...it});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Fn=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),us=/^[\x20-\x7E]+$/,ds=/^[\w.+-]+\/[\w.+-]+/,kr=e=>e&&us.test(e)&&ds.test(e)?e:null,ms=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Vn=e=>encodeURIComponent(e.replace(ms,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Yn=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),zt={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},qn={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Wt=e=>typeof e=="string"&&Object.hasOwn(qn,e),Kt=e=>qn[e],$e="Attachment request failed";var ze=e=>{let t=de("limit",e.limit,1),r=de("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:de("queue.max",e.queue.max,0),maxPerOwner:de("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:de("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,p=(g,A)=>g.get(A)??0,s=(g,A,B)=>{let C=p(g,A)+B;C<=0?g.delete(A):g.set(A,C)},f=g=>p(l,g)<r,m=g=>o<t&&f(g),D=g=>(o+=1,s(l,g,1),b(g)),h=()=>{for(;o<t;){let g=a.findIndex(B=>f(B.owner));if(g<0)return;let[A]=a.splice(g,1);s(i,A.owner,-1),A.grant(D(A.owner))}},b=g=>{let A=!1;return()=>{A||(A=!0,o-=1,s(l,g,-1),h())}};return{canAcquire:m,acquire:(g,A)=>{if(A.aborted)return Promise.resolve(null);if(m(g))return Promise.resolve(D(g));if(n===null||a.length>=n.max||p(i,g)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:B}=n,C=k=>{let M=()=>{let H=a.indexOf(Q);H<0||(a.splice(H,1),s(i,g,-1),V(),k(null))},I=Le(M,B),V=()=>{clearTimeout(I),A.removeEventListener("abort",M)},Q={owner:g,grant:H=>{V(),k(H)}};a.push(Q),s(i,g,1),A.addEventListener("abort",M,{once:!0})};return new Promise(C)}}};var ps=1024,Ur="Too many requests",ys=(e,t)=>{de("limitPerWindow",e,1),de("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let p=l??{tokens:e,lastRefillMs:i};n(p,i),r.set(a,p);for(let s of r.keys()){if(r.size<=ps)break;r.delete(s)}return p};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let p=r.get(a);p&&(n(p,i),p.tokens=Math.min(e,p.tokens+l))}}},Fe=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(de("windowMs",r,1e3)%1e3!==0)throw ie("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=ys(e.limitPerWindow,r),i=Object.freeze({status:429,message:Ur,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Ne({windowMs:r,tallies:[t],writeSuppressed:(p,{count:s,since:f})=>{n.warn(`${t}_suppressed count=${s} since=${f} ${o(p)}`)}});return{spend:(p,s)=>a.consume(p,ce())?null:(l.record(p,t,()=>n.warn(`429 ${s} reason=${t}`)),i),refund:(p,s)=>{a.refund(p,ce(),s)}}};var jn=require("crypto"),Br=e=>`"${(0,jn.createHash)("sha256").update(e).digest("hex")}"`,Jt=e=>Br(JSON.stringify(e));var Hr=(e,t)=>{if(e===null)return!1;for(let r of e.split(",")){let n=r.trim();if((n.startsWith("W/")?n.slice(2):n)===t)return!0}return!1},ae=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=Br(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'",ETag:a});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&Hr(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},hs=5e3/1e3,fs=new Map([[503,hs]]),Ve=e=>{let t=fs.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var gs=256*1024,zn=6e4,bs=e=>Math.ceil(e/2),Ss=new Uint8Array(new ArrayBuffer(0)),Ds=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Ss,t()},i=l=>{clearTimeout(o),o=Le(()=>{l.error(new Error(`attachment body idle for ${zn} ms`)),a()},zn)};return new ReadableStream({start(l){i(l)},pull(l){let p=Math.min(n+gs,r.byteLength);if(p>n&&l.enqueue(r.slice(n,p)),n=p,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},Wn=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=Fe({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:p=>`viewer=${p}`}),l=ze({limit:e.concurrency,maxHeldPerOwner:bs(e.concurrency),queue:null});return async p=>{let{request:s,delivery:f,attachmentId:m,internalUserId:D,readAttachment:h,cookie:b,fail:g}=p,A=e.maxBytes,B=i.spend(D,`attachment=${m} viewer=${D}`);if(B)return g(B.status,B.message,B.headers);let C=await n(s),k=await t.getAttachmentForUser(C,m,D);if(!k)return o.warn(`404 attachment=${m} viewer=${D} reason=not_visible`),g(404,"Attachment not found");if(k.fileSize!=null&&k.fileSize>A)return o.warn(`413 attachment=${m} viewer=${D} reason=db_size`),g(413,"Attachment too large");let M=kr(k.fileType),I=`filename="${Yn(k.fileName)}"; filename*=UTF-8''${Vn(k.fileName)}`,V=await l.acquire(D,s.signal);if(!V)return s.signal.aborted?(o.info(`503 attachment=${m} viewer=${D} reason=aborted`),g(503,"Attachment request aborted")):(o.warn(`503 attachment=${m} viewer=${D} reason=concurrency`),g(503,"Too many concurrent downloads",Ve(503)));let Q=!1;try{let H=await h(k.filePath,{maxBytes:A,head:s.method==="HEAD",principal:r(D),signal:s.signal});if(s.signal.aborted)return o.info(`503 attachment=${m} viewer=${D} reason=aborted`),g(503,"Attachment request aborted");if(!H.ok){if(!Wt(H.reason))return o.error(`500 attachment=${m} viewer=${D} reason=port_contract code=failure_reason`),g(500,$e);let oe=Kt(H.reason);return H.reason==="not_found"&&a(m,!1),o.warn(`${oe} attachment=${m} viewer=${D} reason=${H.reason} code=${H.code??"-"}`),g(oe,zt[oe],Ve(oe))}if(H.bytes.byteLength>A)return o.error(`500 attachment=${m} viewer=${D} reason=port_contract code=over_max_bytes`),g(500,$e);let se=s.method==="HEAD";if(se&&H.size!==void 0&&H.size>A)return o.error(`500 attachment=${m} viewer=${D} reason=port_contract code=over_max_bytes`),g(500,$e);if(!se&&H.size!==void 0&&H.size!==H.bytes.byteLength)return o.error(`500 attachment=${m} viewer=${D} reason=port_contract code=size_mismatch`),g(500,$e);let be=M??kr(H.contentType),ue=be!==null&&Fn.has(be),j=ue?be:"application/octet-stream",Z=ue&&f.kind!=="download"?"inline":"attachment",ne=se?H.size:H.bytes.byteLength,pe=new Headers({"Content-Type":j,"Content-Disposition":`${Z}; ${I}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...it});return ne!==void 0&&pe.set("Content-Length",String(ne)),b&&pe.append("Set-Cookie",b),a(m,!0),o.info(`200 attachment=${m} viewer=${D} type=${j} disposition=${Z} bytes=${ne??"-"}`),se?new Response(null,{status:200,headers:pe}):(Q=!0,new Response(Ds(H.bytes,V),{status:200,headers:pe}))}finally{Q||V()}}};var Ie=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Nu=Ie.queueWaitMs+Ie.readMs+Ie.renderMs+Ie.transferMarginMs;var Gn=require("buffer"),Qn=new Set([194,198,202,206]),Ts=new Set([192,193,194,195]),Xn=216,As=217,Zn=218,Is=4,Es=64,ws=2,Kn=8,Jn=28,We=12,$r=8,_s=20,eo=We+$r+10,xs=2,Ye=(e,t)=>e[t]<<8|e[t+1],st=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},Oe=(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},to=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,ro=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),no=e=>(e.stepsLeft-=1,e.stepsLeft>=0),oo=e=>e[0]===255&&e[1]===Xn,ao=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!no(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let o=e[n];if(n+=1,o===As)return"eoi";if(o===0||o===Xn)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=Ye(e,n),i=n+a;return a<2||i>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=i,"segment")}},Cs=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!no(r))return null;if(a+1>=n)return n;let i=e[a+1];if(i===255)a+=1;else if(i===0||i>=208&&i<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},io=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=Ye(e,r+1),a=Ye(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let p=0;p<i;p+=1){let s=e[r+7+3*p],f=s>>4,m=s&15;if(f<1||f>4||m<1||m>4)return null;l.push({id:e[r+6+3*p],horizontal:f,vertical:m})}return{marker:t,width:a,height:o,components:l}},so=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>Is||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},lo=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:Qn.has(e.marker)||t<e.components.length}),Fr=e=>{if(!oo(e))return null;let t=ro(e.byteLength),r=null;for(let n=2;;){if(ao(e,n,t)!=="segment")return null;if(to(t.marker)){if(r!==null||(r=io(e,t),r===null))return null}else if(t.marker===Zn){if(r===null)return null;let o=so(e,t);return o===null?null:lo(r,o.length)}n=t.end}},co=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:o})=>{let a=Math.ceil(e.width*n/(t*Kn)),i=Math.ceil(e.height*o/(r*Kn));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},uo=e=>e.multiScan?co(e).reduce((r,n)=>r+n,0)*Es*ws:0,Ps=896,mo=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!oo(e))return null;let n=Gn.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=ro(r),a=null,i=null,l=new Map,p=0,s=0,f=0;for(let m=2;;){let D=ao(e,m,o);if(D===null)return null;if(D==="eoi")return i===null?null:{header:i,blockVisits:s};if(m=o.end,to(o.marker)){if(a!==null||!Ts.has(o.marker)||(a=io(e,o),a===null))return null;let h=co(a);l=new Map;for(let[b,g]of a.components.entries()){let A=l.get(g.id);l.set(g.id,A===void 0?h[b]:Math.max(A,h[b]))}p=a.components.length*(Qn.has(a.marker)?Ps:1)}else if(o.marker===Zn){if(a===null||f===p)return null;let h=so(e,o);if(h===null)return null;for(let g of h){let A=l.get(g);if(A===void 0)return null;s+=A}if(f+=1,i===null&&(i=lo(a,h.length)),s>t||!i.multiScan)return{header:i,blockVisits:s};let b=Cs(n,o.end,o);if(b===null)return null;m=b}}},po=e=>{if(e.byteLength<24||Ye(e,8)!==0||Ye(e,10)!==13||!Oe(e,12,"IHDR"))return null;let t=Ye(e,16)*65536+Ye(e,18),r=Ye(e,20)*65536+Ye(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Ms=e=>{if(Oe(e,We,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=st(e,26,2)&16383,r=st(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Oe(e,We,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=st(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Oe(e,We,"VP8X")?e.byteLength<eo?null:{width:st(e,24,3)+1,height:st(e,27,3)+1}:null},yo=e=>{if(po(e)===null||e.byteLength<=Jn)return null;switch(e[Jn]){case 0:return!1;case 1:return!0;default:return null}},ho=(e,t)=>{if(Oe(e,We,"VP8 "))return"lossy";if(Oe(e,We,"VP8L"))return"lossless";if(!Oe(e,We,"VP8X")||e.byteLength<eo)return null;if((e[_s]&xs)!==0)return"animated";let r=!1,n=t;for(let o=We;o+$r<=e.byteLength;){if(n-=1,n<0)return null;if(Oe(e,o,"VP8L"))return"lossless";if(Oe(e,o,"VP8 "))return r?"lossy-alpha":"lossy";Oe(e,o,"ALPH")&&(r=!0);let a=st(e,o+4,4);o+=$r+a+a%2}return null},fo={png:po,jpeg:Fr,webp:Ms};var Gt=Object.freeze(["image/webp","image/jpeg","image/png"]),Qt=1024*1024;var Ls=new Set(["image/png","image/jpeg","image/gif","image/webp"]),vs={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Ns=new Set(Gt),Os=e=>typeof e=="string"&&Ns.has(e),ks=256,Xt=(e,t)=>e.fileType===null||!Ls.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Us=[137,80,78,71,13,10,26,10],Bs=[255,216,255],Hs=[[71,73,70,56,55,97],[71,73,70,56,57,97]],$s=[82,73,70,70],Fs=[87,69,66,80],At=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,o]of t.entries())if(e[r+n]!==o)return!1;return!0},Vr=e=>{if(At(e,Us,0))return"png";if(At(e,Bs,0))return"jpeg";for(let t of Hs)if(At(e,t,0))return"gif";return At(e,$s,0)&&At(e,Fs,8)?"webp":null},Ro=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:Jt([t])}},go=(e,t)=>{if(!Os(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Qt)return"too_large";let r=vs[e.contentType];if(Vr(e.bytes)!==r)return"signature";let n=fo[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},bo=e=>{de("maxBytes",e.maxBytes,0),de("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+ks;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let p of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(p)}}}};var Yr=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ce(),l=new AbortController,p=!1,s,f,m=()=>{a(ce()-i)},D=M=>{s=Le(()=>{p=!0,M({timedOut:!0}),f=Le(m,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},h=new Promise(D),b=AbortSignal.any([r,l.signal]),g=M=>{M(n(b))},A=new Promise(g),B=M=>(clearTimeout(s),clearTimeout(f),p&&o(ce()-i,M.kind==="error"?{error:M.error}:null),M),C=A.then(M=>B({kind:"value",value:M}),M=>B({kind:"error",error:M}));return{outcome:Promise.race([A.then(M=>({timedOut:!1,value:M})),h]),settled:C}};var Ke={404:"Attachment not found",500:$e,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},So=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=go(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Vs=e=>{let t=new AbortController,r=()=>{t.abort()},n=Le(r,Ie.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Do=()=>{},Ys=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),To=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,p=(h,b)=>{let g=b.then(Do,Do);l.set(h,g);let A=()=>{l.get(h)===g&&l.delete(h)};g.then(A)},s=async(h,b)=>{let g=l.get(h.key);if(g===void 0)return t.acquire(h.owner,b);let A=Vs(b);try{if(await Ys(g,A.signal),A.signal.aborted)return null;let B=r.get(h.key);return B!==void 0?{...B,identity:"verified"}:await t.acquire(h.owner,A.signal)}finally{A.end()}},f=(h,b)=>{if(h.fileSize===null)return b.kind==="exact"?"verified":"unrecorded";if(b.kind==="exact"?b.bytes===h.fileSize:h.fileSize>b.maxBytes)return"verified";let A=b.kind==="exact"?String(b.bytes):`>${b.maxBytes}`;return i.warn(`size_mismatch expected=${h.fileSize} got=${A} attachment=${h.attachmentId} viewer=${h.owner} variant=thumbnail`),"unverified"},m=(h,b)=>(g,A)=>{let B=A===null?"":` message=${A.error instanceof Error?A.error.message:"unknown"}`;i.warn(`${h}_overrun ms=${g} attachment=${b.attachmentId} viewer=${b.owner} variant=thumbnail${B}`)},D=(h,b)=>g=>{i.warn(`${h}_stuck ms=${g} attachment=${b.attachmentId} viewer=${b.owner} variant=thumbnail`)};return async(h,b)=>{let g=await s(h,b);if(g===null)return{kind:"failure",status:503,reason:b.aborted?"aborted":"queue"};if(typeof g!="function")return g;let A=g,B=null;try{if(b.aborted)return{kind:"failure",status:503,reason:"aborted"};let C=r.get(h.key);if(C!==void 0)return{...C,identity:"verified"};let k=Yr({budgetMs:Ie.readMs,flightSignal:b,call:oe=>h.readAttachment(h.filePath,{maxBytes:n,head:!1,principal:o(h.owner),signal:oe}),onOverrun:m("read",h),onStuck:D("read",h)}),M=await k.outcome;if(M.timedOut)return B=k.settled,b.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(b.aborted)return{kind:"failure",status:503,reason:"aborted"};let I=M.value;if(!I.ok&&I.reason!=="too_large")return Wt(I.reason)?(I.reason==="not_found"&&a(h.attachmentId,!1),{kind:"failure",status:Kt(I.reason),reason:I.reason,code:I.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(I.ok&&I.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let V=f(h,I.ok?{kind:"exact",bytes:I.bytes.byteLength}:{kind:"over",maxBytes:n}),Q=oe=>{V==="verified"&&r.set(h.key,oe)},H=oe=>(Q(oe),{...oe,identity:V});if(!I.ok)return H({kind:"unrenderable",reason:"too_large"});let se=Vr(I.bytes);if(se===null)return H({kind:"unrenderable",reason:"signature"});let be=Yr({budgetMs:Ie.renderMs,flightSignal:b,call:oe=>h.renderer.render(I.bytes,{format:se,maxWidth:h.box.maxWidth,maxHeight:h.box.maxHeight,signal:oe}),onOverrun:m("render",h),onStuck:D("render",h)}),ue=oe=>{if(oe.kind==="error")return;let ye=So(oe.value,h.box);"entry"in ye&&Q(ye.entry)},j=null,Z=()=>(j===null&&(j=be.settled.then(ue),p(h.key,j)),j);b.addEventListener("abort",Z,{once:!0});let ne=await be.outcome.finally(()=>b.removeEventListener("abort",Z));if(ne.timedOut||b.aborted)return B=Z(),b.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let pe=So(ne.value,h.box);return"entry"in pe?H(pe.entry):pe.failure}finally{B===null?A():B.then(A,A)}}};var Ao=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let p=new AbortController,s=()=>{e.get(t)?.controller===p&&e.delete(t)},m={promise:n(p.signal).finally(s),controller:p,waiters:0};return e.set(t,m),m},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var wo=10,qs=1/wo,Io=1-qs,js=1024,zs=64,Ws=8,Eo="private, no-cache",Ks="no-store",Js=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Gs=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},_o=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:p}=l,s=(M,I)=>Fe({reason:M,limitPerWindow:I,windowMs:6e4,logger:o,windowFields:V=>`viewer=${V} variant=thumbnail`}),f=s("rate_limit",l.rateLimitPerMinute),m=s("revalidation_rate_limit",l.rateLimitPerMinute*wo),D=ze({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:zs,maxPerOwner:Ws,maxWaitMs:Ie.queueWaitMs}}),h=bo({maxBytes:l.cacheBytes,maxEntries:js}),b=Ao(),g=To({gate:D,cache:h,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),A=(M,I,V,Q)=>{let H=`attachment=${M.attachmentId} viewer=${M.internalUserId} variant=thumbnail cache=${Q}`;if(I.kind==="failure")return o[Gs(I)](`${I.status} ${H} reason=${I.reason} code=${I.code??"-"}`),M.fail(I.status,Ke[I.status],Ve(I.status));let se=Js[I.identity];if(I.kind==="unrenderable")return o.info(`404 ${H} reason=${I.reason}${se}`),M.fail(404,Ke[404]);let be=I.identity==="verified"?{"Cache-Control":Eo,ETag:V}:{"Cache-Control":Ks},ue=new Headers({"Content-Type":I.contentType,"Content-Length":String(I.bytes.byteLength),...be,"Content-Security-Policy":"default-src 'none'; sandbox",...it});return M.cookie&&ue.append("Set-Cookie",M.cookie),o.info(`200 ${H} type=${I.contentType} bytes=${I.bytes.byteLength}${se}`),new Response(I.bytes,{status:200,headers:ue})},B=(M,I)=>{let V=M.spend(I.internalUserId,`attachment=${I.attachmentId} viewer=${I.internalUserId} variant=thumbnail`);return V===null?null:I.fail(V.status,V.message,V.headers)},C=M=>B(f,M),k=(M,I)=>I?B(m,M):C(M);return async(M,I)=>{let{request:V,attachmentId:Q,internalUserId:H,readAttachment:se,cookie:be,fail:ue}=M,j=Lr[I],Z=V.headers.get("If-None-Match"),ne=Z!==null,pe=k(M,ne);if(pe)return pe;let oe=await n(V),ye=await t.getAttachmentForUser(oe,Q,H),x=ye!==null&&Xt(ye,i)?Ro({rendererId:p.id,box:j,attachmentId:Q,filePath:ye.filePath,fileType:ye.fileType,fileSize:ye.fileSize}):null;if(x&&Hr(Z,x.etag)){let F=new Headers({"Cache-Control":Eo,ETag:x.etag,...it});return be&&F.append("Set-Cookie",be),o.info(`304 attachment=${Q} viewer=${H} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:F})}if(ne){let F=C(M);if(F)return F}if(!ye)return o.warn(`404 attachment=${Q} viewer=${H} variant=thumbnail reason=not_visible`),ue(404,Ke[404]);if(!x)return f.refund(H,Io),o.info(`404 attachment=${Q} viewer=${H} variant=thumbnail reason=not_eligible`),ue(404,Ke[404]);let{key:v,etag:N}=x,$=h.get(v);if($)return f.refund(H,Io),A(M,{...$,identity:"verified"},N,"hit");let Y=F=>g({key:v,attachmentId:Q,filePath:ye.filePath,fileSize:ye.fileSize,box:j,owner:H,readAttachment:se,renderer:p},F),G;try{G=await b.join(v,V.signal,Y)}catch(F){return o.error(`500 attachment=${Q} viewer=${H} variant=thumbnail cache=miss reason=port_exception message=${F instanceof Error?F.message:"unknown"}`),ue(500,Ke[500])}return A(M,G,N,"miss")}};var Qs='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Xs=()=>jt(403,Or,{cookie:null}),xo=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=vr(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>jt(404,zt[404],{cookie:null}),crossSiteRejection:Xs}),Co=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,i=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:$n(r,a)},p=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Wn({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:_o({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:s,params:f})=>{let m=null,D=(h,b,g={})=>jt(h,b,{cookie:m,extraHeaders:g});try{let{user:h,cookie:b}=await t(s,{failureRedirect:null});if(m=b??null,!h)return D(401,"Unauthorized");let g=vr(new URL(s.url).searchParams);if(g.kind==="invalid")return D(400,"Invalid attachment request");if(g.kind==="thumbnail"&&s.method!=="GET")return D(405,"Method not allowed",{Allow:"GET"});if(s.method!=="GET"&&s.method!=="HEAD")return D(405,"Method not allowed",{Allow:"GET, HEAD"});if(p===null)return D(404,"Attachment not found");if(f.token===void 0)throw new Error(Qs);let A=p.idCodec.decode(f.token);if(A===null||!at(A))return D(400,"Invalid attachment token");let B=await r.getUserIdByExternalId(h.id);if(!B)return D(403,"Forbidden");let C={request:s,delivery:g,attachmentId:A,internalUserId:B,readAttachment:p.read,cookie:m,fail:D};return g.kind!=="thumbnail"?await p.serveOriginal(C):p.serveThumbnail===null?D(404,Ke[404]):await p.serveThumbnail(C,g.variant)}catch(h){if(h instanceof Response)throw h;return a.error(`500 attachment=? viewer=? reason=unexpected message=${h instanceof Error?h.message:"unknown"}`),D(500,$e)}}};var Zs=32*1024*1024,el=60,tl=4,rl=120,nl=2,ol=8*1024*1024,Zt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),al=e=>{if(e===void 0)throw ot("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Zt(e))throw ie("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw ot("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw ie("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw ie("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},il=e=>{if(e===void 0)return null;if(!Zt(e))throw ie("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:al(e.renderer),rateLimitPerMinute:Qe("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,rl),concurrency:Qe("attachments.thumbnails.concurrency",e.concurrency,1,nl),cacheBytes:Qe("attachments.thumbnails.cacheBytes",e.cacheBytes,0,ol)})},Po=e=>{let t=e;if(t===void 0)return null;if(!Zt(t))throw ie("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw ot("attachments.idCodec","injected when attachments is given");if(!Zt(r)||typeof r.encode!="function"||typeof r.decode!="function")throw ie("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw ot("attachments.read","injected when attachments is given");if(typeof n!="function")throw ie("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Qe("attachments.maxBytes",t.maxBytes,1,Zs),rateLimitPerMinute:Qe("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,el),concurrency:Qe("attachments.concurrency",t.concurrency,1,tl),thumbnails:il(t.thumbnails)})},sl=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),er=e=>{for(let[t,r]of sl)if(Object.hasOwn(e,t))throw ot(r,`given in place of the flat key ${t}`)};var ll=/^[0-9a-f]{1,16}$/;var Mo=e=>{let t=e.get(Ae.cursorReportHubId),r=e.get(Ae.cursorBusinessDate),n=e.get(Ae.cursorSnapshot),o=n!==null&&ll.test(n)?n:null,a=null;if(t!==null){let l=Me(t);if(l===null)return{refused:"cursor"};if(r!==null&&!Ht(r))return{refused:"cursor"};a={businessDate:r,reportHubId:l}}else if(r!==null)return{refused:"cursor"};let i=St(e.get(Ae.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var tr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,cl=2,ul=16,dl=cl*ul,ml=6e4,Lo=()=>{},pl=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},vo=e=>{let t=ze({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:dl,queue:null}),r=Ne({windowMs:ml,tallies:["sse","ids-stream"],writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`streams_per_viewer_suppressed count=${o} since=${a} viewer=${n} routes=sse:${i.sse},ids-stream:${i["ids-stream"]}`)}});return{admit:async(n,o,a)=>{if(n===null)return Lo;if(a.aborted){if(t.canAcquire(n))return Lo}else{let i=await t.acquire(n,a);if(i!==null)return pl(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var rr=30,Bo=4e3,yl="stream interrupted by server error",hl="Too many streams",fl=15e3,Ho=Symbol("ids-stream-heartbeat"),No=()=>{},Oo=e=>e.return(void 0).then(No,No),Rl=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Ho),fl)}),stop:()=>clearTimeout(e)}};async function*ko(e,t,r,n){let o=t?mn(e,t):0,a=!0;for(;;){let i=e.slice(o,o+(a?r:Bo));o+=i.length;let l=o>=e.length,p=i[i.length-1];if(yield{kind:"chunk",items:i,nextCursor:l||!p?null:{businessDate:p.businessDate,reportHubId:p.reportHubId},isLast:l,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,l)return}}var $o=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform","X-Content-Type-Options":"nosniff"});return e&&t.append("Set-Cookie",e),t},Uo=(e,t,r,n,o)=>{let a=async(f,m)=>{o(),m&&await Oo(t);try{f.close()}catch{}},i=new TextEncoder,l=!1,p=null,s=new ReadableStream({async pull(f){if(l||r.aborted){await a(f,!0);return}let m=Rl();try{p===null&&(p=t.next());let D=await Promise.race([p,m.fired]);if(m.stop(),D===Ho){if(l||r.aborted){await a(f,!0);return}f.enqueue(i.encode(`
2
- `));return}p=null;let{value:h,done:b}=D;if(b){await a(f,!1);return}if(l||r.aborted){await a(f,!0);return}f.enqueue(i.encode(`${JSON.stringify(h)}
3
- `))}catch(D){if(m.stop(),p=null,o(),l||r.aborted)return;n.error(`ids-stream emission failed: ${D instanceof Error?D.message:String(D)}`);try{let h={kind:"error",error:yl};f.enqueue(i.encode(`${JSON.stringify(h)}
4
- `)),f.close()}catch{}}},cancel(){l=!0,o(),Oo(t)}});return new Response(s,{status:200,headers:$o(e)})},Fo=e=>{let{service:t,logger:r,streamSlots:n,refuseForcedRead:o}=e,a=async(i,l,p,s,f,m)=>{let D=!1,h=null,b=null,g=new Promise((C,k)=>{h=C,b=k});g.catch(()=>{});let A=t.getDailyReportIdsByExternalId(p,l.id,{forceRefresh:i.forceRefresh,onFetchStart:i.cursor?void 0:()=>{D=!0,t.readSseStreamAnchor().then(C=>t.getDailyReportIdsFirstPageByExternalId(p,l.id,rr).then(k=>({items:k,streamAnchor:C}))).then(C=>h?.(C),C=>b?.(C))}});if(A.catch(()=>{}),i.cursor){let{items:C,streamAnchor:k,snapshot:M}=await A,I=i.snapshot!==null&&i.snapshot===M;return Uo(s,ko(C,I?i.cursor:null,rr,{snapshot:M,restarted:!I,streamAnchor:k}),f,r,m)}let B=(async function*(){let C=await Promise.race([A.then(I=>({kind:"full",source:I}),I=>({kind:"full-error",error:I})),g.then(I=>({kind:"page",page:I}),()=>({kind:"page-error"}))]),k=null,M=!1;if(C.kind==="full")k=C.source;else if(C.kind==="page"){let{items:I,streamAnchor:V}=C.page;if(I.length<rr){yield{kind:"chunk",items:I,nextCursor:null,isLast:!0,total:I.length,streamAnchor:V};return}yield{kind:"chunk",items:I,nextCursor:null,isLast:!1,provisional:!0},M=!0}else if(C.kind==="full-error"&&D){let I=await g.catch(()=>null);I&&I.items.length>0&&(yield{kind:"chunk",items:I.items,nextCursor:null,isLast:!1,provisional:!0})}k===null&&(k=await A),yield*ko(k.items,null,M?Bo:rr,{snapshot:k.snapshot,streamAnchor:k.streamAnchor})})();return Uo(s,B,f,r,m)};return async(i,l,p,s,f)=>{let m=Mo(i.searchParams);if("refused"in m)return ae(p,l,{error:{message:m.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:D}=m;if(D.forceRefresh){let g=o(s,p,l);if(g!==null)return g}let h=tr(p),b=await n.admit(await t.getUserIdByExternalId(s.id),"ids-stream",h);if(b===null){let g=ae(p,l,{error:{message:hl}},503);for(let[A,B]of Object.entries(Ve(503)))g.headers.set(A,B);return g}if(h.aborted)return new Response(null,{status:200,headers:$o(l)});try{return await a(D,s,f,l,h,b)}catch(g){throw b(),g}}};var Vo=6e4,gl=1,qr=e=>{let{concurrency:t,route:r,logger:n}=e,o=Fe({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:Vo,logger:n,windowFields:()=>`route=${r}`}),a=ze({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:null}),i=Object.freeze({status:429,message:Ur,headers:Object.freeze({"Retry-After":String(gl)})}),l=Ne({windowMs:Vo,tallies:["busy"],writeSuppressed:(p,{count:s,since:f})=>{n.warn(`busy_suppressed count=${s} since=${f} route=${r} concurrency=${t}`)}});return{admit:async(p,s)=>{let f=o.spend(p,r);if(f!==null)return{refusal:f};let m=await a.acquire(p,s);return m!==null?{release:m}:(o.refund(p,1),l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};var Ko=require("@aiquants/fuzzy-search");var Yo=require("crypto"),Et=require("@aiquants/fuzzy-search/normalize"),nr=`
5
- `,bl=4e3,Sl=1,Dl=new RegExp(`[${String.fromCodePoint(8203,8288,65279,173)}]`,"gu"),Tl=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"u"),Al=/(\s+)/u,Il=/^\s+$/u,El=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,wl=new Set([8205,1536,1537,1538,1539,1540,1541,1757,1807,2192,2193,2274,69821,69837,70082,70083,71999,72001,72250,72324,72325,72326,72327,72328,72329,73030,73474]),or=e=>e.replace(Dl,""),It=e=>(0,Et.normalizeText)(e,Et.DEFAULT_NORMALIZE_OPTIONS),qo=e=>It(or(e)),jo=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},_l=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&jo(e,t-1)?t-2:t-1;return El.test(String.fromCodePoint(r))&&!wl.has(e.codePointAt(n))},xl=(e,t)=>{let r=[],n=0,o=0;for(;e.length-o>t;){let a=o+t;for(;a>o&&!_l(e,a);)a--;a===o&&(a=o+t,jo(e,a)&&a--,n++),r.push(e.slice(o,a)),o=a}return r.push(e.slice(o)),{pieces:r,forcedCuts:n}},Cl=(e,t)=>{if(e.length<=t)return{text:It(e),forcedCuts:0};let r=[],n=0,o="",a=()=>{r.push(It(o)),o=""};for(let i of e.split(Al)){if(o.length+i.length<=t){o+=i;continue}if(a(),Il.test(i))continue;if(i.length<=t){o=i;continue}let l=xl(i,t);n+=l.forcedCuts,r.push(l.pieces.map(It).join(""))}return a(),{text:r.filter(i=>i.length>0).join(" "),forcedCuts:n}},ar=(e,t=bl)=>{let r=[],n=0;for(let o of or(e).split(Tl)){let a=Cl(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}return{text:r.join(nr),forcedCuts:n}},zo=e=>e.filter(t=>t.length>0).join(nr),Pl=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
6
- `)},Ml=[`\u3067\u3093${String.fromCodePoint(8203)}\u3077\u3093 \uFF83\uFF9E\uFF9D\uFF8C\uFF9F\uFF9D\r
7
- \u30C7\u30F3\u30D7\u30F3`,"\u30DD\u30C6\u30C8-25kg \u30A2--1 \u30FC\u30FC\u30E1\u30F3 \u4F50\u3005\u6728","\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CA",`\uFF71\uFF72\uFF73\uFF74\uFF75\uFF76\uFF9E\uFF77\uFF9E\uFF78\uFF9E\uFF79\uFF9E\uFF7A\uFF9E${String.fromCodePoint(8232)}\u6B21\u306E\u884C`],Ll=()=>{let e=(0,Yo.createHash)("sha256");e.update(JSON.stringify(Et.DEFAULT_NORMALIZE_OPTIONS));for(let t of["","\u30A2","\u4F50"," "])e.update("\0"),e.update(It(Pl(t)));return e.update("\0"),e.update(JSON.stringify(Ml.map(t=>ar(t,8)))),`dr-search-v${Sl};fz=${e.digest("hex").slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`},jr=null,Wo=()=>(jr===null&&(jr=Ll()),jr);var vl=/^-+/u,Nl=/\s+/u,Ol=e=>{let t=vl.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Jo=(e,t)=>{if(e.length>Pe.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of(0,Ko.parseQuerySets)(or(e),t).sets){let i=[],l=new Set;for(let s of a.split(Nl)){let f=qo(s);if(f.length===0)return{ok:!1,reason:"blank-word"};if(f.length>Pe.maxWordLength)return{ok:!1,reason:"word-too-long"};l.has(f)||(l.add(f),i.push({alternatives:Ol(f)}))}if(i.length>Pe.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let p=[...l].sort().join("\0");n.has(p)||(n.add(p),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>Pe.maxSets?{ok:!1,reason:"too-many-sets"}:o>Pe.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}};var ca=require("@aiquants/sse"),Je=require("@aiquants/sse/server");var lt=(e,t)=>{let r=e.message.data;if(!r)return{entry:{id:e.id,message:null},json:void 0};let n;try{n=JSON.parse(r)}catch(i){return t.error(`SSE message ${e.id} is not JSON:`,i),{entry:{id:e.id,message:null},json:void 0}}let o=Dn.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n,text:r});return{entry:Object.freeze({id:e.id,message:a}),json:n}},kl=["externalComments","postedComments"],Go=new WeakMap,Ul=e=>{let t=Go.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return Go.set(e,r),r},Qo=e=>{let{recipientRawUserId:t,...r}=e;return r},Xo=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=Ul(e);if(t){if(n.commentsRedacted===null){let o=Qo(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(kl.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(Qo(r))),n.recipientRemoved};var na=require("@aiquants/sse"),oa=require("@aiquants/sse/shared-source");var Ze="daily-report:ids:",et="daily-report:business-date:",ir=(e,t)=>`${e}st:${t}`,zr=e=>`${Ze}user:${e}:`,Zo=(e,t)=>ir(zr(e),t),Bl=e=>`${et}${e}:`,ea=(e,t)=>ir(Bl(e),t),wt=e=>`daily-report:date:${e}:user:`,ct=(e,t)=>`${wt(e)}${t}:`,ta=(e,t,r)=>ir(ct(e,t),r),ke=e=>`daily-report:detail:${e}:user:`,sr=(e,t)=>`${ke(e)}${t}:`,ra=(e,t,r)=>ir(sr(e,t),r);var qe=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},Hl=5e3,$l=Vt,ut=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=he(t.logger,1,"[DailyReportSseReader]"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return(0,oa.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:na.systemSseRuntime,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",i=>{this._logger.error("Redis client error:",i)});let o=!1,a=this._readLoop(n,t,r,()=>o);return async()=>{if(o=!0,n.isOpen)try{await n.quit()}catch{}await a}}async _readLoop(t,r,n,o){let a=n;try{for(;!o()&&t.isOpen;){let i=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:Hl,COUNT:$l});if(i)for(let l of i)for(let p of l.messages){a=p.id;let{entry:s,json:f}=lt(p,this._logger);this._invalidateCaches(f),r.next(s)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(Ze),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(ke(n))}};var xt=require("drizzle-orm");var Fl="",Vl=64,Yl=e=>e.toLowerCase(),ql=e=>e.trim().toLowerCase();function aa(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=ql(r);n.length>0&&t.add(n)}return t}function xe(e,t){return e===null?!0:t==null?!1:e.has(Yl(t))}function Ue(e){return e!==null&&e.size===0}function Ct(e,t){if(t!==null)return t.size===0?xt.sql`1 = 0`:(0,xt.inArray)(xt.sql`LOWER(${e})`,[...t])}var dt,mt,_t=class _t{constructor(t,r){Rr(this,dt);Rr(this,mt);gr(this,dt,t),gr(this,mt,r)}get visible(){return gt(this,dt)===null?null:new Set(gt(this,dt))}get commentable(){return gt(this,mt)===null?null:new Set(gt(this,mt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=aa(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new _t(n,n);let a=aa(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new _t(n,i)}static unrestricted(t){return new _t(null,null)}};dt=new WeakMap,mt=new WeakMap;var Ee=_t;function Pt(e){let t=ia(e.visible),r=ia(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function ia(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Fl);if(t.length<=Vl)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 ua=Object.freeze({...Tt,route:"sse",frameworkDataRefusal:qt}),sa=864e5,jl={baseMs:2e3,jitterMs:8e3},Wr=6e4,cr=Vt,da=JSON.stringify({type:"connected"}),la="0-0",zl=(e,t,r,n)=>{if(r===null&&n===null)return!0;let o=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return xe(r,e.report.sourceType);case"comment-add":case"comment-delete":return xe(n,o??"Internal");case"report-delete":return xe(r,o)}},Wl=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!xe(t,e.report.sourceType),Kl=(e,t)=>{e.writeEvent({event:null,id:t,data:da})},Jl=(e,t,r)=>{let{message:n}=t;if(n===null)return;let{parsed:o,published:a}=n,i=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((o.type==="status-update"||i!==void 0)&&i!==r.internalUserId||!zl(o,a,r.visibleSet,r.commentableSet)){Kl(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Xo(n,Wl(o,r.commentableSet))})},ma=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:p}=e,s=async(f,m)=>{let{request:D,internalUserId:h,cursor:b}=m,g=m.initialScope.visible,A=m.initialScope.commentable,B=0,C=setInterval(()=>{let j=++B;n(D,"refresh").then(Z=>{j===B&&(g=Z.visible,A=Z.commentable)})},Wr);f.onClose(()=>clearInterval(C));let k=b===null?la:b,M=b!==null&&o!==void 0,I=[],V=null,Q=j=>{qe(j.id,k)||(k=j.id,Jl(f,j,{internalUserId:h,visibleSet:g,commentableSet:A}))},H=async(j,Z)=>{let[ne]=await j.xRange(i,"-","+",{COUNT:1});return ne!==void 0&&!qe(ne.id,Z)},se=async(j,Z)=>{if(await H(j,Z))return!1;let ne=Z;for(;;){let pe=await j.xRange(i,ne,"+",{COUNT:cr}),oe=pe[0];if(oe!==void 0&&oe.id!==ne&&await H(j,ne))return!1;for(let ee of pe){if(V!==null&&qe(V,ee.id))return!0;qe(ee.id,k)||Q(lt(ee,p).entry)}let ye=pe.at(-1);if(pe.length<cr||ye===void 0||f.isClosed())return!0;ne=ye.id}},be=a.subscribe(j=>{if(!M){Q(j);return}qe(j.id,k)||(V===null&&(V=j.id),I.push(j))},j=>{p.error(`[SSE:${h}] Fan-Out reader error:`,j),f.close()});if(f.onClose(be),b===null){await a.ready();try{let j=await o?.getClient();if(j){let Z=await j.xRevRange(i,"+","-",{COUNT:1});Z.length>0&&!qe(Z[0].id,k)&&(k=Z[0].id)}}catch{}}if(f.writeEvent({event:null,id:k===la?null:k,data:da}),(0,Je.startSseHeartbeat)(f,{intervalMs:Rn,retry:jl,runtime:ca.systemSseRuntime}),b===null||o===void 0)return;await a.ready();let ue=await o.getClient();if(ue===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await se(ue,b)){f.writeRetry(sa),f.writeEvent({event:"resync-required",id:null,data:""}),f.close();return}M=!1;for(let j of I.splice(0))Q(j)};return async({request:f,params:m})=>{let D,h=()=>{let g=new Headers;return D!==void 0&&g.append("Set-Cookie",D),g},b=g=>(0,Je.terminalStreamResponse)(g,{data:"",retryMs:sa,headers:h()});try{let g=await t(f,{failureRedirect:null});D=g.cookie;let{user:A}=g;if(!A)return b("auth-required");let B=await r.getUserIdByExternalId(A.id);if(!B)return b("forbidden");if(m.endpoint!=="updates")return new Response("Not Found",{status:404,headers:h()});let C=(0,Je.readLastEventId)(f,gn);if(C!==null&&!bn(C))return p.warn(`[SSE:${B}] malformed resume cursor; asking the client to resync`),b("resync-required");let k=tr(f),M=await l.admit(B,"sse",k);if(M===null){let V=h();for(let[Q,H]of Object.entries(Ve(503)))V.set(Q,H);return new Response("Too many streams",{status:503,headers:V})}let I=!1;try{let V=await n(f,"initial");return(0,Je.createSseResponse)({requestSignal:k,headers:h(),onError:(Q,H)=>p.error(`[SSE:${B}] ${H} failed:`,Q),produce:Q=>(I=!0,Q.onClose(M),s(Q,{request:f,internalUserId:B,cursor:C,initialScope:V}))})}finally{I||M()}}catch(g){if(g instanceof Response)throw g;let A=g instanceof Error?g:new Error(String(g));return p.error(`500 sse name=${A.name} message=${A.message}`),new Response("Internal Server Error",{status:500,headers:h()})}}};var pa=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json"});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Gl=Object.freeze({...Tt,route:"api",frameworkDataRefusal:({params:e})=>Mr(e.endpoint)&&Dt[e.endpoint].body==="stream"?qt():null}),Ql=Object.freeze({...Tt,route:"action"}),Xl=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),ya=6e4,ha=5,Zl=ha*Math.ceil(ya/500),ec=2,tc=6,rc=6e4,nc=ha*ec*tc,oc=2,ac=10,Kr=(e,t,r)=>{let n=ae(e,t,{error:{message:r.message}},r.status);for(let[o,a]of Object.entries(r.headers))n.headers.set(o,a);return n};function ur(e){er(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:de("service.titleMaxLength",r.titleMaxLength,1)},p=e.loginRedirectPath??"/auth/login",s=he(e.logger,3,"[DailyReportAPI]"),f=he(e.logger,3,"[DailyReportVisibility]"),m=he(e.logger,1,"[DailyReportSSE]"),D=he(e.logger,1,"[DailyReportAttachment]"),h=he(e.logger,2,"[DailyReportIsolation]"),b=he(e.logger,2,"[DailyReportAction]"),g=he(e.logger,2,"[DailyReportSearch]"),A=he(e.logger,2,"[DailyReportRefresh]"),B=he(e.logger,2,"[DailyReportStreams]"),C=Fe({reason:"refresh_rate_limit",limitPerWindow:nc,windowMs:rc,logger:A,windowFields:()=>"route=api"}),k=vo(B),M=(x,v,N,$)=>{let Y=C.spend(v.id,`endpoint=${x}`);return Y===null?null:Kr(N,$,Y)},I=async(x,v="initial")=>{let N=e.resolveVisibleSourceTypes;if(!N)return Ee.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let $=await N(x,{reason:v});return $==null?Ee.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):Ee.restrictTo($)}catch($){return f.error("resolveVisibleSourceTypes threw; failing closed (deny all)",$),Ee.restrictTo([])}},V=async({request:x})=>{let{user:v,cookie:N}=await t(x,{failureRedirect:p}),$=new Headers;N&&$.append("Set-Cookie",N);let Y=await r.getUserIdByExternalId(v.id),G=Y?n(Y):null;return{data:{user:v,userId:G},headers:$}},Q=r.searchLimits===null?null:qr({...r.searchLimits,route:Re.search,logger:g}),H=r.searchLimits===null?null:qr({concurrency:r.searchLimits.concurrency*oc,rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*ac,route:Re.reports,logger:g}),se={[Re.businessDate]:async(x,v,N,$,Y)=>{let G=x.searchParams.get(Ae.businessDate),F=G===null?null:nt(G);if(F===null)return ae(N,v,{error:{message:"Invalid business date"}},400);let z=St(x.searchParams.get(Ae.forceRefresh));if(z===null)return ae(N,v,{error:{message:"Invalid forceRefresh"}},400);let X=z?M(Re.businessDate,$,N,v):null;if(X!==null)return X;let L=await r.getDailyReportsByBusinessDateByExternalId(Y,F,$.id,{forceRefresh:z});return ae(N,v,{businessDate:F,reports:L},200)},[Re.idsStream]:Fo({service:r,logger:s,streamSlots:k,refuseForcedRead:(x,v,N)=>M(Re.idsStream,x,v,N)}),[Re.report]:async(x,v,N,$,Y)=>{let G=Me(x.searchParams.get(Ae.reportHubId));if(G===null)return ae(N,v,{error:{message:"Invalid reportHubId"}},400);let F=St(x.searchParams.get(Ae.forceRefresh));if(F===null)return ae(N,v,{error:{message:"Invalid forceRefresh"}},400);let z=F?M(Re.report,$,N,v):null;if(z!==null)return z;let X=await r.getDailyReportDetailByIdByExternalId(Y,G,$.id,{snapshot:!0,forceRefresh:F});return X?ae(N,v,{report:X},200):ae(N,v,{error:{message:"Report not found"}},404)},[Re.search]:async(x,v,N,$,Y)=>{if(Q===null)return ae(N,v,{error:{message:"Unknown endpoint"}},404);let G=x.searchParams.get(Ae.searchQuery),F=Tn(x.searchParams.get(Ae.searchCombine));if(G===null||F===null)return ae(N,v,{error:{message:"Invalid search request"}},400);let z=Jo(G,F);if(!z.ok)return ae(N,v,{error:{message:"Invalid search query",reason:z.reason}},400);let X=await r.getUserIdByExternalId($.id);if(!X)return ae(N,v,Sr([]),200);let L=await Q.admit(X,N.signal);if("refusal"in L)return Kr(N,v,L.refusal);try{let fe=await r.searchDailyReports(Y,X,z.plan);return ae(N,v,Sr(fe),200)}finally{L.release()}},[Re.reports]:async(x,v,N,$,Y)=>{if(H===null)return ae(N,v,{error:{message:"Unknown endpoint"}},404);let G=An(x.searchParams.get(Ae.reportIds));if(G===null)return ae(N,v,{error:{message:"Invalid ids"}},400);let F=await r.getUserIdByExternalId($.id);if(!F)return ae(N,v,{reports:[]},200);let z=await H.admit(F,N.signal);if("refusal"in z)return Kr(N,v,z.refusal);try{let X=await r.getDailyReportDetailsByIdsByExternalId(Y,G,$.id);return ae(N,v,{reports:X},200)}finally{z.release()}}},be=async({request:x,params:v})=>{let{user:N,cookie:$}=await t(x,{failureRedirect:null}),Y=$??null;if(!N)return ae(x,Y,{error:{message:"Unauthorized"}},401);let G=v.endpoint;if(!Mr(G))return ae(x,Y,{error:{message:"Unknown endpoint"}},404);let F=vn[Dt[G].body];if(!F.includes(x.method)){let X=ae(x,Y,{error:{message:"Method not allowed"}},405);return X.headers.set("Allow",F.join(", ")),X}let z=ce();try{let X=new URL(x.url),L=await I(x),fe=await se[G](X,Y,x,N,L);return Dt[G].body==="json"&&s.debug(`${fe.status} endpoint=${G} etag_match=${fe.status===304}`),fe}catch(X){let L=ce()-z,fe=X instanceof Error?X:new Error(String(X));return s.error(`500 endpoint=${G} elapsed=${L}ms name=${fe.name} code=${"code"in fe?fe.code:"N/A"} message=${fe.message}`,fe),ae(x,Y,{error:{message:"Internal Server Error"}},500)}},ue=Ln(b),j=Fe({reason:"rate_limit",limitPerWindow:Zl,windowMs:ya,logger:b,windowFields:()=>"route=action"}),Z=async(x,v,N,$,Y)=>{let{clientTempId:G}=x;if(x.intent==="create"){let L=await r.createDailyReport(v,x.businessDate,G);return Y(x,L.reportHubId,{report:L})}let{reportHubId:F,businessDate:z}=x,X=async(L,fe)=>{try{let Te=await fe(L.value);return Y(L,F,{updatedStatus:{isStarred:Te.isStarred,isRead:Te.isRead},operationTimestamp:L.operationTimestamp})}catch(Te){if(Te instanceof Error&&Te.message==="Not Found")return $({error:"Report not found"},{status:404});throw Te}};switch(x.intent){case"update":try{return await r.updateDailyReport(F,v,x.changes,G),Y(x,F,{})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return $({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return $({error:"Report not found"},{status:404})}throw L}case"publish":try{let L=await r.publishDailyReport(F,v,G);return Y(x,F,{report:L})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return $({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return $({error:"Report not found"},{status:404})}throw L}case"delete":try{return await r.deleteDailyReport(F,v,G),Y(x,F,{})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return $({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return $({error:"Report not found"},{status:404})}throw L}case"toggleStar":return await X(x,L=>r.setStarStatus(N,v,F,z,L,G));case"toggleRead":return await X(x,L=>r.setReadStatus(N,v,F,z,L,G));case"addComment":try{let L=await r.addComment(N,v,F,x.content,z,G);return Y(x,F,{newComment:L})}catch(L){if(L instanceof Error){if(L.message==="Not Found")return $({error:"Report not found"},{status:404});if(L.message.startsWith("Comments are restricted"))return $({error:"Comments are restricted for this report"},{status:403})}throw L}case"deleteComment":try{return await r.deleteComment(N,v,F,x.commentId,z,G),Y(x,F,{deletedCommentId:x.commentId})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return $({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return $({error:"Comment not found"},{status:404})}throw L}}},ne=async({request:x,params:v})=>{let{user:N,cookie:$}=await t(x,{failureRedirect:null}),Y=(z,X)=>pa(z,{...X,setCookie:$}),G=(z,X,L)=>pa(Xl(z,X,L),{setCookie:$});if(!N)return Y({error:"Unauthorized"},{status:401});let F=ce();try{if(v.endpoint!==Re.action)return Y({error:"Unknown endpoint"},{status:404});let z=j.spend(N.id,"action");if(z!==null)return Y({error:z.message},{status:z.status,headers:z.headers});let X=await Mn(x,l);if("refusal"in X){let{refusal:Ce}=X;return Ce.status===413&&ue(Ce.measuredBy),Y({error:Ce.error},{status:Ce.status})}let{command:L}=X;if(L.intent==="clearCache"&&!e.enableDevCacheClear)return Y({error:"Invalid intent"},{status:400});let fe=await r.getUserIdByExternalId(N.id);if(!fe)return Y({error:"User not found"},{status:404});let Te=await I(x);return L.intent==="clearCache"?(await r.clearCache(),Y({status:"OK",intent:"clearCache"})):await Z(L,fe,Te,Y,G)}catch(z){if(z instanceof Response)throw z;let X=ce()-F,L=z instanceof Error?z:new Error(String(z));return s.error(`500 action elapsed=${X}ms name=${L.name} message=${L.message}`,L),Y({error:"Internal Server Error"},{status:500})}},pe=ma({authenticate:t,service:r,resolveViewerScope:I,redis:o,sseReader:a,streamKey:i,streamSlots:k,logger:m}),oe=Co({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:I,logger:D}),ye=Hn(h),ee=(x,v)=>async N=>{let $=Un(N.request)?x.frameworkDataRefusal(N):null;if($!==null)throw $;return Bn(N.request,x)?(ye(x.route,N.request),x.crossSiteRejection()):v(N)};return{index:{loader:V},api:{loader:ee(Gl,be),action:ee(Ql,ne)},sse:{loader:ee(ua,pe)},attachment:{loader:ee(xo,oe)}}}var ft=require("@aiquants/mssql"),d=require("drizzle-orm");var fa=(e,t,r,n)=>xe(n.commentable,t)||e.authorUserId!==null&&e.authorUserId===r;var ic=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],sc=["document","comment"],lc=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion"],cc=["hubId","ordinal","authorUserId","commentText"],Jr=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Ra=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw br(e,n,r)},ga=(e,t,r)=>{if(typeof t!="object"||t===null)throw ie(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw ie(`${e}.${o}`,"a column",n[o])},ba=(e,t)=>{if(!Jr(e))throw ie("search","a plain object",e);Ra("search key",e,ic);let{tables:r}=e;if(!Jr(r))throw ie("search.tables","a plain object with document and comment",r);Ra("search.tables key",r,sc),ga("search.tables.document",r.document,lc),ga("search.tables.comment",r.comment,cc);let n=new Map;if(e.externalSourceTexts!==void 0){if(!Jr(e.externalSourceTexts))throw ie("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw br("search.externalSourceTexts key",o,t);if(typeof a!="function")throw ie(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:de("search.concurrency",e.concurrency,1),rateLimitPerMinute:de("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var pt=e=>{let t=typeof e=="object"&&e!==null?e.recordset:void 0;if(!Array.isArray(t))throw new Error("[daily-report] search: the database result has no recordset");return t},yt=(e,t)=>{let r=typeof e=="string"?Me(e):typeof e=="number"&&at(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},ht=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};var J=require("drizzle-orm");var uc=/[[%_]/gu,dc=e=>e.replace(uc,t=>`[${t}]`),Sa=e=>`%${dc(e)}%`;var ve=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),Se=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),q=e=>J.sql`${J.sql.identifier(e.name)}`,Gr=e=>J.sql.join(e.map(t=>J.sql`${t}`),J.sql`, `),Da=(e,t)=>J.sql`SELECT ${q(e.id)} AS ${J.sql.identifier(Se.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${Gr(t)}) ORDER BY ${e.id}`,mc=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(Sa),l=J.sql.join(i.map(m=>J.sql`${o.searchText} LIKE ${m}`),J.sql` OR `),p=J.sql.join(i.map(m=>J.sql`${a.commentText} LIKE ${m}`),J.sql` OR `),s=Ct(n.sourceType,r.scope.commentable),f=s===void 0?J.sql``:J.sql` AND (${s} OR ${a.authorUserId} = ${r.userId})`;return J.sql`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${p})${f}))`},pc=(e,t,r)=>J.sql`(${J.sql.join(t.words.map(n=>mc(e,n,r)),J.sql` AND `)})`,Ta=(e,t,r,n,o)=>{let{hub:a,hubLabel:i,label:l}=e,{document:p}=e.search,s=[J.sql`${a.deletedAt} IS NULL`];n.length>0&&s.push(J.sql`(${a.userId} = ${r.userId} OR NOT EXISTS (SELECT 1 FROM ${i} INNER JOIN ${l} ON ${l.id} = ${i.labelId} WHERE ${i.hubId} = ${a.id} AND ${l.name} IN (${Gr(n)})))`);let f=Ct(a.sourceType,r.scope.visible);f!==void 0&&s.push(f),o!==void 0&&s.push(J.sql`${a.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(o)}))`);let m=t.combine==="intersection"?J.sql` AND `:J.sql` OR `;return s.push(J.sql`(${J.sql.join(t.sets.map(D=>pc(e,D,r)),m)})`),J.sql`SELECT ${q(a.id)} AS ${J.sql.identifier(ve.reportHubId)}, CONVERT(char(10), ${q(a.businessDate)}, 23) AS ${J.sql.identifier(ve.businessDate)}, ${q(a.sourceType)} AS ${J.sql.identifier(ve.sourceType)} FROM ${a} INNER JOIN ${p} ON ${p.hubId} = ${a.id} WHERE ${J.sql.join(s,J.sql` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},Aa=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(p=>({[n.hubId.name]:p.hubId,[n.searchText.name]:p.searchText,[n.sourceDigest.name]:p.sourceDigest,[n.normalizerVersion.name]:r}))),i=JSON.stringify(t.flatMap(p=>p.comments.map(s=>({[o.hubId.name]:p.hubId,[o.ordinal.name]:s.ordinal,[o.authorUserId.name]:s.authorUserId,[o.commentText.name]:s.commentText})))),l=JSON.stringify(t.map(p=>p.hubId));return J.sql`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${q(n.hubId)} bigint, ${q(n.searchText)} nvarchar(max), ${q(n.sourceDigest)} char(64), ${q(n.normalizerVersion)} varchar(64))) AS s ON t.${q(n.hubId)} = s.${q(n.hubId)}
8
- WHEN MATCHED THEN UPDATE SET t.${q(n.searchText)} = s.${q(n.searchText)}, t.${q(n.sourceDigest)} = CONVERT(binary(32), s.${q(n.sourceDigest)}, 2), t.${q(n.normalizerVersion)} = s.${q(n.normalizerVersion)}, t.${q(n.indexedAt)} = SYSUTCDATETIME()
9
- WHEN NOT MATCHED THEN INSERT (${q(n.hubId)}, ${q(n.searchText)}, ${q(n.sourceDigest)}, ${q(n.normalizerVersion)}) VALUES (s.${q(n.hubId)}, s.${q(n.searchText)}, CONVERT(binary(32), s.${q(n.sourceDigest)}, 2), s.${q(n.normalizerVersion)});
1
+ "use strict";var Nr=Object.defineProperty;var ys=Object.getOwnPropertyDescriptor;var hs=Object.getOwnPropertyNames;var fs=Object.prototype.hasOwnProperty;var vn=e=>{throw TypeError(e)};var Rs=(e,t)=>{for(var r in t)Nr(e,r,{get:t[r],enumerable:!0})},Ss=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of hs(t))!fs.call(e,o)&&o!==r&&Nr(e,o,{get:()=>t[o],enumerable:!(n=ys(t,o))||n.enumerable});return e};var gs=e=>Ss(Nr({},"__esModule",{value:!0}),e);var kn=(e,t,r)=>t.has(e)||vn("Cannot "+r);var Mt=(e,t,r)=>(kn(e,t,"read from private field"),r?r.call(e):t.get(e)),vr=(e,t,r)=>t.has(e)?vn("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),kr=(e,t,r,n)=>(kn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Ju={};Rs(Ju,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>cr,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>lr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>Mn,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Yt,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>Pn,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>Er,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>Dn,DailyReportSseReader:()=>Et,DailyReportViewerScope:()=>Ce,SqlResultCache:()=>Rt,createDailyReportHandlers:()=>Ir,createDailyReportServer:()=>Ku,createDailyReportService:()=>Cr,createEpochStore:()=>zt,createSharpThumbnailRenderer:()=>Bi,defineDailyReportSchema:()=>Ei,defineDailyReportSearchSchema:()=>Ii,isStreamIdLte:()=>Ze,parseClientTempId:()=>rr,predictSharpThumbnailWorkingSetBytes:()=>$i,readDailyReportSseStreamEntry:()=>At,transformJsonArray:()=>Ti});module.exports=gs(Ju);var bs=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,se=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${bs(r)}`),ft=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),Hr=(e,t,r)=>se(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),te=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw se(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},at=(e,t,r,n)=>t===void 0?n:te(e,t,r);var ce=()=>Math.floor(performance.now());var He=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},zt=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{}}}),Pt=(e,t)=>t?e.map(r=>structuredClone(r)):e,Rt=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-ce())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let c=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:s,expireAt:ce()+a,epoch:c}),s})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&c===null)throw new He(o.signal.aborted?"aborted":"busy");try{for(let y of r)y();let s=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:s,expireAt:ce()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),s}finally{c?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new He("aborted");return this.buckets.delete(r),Pt(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ce())if(t.epochKey){let c=await this.epochStore.getEpoch(t.epochKey);if(c===null||i.epoch===c)return this.maybeRefreshAhead(t),Pt(i.records,o);this.buckets.delete(r)}else return this.maybeRefreshAhead(t),Pt(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return Pt(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new He("aborted");return Pt(await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};this.readOwnOrRetry=async(t,r)=>{try{return await t}catch(n){let{admission:o}=r;if(!(n instanceof He&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};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)};this.defaultTtlMs=te("defaultTtlMs",t.defaultTtlMs,1),this.maxBuckets=te("maxBuckets",t.maxBuckets,1),this.lastSweepAt=ce()}writeBucket(t,r){this.buckets.delete(t),this.buckets.set(t,r);let n=ce();n-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(n);for(let o of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets)break;this.buckets.delete(o)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.buckets.delete(r)}};var Hn="ids-stream";var Gt=e=>{let t=2166136261,r=-624069552;for(let n of e){let o=n.reportHubId;t^=o&255,t=Math.imul(t,16777619),t^=o>>>8&255,t=Math.imul(t,16777619),t^=o>>>16&255,t=Math.imul(t,16777619),t^=o>>>24&255,t=Math.imul(t,16777619),r^=o>>>24&255,r=Math.imul(r,16777619),r^=o>>>16&255,r=Math.imul(r,16777619),r^=o>>>8&255,r=Math.imul(r,16777619),r^=o&255,r=Math.imul(r,16777619);let a=n.businessDate;if(a===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let i=0;i<a.length;i++){let l=a.charCodeAt(i);t^=l&255,t=Math.imul(t,16777619),r^=l&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},Kt=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,Un=e=>{for(let t=1;t<e.length;t++)if(Kt(e[t-1],e[t])>0)return!1;return!0},$n=(e,t)=>{let r=e.findIndex(n=>Kt({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var ue=Object.freeze({businessDate:"business-date",idsStream:Hn,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",action:"action"}),Te=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var Ds=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Bn=e=>e<10?`0${e}`:`${e}`,As=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Bn(e.getMonth()+1),n=Bn(e.getDate());return`${t}-${r}-${n}`},St=e=>{let t=Ds.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let c=new Date(0);return c.setUTCFullYear(a,i-1,l),c.getUTCFullYear()!==a||c.getUTCMonth()!==i-1||c.getUTCDate()!==l?null:`${r}-${n}-${o}`},Jt=e=>St(e)===e;var Pe=e=>e==null?null:e instanceof Date?As(e):St(e);var Fn=(e,t,r=console)=>{let n=o=>typeof o=="string"?[`${t} ${o}`]:[t,o];return{debug:(o,...a)=>{e<=0&&r.debug(...n(o),...a)},info:(o,...a)=>{e<=1&&r.info(...n(o),...a)},warn:(o,...a)=>{e<=2&&r.warn(...n(o),...a)},error:(o,...a)=>{e<=3&&r.error(...n(o),...a)}}},sd=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),Vn=e=>`[DailyReport${e}]`,Re=(e,t,r)=>e===void 0?Fn(t,Vn(r)):Fn(0,Vn(r),e);var Ts="legacy-",Ur=e=>`${Ts}${e}`;var Yn=require("zod"),gt=e=>Number.isSafeInteger(e)&&e>0,be=Yn.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var Es=/^[1-9][0-9]*$/,Is=/^(?:0|[1-9][0-9]*)$/,Ue=e=>{if(e===null||!Es.test(e))return null;let t=Number(e);return gt(t)?t:null},$r=e=>{if(e===null||!Is.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Br=e=>e==="true"?!0:e==="false"?!1:null,Lt=e=>e===null?!1:Br(e);var qn=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),Ge=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var _s=2166136261,ws=16777619,Fr=e=>{let t=_s;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,ws);return t>>>0},xs=String.fromCodePoint(3),Cs=String.fromCodePoint(2),Ms=String.fromCodePoint(1),Qt=e=>Fr(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(xs)).join(Cs)).join(Ms));var Wn=e=>e==="intersection"||e==="union",Ie=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Vr=2,Xt=2,it=Object.freeze({word:0,reading:1});var Yr=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var yd=2*(1+Vr);var Hs=require("zod");var Zt=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;var O=require("zod");var jn=15e3,zn="lastEventId",Ps=/^\d{1,15}-\d{1,15}$/,Gn=e=>Ps.test(e),Ls=O.z.object({name:O.z.string().nullish(),affiliation:O.z.string().nullish()}),Os=O.z.object({name:O.z.string().nullish(),text:O.z.string().nullish(),color:O.z.string().nullish()}),Ns=O.z.object({id:be,name:O.z.string().nullish(),color:O.z.string().nullish()}),Kn=O.z.object({id:be,userId:O.z.string().nullish(),userName:O.z.string().nullish(),content:O.z.string().nullish(),createdAt:O.z.string().nullish(),isMine:O.z.boolean()}),vs=O.z.object({id:O.z.string(),fileName:O.z.string(),fileType:O.z.string().nullable(),fileSize:O.z.number().nullable(),createdAt:O.z.string().nullable(),state:O.z.enum(["present","absent","unknown"]),hasThumbnail:O.z.boolean().default(!1)}),qr=O.z.object({reportHubId:be,date:O.z.string().nullish(),createdAt:O.z.string().nullish(),author:O.z.string().nullish(),userId:O.z.string().nullish(),sourceType:O.z.string().nullish(),employeeName:O.z.string().nullish(),updatedBy:O.z.string().nullish(),updatedAt:O.z.string().nullish(),category:O.z.string().nullish(),creationCategory:O.z.string().nullish(),visitTimeFrom:O.z.string().nullish(),visitTimeTo:O.z.string().nullish(),customerName:O.z.string().nullish(),interviewers:O.z.array(Ls),subject:O.z.string().nullish(),content:O.z.string().nullish(),externalComments:O.z.array(Os),isRead:O.z.boolean(),isStarred:O.z.boolean(),labels:O.z.array(Ns),postedComments:O.z.array(Kn),attachments:O.z.array(vs).default([])}),st=O.z.string().regex(Zt),ks=O.z.object({type:O.z.literal("connected")}),er=O.z.object({type:O.z.literal("status-update"),reportHubId:be,statusType:O.z.enum(["star","read"]),value:O.z.boolean(),clientTempId:st,recipientRawUserId:be.optional()}),Wr=O.z.string().optional(),jr=O.z.object({type:O.z.literal("comment-add"),reportHubId:be,comment:Kn,clientTempId:st,recipientRawUserId:be.optional(),sourceType:Wr}),zr=O.z.object({type:O.z.literal("comment-delete"),reportHubId:be,commentId:be,clientTempId:st,recipientRawUserId:be.optional(),sourceType:Wr}),Gr=O.z.object({type:O.z.literal("report-create"),reportHubId:be,report:qr,clientTempId:st,recipientRawUserId:be.optional()}),Kr=O.z.object({type:O.z.literal("report-update"),reportHubId:be,report:qr,clientTempId:st,recipientRawUserId:be.optional()}),Jr=O.z.object({type:O.z.literal("report-publish"),reportHubId:be,report:qr,clientTempId:st,recipientRawUserId:be.optional()}),Qr=O.z.object({type:O.z.literal("report-delete"),reportHubId:be,clientTempId:st,sourceType:Wr}),Jn=O.z.discriminatedUnion("type",[ks,er,jr,zr,Gr,Kr,Jr,Qr]);var Le=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var tr=Math.max(1,Math.floor(10.556701030927835));var $e=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Oe=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(s=>[s,0]))};o.set(i,l),$e(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,c)=>{let s=o.get(i);if(s!==void 0){s.count+=1,s.tallies[l]+=1;return}c(),a(i)}}};var rr=e=>e!==null&&Zt.test(e)?e:null,Xr=e=>Wn(e)?e:null,Zr=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Ie.maxDetailIds)return null;let r=[];for(let n of t){let o=Ue(n);if(o===null||r.includes(o))return null;r.push(o)}return r},Qn=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Zn=Object.freeze({status:400,error:"Invalid form"}),eo=e=>({status:413,error:"Form too large",measuredBy:e}),Us=(e,t,r)=>{let n=0;return e.pipeThrough(new TransformStream({transform(o,a){if(n+=o.byteLength,n>t){r(),a.error(new Error(`action form body exceeds ${t} bytes`));return}a.enqueue(o)}}))},$s=async e=>{let t=$r(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:eo("declared")};let r=!1,n=e.body===null?null:Us(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let i;try{i=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?eo("counted"):Zn}}let l=Qn(i);return l===null?{refusal:Zn}:{fields:l}},to=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=Br(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},no=Object.freeze({update:(e,t,r)=>{let n=e.get(Le.title),o=e.get(Le.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:to("toggleStar",Le.isStarred),toggleRead:to("toggleRead",Le.isRead),addComment:(e,t)=>{let r=e.get(Le.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Ue(e.get(Le.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Bs=e=>Object.hasOwn(no,e),Fs=(e,t)=>{let r=e.get(Le.intent),n=e.get(Le.businessDate),o=n===null?null:St(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Le.operationTimestamp),i=$r(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Le.clientTempId);if(!l)return{error:"clientTempId required"};let c=rr(l);if(c===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:c,businessDate:o,operationTimestamp:i}};let s=Ue(e.get(Le.reportHubId));return s===null?{error:"Invalid reportHubId"}:r===null||!Bs(r)?{error:"Invalid intent"}:no[r](e,{clientTempId:c,businessDate:o,operationTimestamp:i,reportHubId:s},t)},oo=async(e,t)=>{let r=await $s(e);if("refusal"in r)return r;let n=Fs(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Vs=6e4,Ys="form_too_large",ro=["declared","counted"],ao=e=>{let t=Oe({windowMs:Vs,tallies:ro,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${ro.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(Ys,r,n)}};var tt=Object.freeze({[ue.businessDate]:{body:"json",admission:["refresh-bucket","cache","miss-gate"]},[ue.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[ue.report]:{body:"json",admission:["refresh-bucket","cache","miss-gate"]},[ue.search]:{body:"json",admission:["search-limiter"]},[ue.reports]:{body:"json",admission:["search-limiter"]},[ue.searchMarks]:{body:"json",admission:["search-limiter"]}}),io=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),en=e=>e!==void 0&&Object.hasOwn(tt,e);var tn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),so=e=>Object.hasOwn(tn,e);var qs="download",Ws="thumbnail",js="1";var rn=e=>{let t=e.getAll(Ws),r=e.getAll(qs);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&so(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===js?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var lo=require("crypto"),nn=e=>`"${(0,lo.createHash)("sha256").update(e).digest("hex")}"`,co=e=>nn(JSON.stringify(e));var Fe=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),on=(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},ae=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=nn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...Fe});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&on(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},Ke=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...Fe});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},zs=5e3/1e3,Gs=new Map([[503,zs]]),we=e=>{let t=Gs.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var sn="Cross-site request rejected",Ks="Not Found",Js=new Set(["same-origin","none"]),Qs=new Set(["GET","HEAD","OPTIONS"]),uo=["api","action","sse","attachment"],mo=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...Fe}}),Xs=()=>mo(403,sn),nr=()=>mo(404,Ks),Ot=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:Xs}),po=e=>new URL(e.url).pathname.endsWith(".data"),Zs=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},yo=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Qs.has(e.method)||Zs(e)):Js.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},el=6e4,tl="refusals",rl=32,nl=/^[a-z-]+$/,an=e=>{if(e===null)return"-";let t=e.slice(0,rl);return nl.test(t)&&t===e?e:JSON.stringify(t)},ho=e=>{let t=Oe({windowMs:el,tallies:uo,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${uo.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${an(a.get("Sec-Fetch-Site"))} mode=${an(a.get("Sec-Fetch-Mode"))} dest=${an(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(tl,r,o)}};var fo=(e,t)=>(r,n)=>{let o=n?"markAttachmentPresent":"markAttachmentMissing";e[o](r).catch(a=>{t.error(`${o} failed attachment=${r} message=${a instanceof Error?a.message:"unknown"}`)})};var ol="same-origin",al="SAMEORIGIN",bt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":ol,"X-Frame-Options":al}),or=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...bt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Ro=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),il=/^[\x20-\x7E]+$/,sl=/^[\w.+-]+\/[\w.+-]+/,ln=e=>e&&il.test(e)&&sl.test(e)?e:null,ll=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,So=e=>encodeURIComponent(e.replace(ll,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),go=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),ar={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},bo={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},ir=e=>typeof e=="string"&&Object.hasOwn(bo,e),sr=e=>bo[e],Je="Attachment request failed";var Ve=e=>{let t=te("limit",e.limit,1),r=te("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:te("queue.max",e.queue.max,0),maxPerOwner:te("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:te("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,c=(b,w)=>b.get(w)??0,s=(b,w,H)=>{let B=c(b,w)+H;B<=0?b.delete(w):b.set(w,B)},y=b=>c(l,b)<r,m=b=>o<t&&y(b),S=b=>(o+=1,s(l,b,1),A(b)),f=()=>{let b=-1,w=r;for(let[H,B]of a.entries()){let C=c(l,B.owner);if(C<w&&(b=H,w=C,C===0))break}return b},R=()=>{for(;o<t;){let b=f();if(b<0)return;let[w]=a.splice(b,1);s(i,w.owner,-1),w.grant(S(w.owner))}},A=b=>{let w=!1;return()=>{w||(w=!0,o-=1,s(l,b,-1),R())}};return{canAcquire:m,acquire:(b,w)=>{if(w.aborted)return Promise.resolve(null);if(m(b))return Promise.resolve(S(b));if(n===null||a.length>=n.max||c(i,b)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:H}=n,B=C=>{let I=()=>{let le=a.indexOf(U);le<0||(a.splice(le,1),s(i,b,-1),$(),C(null))},V=$e(I,H),$=()=>{clearTimeout(V),w.removeEventListener("abort",I)},U={owner:b,grant:le=>{$(),C(le)}};a.push(U),s(i,b,1),w.addEventListener("abort",I,{once:!0})};return new Promise(B)}}};var cl=1024,cn="Too many requests",ul=(e,t)=>{te("limitPerWindow",e,1),te("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let c=l??{tokens:e,lastRefillMs:i};n(c,i),r.set(a,c);for(let s of r.keys()){if(r.size<=cl)break;r.delete(s)}return c};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let c=r.get(a);c&&(n(c,i),c.tokens=Math.min(e,c.tokens+l))}}},Qe=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(te("windowMs",r,1e3)%1e3!==0)throw se("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=ul(e.limitPerWindow,r),i=Object.freeze({status:429,message:cn,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Oe({windowMs:r,tallies:[t],writeSuppressed:(c,{count:s,since:y})=>{n.warn(`${t}_suppressed count=${s} since=${y} ${o(c)}`)}});return{spend:(c,s)=>a.consume(c,ce())?null:(l.record(c,t,()=>n.warn(`429 ${s} reason=${t}`)),i),refund:(c,s)=>{a.refund(c,ce(),s)}}};var ml=256*1024,Do=6e4,pl=e=>Math.ceil(e/2),yl=new Uint8Array(new ArrayBuffer(0)),hl=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=yl,t()},i=l=>{clearTimeout(o),o=$e(()=>{l.error(new Error(`attachment body idle for ${Do} ms`)),a()},Do)};return new ReadableStream({start(l){i(l)},pull(l){let c=Math.min(n+ml,r.byteLength);if(c>n&&l.enqueue(r.slice(n,c)),n=c,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},Ao=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=Qe({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:c=>`viewer=${c}`}),l=Ve({limit:e.concurrency,maxHeldPerOwner:pl(e.concurrency),queue:null});return async c=>{let{request:s,delivery:y,attachmentId:m,internalUserId:S,readAttachment:f,cookie:R,fail:A}=c,b=e.maxBytes,w=i.spend(S,`attachment=${m} viewer=${S}`);if(w)return A(w.status,w.message,w.headers);let H=await n(s),B=await t.getAttachmentForUser(H,m,S);if(!B)return o.warn(`404 attachment=${m} viewer=${S} reason=not_visible`),A(404,"Attachment not found");if(B.fileSize!=null&&B.fileSize>b)return o.warn(`413 attachment=${m} viewer=${S} reason=db_size`),A(413,"Attachment too large");let C=ln(B.fileType),I=`filename="${go(B.fileName)}"; filename*=UTF-8''${So(B.fileName)}`,V=await l.acquire(S,s.signal);if(!V)return s.signal.aborted?(o.info(`503 attachment=${m} viewer=${S} reason=aborted`),A(503,"Attachment request aborted")):(o.warn(`503 attachment=${m} viewer=${S} reason=concurrency`),A(503,"Too many concurrent downloads",we(503)));let $=!1;try{let U=await f(B.filePath,{maxBytes:b,head:s.method==="HEAD",principal:r(S),signal:s.signal});if(s.signal.aborted)return o.info(`503 attachment=${m} viewer=${S} reason=aborted`),A(503,"Attachment request aborted");if(!U.ok){if(!ir(U.reason))return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=failure_reason`),A(500,Je);let me=sr(U.reason);return U.reason==="not_found"&&a(m,!1),o.warn(`${me} attachment=${m} viewer=${S} reason=${U.reason} code=${U.code??"-"}`),A(me,ar[me],we(me))}if(U.bytes.byteLength>b)return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=over_max_bytes`),A(500,Je);let le=s.method==="HEAD";if(le&&U.size!==void 0&&U.size>b)return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=over_max_bytes`),A(500,Je);if(!le&&U.size!==void 0&&U.size!==U.bytes.byteLength)return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=size_mismatch`),A(500,Je);let de=C??ln(U.contentType),Se=de!==null&&Ro.has(de),W=Se?de:"application/octet-stream",ne=Se&&y.kind!=="download"?"inline":"attachment",ee=le?U.size:U.bytes.byteLength,ie=new Headers({"Content-Type":W,"Content-Disposition":`${ne}; ${I}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...bt});return ee!==void 0&&ie.set("Content-Length",String(ee)),R&&ie.append("Set-Cookie",R),a(m,!0),o.info(`200 attachment=${m} viewer=${S} type=${W} disposition=${ne} bytes=${ee??"-"}`),le?new Response(null,{status:200,headers:ie}):($=!0,new Response(hl(U.bytes,V),{status:200,headers:ie}))}finally{$||V()}}};var xe=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),lm=xe.queueWaitMs+xe.readMs+xe.renderMs+xe.transferMarginMs;var Io=require("buffer"),_o=new Set([194,198,202,206]),fl=new Set([192,193,194,195]),wo=216,Rl=217,xo=218,Sl=4,gl=64,bl=2,To=8,Eo=28,rt=12,un=8,Dl=20,Co=rt+un+10,Al=2,Xe=(e,t)=>e[t]<<8|e[t+1],Dt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},Ye=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},Mo=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Po=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),Lo=e=>(e.stepsLeft-=1,e.stepsLeft>=0),Oo=e=>e[0]===255&&e[1]===wo,No=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!Lo(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let o=e[n];if(n+=1,o===Rl)return"eoi";if(o===0||o===wo)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=Xe(e,n),i=n+a;return a<2||i>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=i,"segment")}},Tl=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!Lo(r))return null;if(a+1>=n)return n;let i=e[a+1];if(i===255)a+=1;else if(i===0||i>=208&&i<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},vo=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=Xe(e,r+1),a=Xe(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let c=0;c<i;c+=1){let s=e[r+7+3*c],y=s>>4,m=s&15;if(y<1||y>4||m<1||m>4)return null;l.push({id:e[r+6+3*c],horizontal:y,vertical:m})}return{marker:t,width:a,height:o,components:l}},ko=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>Sl||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},Ho=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:_o.has(e.marker)||t<e.components.length}),dn=e=>{if(!Oo(e))return null;let t=Po(e.byteLength),r=null;for(let n=2;;){if(No(e,n,t)!=="segment")return null;if(Mo(t.marker)){if(r!==null||(r=vo(e,t),r===null))return null}else if(t.marker===xo){if(r===null)return null;let o=ko(e,t);return o===null?null:Ho(r,o.length)}n=t.end}},Uo=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:o})=>{let a=Math.ceil(e.width*n/(t*To)),i=Math.ceil(e.height*o/(r*To));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},$o=e=>e.multiScan?Uo(e).reduce((r,n)=>r+n,0)*gl*bl:0,El=896,Bo=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!Oo(e))return null;let n=Io.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=Po(r),a=null,i=null,l=new Map,c=0,s=0,y=0;for(let m=2;;){let S=No(e,m,o);if(S===null)return null;if(S==="eoi")return i===null?null:{header:i,blockVisits:s};if(m=o.end,Mo(o.marker)){if(a!==null||!fl.has(o.marker)||(a=vo(e,o),a===null))return null;let f=Uo(a);l=new Map;for(let[R,A]of a.components.entries()){let b=l.get(A.id);l.set(A.id,b===void 0?f[R]:Math.max(b,f[R]))}c=a.components.length*(_o.has(a.marker)?El:1)}else if(o.marker===xo){if(a===null||y===c)return null;let f=ko(e,o);if(f===null)return null;for(let A of f){let b=l.get(A);if(b===void 0)return null;s+=b}if(y+=1,i===null&&(i=Ho(a,f.length)),s>t||!i.multiScan)return{header:i,blockVisits:s};let R=Tl(n,o.end,o);if(R===null)return null;m=R}}},Fo=e=>{if(e.byteLength<24||Xe(e,8)!==0||Xe(e,10)!==13||!Ye(e,12,"IHDR"))return null;let t=Xe(e,16)*65536+Xe(e,18),r=Xe(e,20)*65536+Xe(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Il=e=>{if(Ye(e,rt,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Dt(e,26,2)&16383,r=Dt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Ye(e,rt,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Dt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Ye(e,rt,"VP8X")?e.byteLength<Co?null:{width:Dt(e,24,3)+1,height:Dt(e,27,3)+1}:null},Vo=e=>{if(Fo(e)===null||e.byteLength<=Eo)return null;switch(e[Eo]){case 0:return!1;case 1:return!0;default:return null}},Yo=(e,t)=>{if(Ye(e,rt,"VP8 "))return"lossy";if(Ye(e,rt,"VP8L"))return"lossless";if(!Ye(e,rt,"VP8X")||e.byteLength<Co)return null;if((e[Dl]&Al)!==0)return"animated";let r=!1,n=t;for(let o=rt;o+un<=e.byteLength;){if(n-=1,n<0)return null;if(Ye(e,o,"VP8L"))return"lossless";if(Ye(e,o,"VP8 "))return r?"lossy-alpha":"lossy";Ye(e,o,"ALPH")&&(r=!0);let a=Dt(e,o+4,4);o+=un+a+a%2}return null},qo={png:Fo,jpeg:dn,webp:Il};var lr=Object.freeze(["image/webp","image/jpeg","image/png"]),cr=1024*1024;var _l=new Set(["image/png","image/jpeg","image/gif","image/webp"]),wl={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},xl=new Set(lr),Cl=e=>typeof e=="string"&&xl.has(e),Ml=256,ur=(e,t)=>e.fileType===null||!_l.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Pl=[137,80,78,71,13,10,26,10],Ll=[255,216,255],Ol=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Nl=[82,73,70,70],vl=[87,69,66,80],Nt=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,o]of t.entries())if(e[r+n]!==o)return!1;return!0},mn=e=>{if(Nt(e,Pl,0))return"png";if(Nt(e,Ll,0))return"jpeg";for(let t of Ol)if(Nt(e,t,0))return"gif";return Nt(e,Nl,0)&&Nt(e,vl,8)?"webp":null},Wo=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:co([t])}},jo=(e,t)=>{if(!Cl(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>cr)return"too_large";let r=wl[e.contentType];if(mn(e.bytes)!==r)return"signature";let n=qo[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},zo=e=>{te("maxBytes",e.maxBytes,0),te("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+Ml;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let c of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(c)}}}};var pn=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ce(),l=new AbortController,c=!1,s,y,m=()=>{a(ce()-i)},S=C=>{s=$e(()=>{c=!0,C({timedOut:!0}),y=$e(m,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},f=new Promise(S),R=AbortSignal.any([r,l.signal]),A=C=>{C(n(R))},b=new Promise(A),w=C=>(clearTimeout(s),clearTimeout(y),c&&o(ce()-i,C.kind==="error"?{error:C.error}:null),C),H=b.then(C=>w({kind:"value",value:C}),C=>w({kind:"error",error:C}));return{outcome:Promise.race([b.then(C=>({timedOut:!1,value:C})),f]),settled:H}};var nt={404:"Attachment not found",500:Je,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Go=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=jo(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},kl=e=>{let t=new AbortController,r=()=>{t.abort()},n=$e(r,xe.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Ko=()=>{},Hl=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),Jo=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,c=(f,R)=>{let A=R.then(Ko,Ko);l.set(f,A);let b=()=>{l.get(f)===A&&l.delete(f)};A.then(b)},s=async(f,R)=>{let A=l.get(f.key);if(A===void 0)return t.acquire(f.owner,R);let b=kl(R);try{if(await Hl(A,b.signal),b.signal.aborted)return null;let w=r.get(f.key);return w!==void 0?{...w,identity:"verified"}:await t.acquire(f.owner,b.signal)}finally{b.end()}},y=(f,R)=>{if(f.fileSize===null)return R.kind==="exact"?"verified":"unrecorded";if(R.kind==="exact"?R.bytes===f.fileSize:f.fileSize>R.maxBytes)return"verified";let b=R.kind==="exact"?String(R.bytes):`>${R.maxBytes}`;return i.warn(`size_mismatch expected=${f.fileSize} got=${b} attachment=${f.attachmentId} viewer=${f.owner} variant=thumbnail`),"unverified"},m=(f,R)=>(A,b)=>{let w=b===null?"":` message=${b.error instanceof Error?b.error.message:"unknown"}`;i.warn(`${f}_overrun ms=${A} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail${w}`)},S=(f,R)=>A=>{i.warn(`${f}_stuck ms=${A} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail`)};return async(f,R)=>{let A=await s(f,R);if(A===null)return{kind:"failure",status:503,reason:R.aborted?"aborted":"queue"};if(typeof A!="function")return A;let b=A,w=null;try{if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let H=r.get(f.key);if(H!==void 0)return{...H,identity:"verified"};let B=pn({budgetMs:xe.readMs,flightSignal:R,call:me=>f.readAttachment(f.filePath,{maxBytes:n,head:!1,principal:o(f.owner),signal:me}),onOverrun:m("read",f),onStuck:S("read",f)}),C=await B.outcome;if(C.timedOut)return w=B.settled,R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let I=C.value;if(!I.ok&&I.reason!=="too_large")return ir(I.reason)?(I.reason==="not_found"&&a(f.attachmentId,!1),{kind:"failure",status:sr(I.reason),reason:I.reason,code:I.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(I.ok&&I.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let V=y(f,I.ok?{kind:"exact",bytes:I.bytes.byteLength}:{kind:"over",maxBytes:n}),$=me=>{V==="verified"&&r.set(f.key,me)},U=me=>($(me),{...me,identity:V});if(!I.ok)return U({kind:"unrenderable",reason:"too_large"});let le=mn(I.bytes);if(le===null)return U({kind:"unrenderable",reason:"signature"});let de=pn({budgetMs:xe.renderMs,flightSignal:R,call:me=>f.renderer.render(I.bytes,{format:le,maxWidth:f.box.maxWidth,maxHeight:f.box.maxHeight,signal:me}),onOverrun:m("render",f),onStuck:S("render",f)}),Se=me=>{if(me.kind==="error")return;let fe=Go(me.value,f.box);"entry"in fe&&$(fe.entry)},W=null,ne=()=>(W===null&&(W=de.settled.then(Se),c(f.key,W)),W);R.addEventListener("abort",ne,{once:!0});let ee=await de.outcome.finally(()=>R.removeEventListener("abort",ne));if(ee.timedOut||R.aborted)return w=ne(),R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let ie=Go(ee.value,f.box);return"entry"in ie?U(ie.entry):ie.failure}finally{w===null?b():w.then(b,b)}}};var Qo=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let c=new AbortController,s=()=>{e.get(t)?.controller===c&&e.delete(t)},m={promise:n(c.signal).finally(s),controller:c,waiters:0};return e.set(t,m),m},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var ea=10,Ul=1/ea,Xo=1-Ul,$l=1024,Bl=64,Fl=8,Zo="private, no-cache",Vl="no-store",Yl=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),ql=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},ta=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:c}=l,s=(C,I)=>Qe({reason:C,limitPerWindow:I,windowMs:6e4,logger:o,windowFields:V=>`viewer=${V} variant=thumbnail`}),y=s("rate_limit",l.rateLimitPerMinute),m=s("revalidation_rate_limit",l.rateLimitPerMinute*ea),S=Ve({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Bl,maxPerOwner:Fl,maxWaitMs:xe.queueWaitMs}}),f=zo({maxBytes:l.cacheBytes,maxEntries:$l}),R=Qo(),A=Jo({gate:S,cache:f,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),b=(C,I,V,$)=>{let U=`attachment=${C.attachmentId} viewer=${C.internalUserId} variant=thumbnail cache=${$}`;if(I.kind==="failure")return o[ql(I)](`${I.status} ${U} reason=${I.reason} code=${I.code??"-"}`),C.fail(I.status,nt[I.status],we(I.status));let le=Yl[I.identity];if(I.kind==="unrenderable")return o.info(`404 ${U} reason=${I.reason}${le}`),C.fail(404,nt[404]);let de=I.identity==="verified"?{"Cache-Control":Zo,ETag:V}:{"Cache-Control":Vl},Se=new Headers({"Content-Type":I.contentType,"Content-Length":String(I.bytes.byteLength),...de,"Content-Security-Policy":"default-src 'none'; sandbox",...bt});return C.cookie&&Se.append("Set-Cookie",C.cookie),o.info(`200 ${U} type=${I.contentType} bytes=${I.bytes.byteLength}${le}`),new Response(I.bytes,{status:200,headers:Se})},w=(C,I)=>{let V=C.spend(I.internalUserId,`attachment=${I.attachmentId} viewer=${I.internalUserId} variant=thumbnail`);return V===null?null:I.fail(V.status,V.message,V.headers)},H=C=>w(y,C),B=(C,I)=>I?w(m,C):H(C);return async(C,I)=>{let{request:V,attachmentId:$,internalUserId:U,readAttachment:le,cookie:de,fail:Se}=C,W=tn[I],ne=V.headers.get("If-None-Match"),ee=ne!==null,ie=B(C,ee);if(ie)return ie;let me=await n(V),fe=await t.getAttachmentForUser(me,$,U),re=fe!==null&&ur(fe,i)?Wo({rendererId:c.id,box:W,attachmentId:$,filePath:fe.filePath,fileType:fe.fileType,fileSize:fe.fileSize}):null;if(re&&on(ne,re.etag)){let E=new Headers({"Cache-Control":Zo,ETag:re.etag,...bt});return de&&E.append("Set-Cookie",de),o.info(`304 attachment=${$} viewer=${U} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:E})}if(ee){let E=H(C);if(E)return E}if(!fe)return o.warn(`404 attachment=${$} viewer=${U} variant=thumbnail reason=not_visible`),Se(404,nt[404]);if(!re)return y.refund(U,Xo),o.info(`404 attachment=${$} viewer=${U} variant=thumbnail reason=not_eligible`),Se(404,nt[404]);let{key:Me,etag:ke}=re,Ae=f.get(Me);if(Ae)return y.refund(U,Xo),b(C,{...Ae,identity:"verified"},ke,"hit");let v=E=>A({key:Me,attachmentId:$,filePath:fe.filePath,fileSize:fe.fileSize,box:W,owner:U,readAttachment:le,renderer:c},E),N;try{N=await R.join(Me,V.signal,v)}catch(E){return o.error(`500 attachment=${$} viewer=${U} variant=thumbnail cache=miss reason=port_exception message=${E instanceof Error?E.message:"unknown"}`),Se(500,nt[500])}return b(C,N,ke,"miss")}};var Wl='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',jl=()=>or(403,sn,{cookie:null}),ra=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=rn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>or(404,ar[404],{cookie:null}),crossSiteRejection:jl}),na=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,i=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:fo(r,a)},c=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Ao({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:ta({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:s,params:y})=>{let m=null,S=(f,R,A={})=>or(f,R,{cookie:m,extraHeaders:A});try{let{user:f,cookie:R}=await t(s,{failureRedirect:null});if(m=R??null,!f)return S(401,"Unauthorized");let A=rn(new URL(s.url).searchParams);if(A.kind==="invalid")return S(400,"Invalid attachment request");if(A.kind==="thumbnail"&&s.method!=="GET")return S(405,"Method not allowed",{Allow:"GET"});if(s.method!=="GET"&&s.method!=="HEAD")return S(405,"Method not allowed",{Allow:"GET, HEAD"});if(c===null)return S(404,"Attachment not found");if(y.token===void 0)throw new Error(Wl);let b=c.idCodec.decode(y.token);if(b===null||!gt(b))return S(400,"Invalid attachment token");let w=await r.getUserIdByExternalId(f.id);if(!w)return S(403,"Forbidden");let H={request:s,delivery:A,attachmentId:b,internalUserId:w,readAttachment:c.read,cookie:m,fail:S};return A.kind!=="thumbnail"?await c.serveOriginal(H):c.serveThumbnail===null?S(404,nt[404]):await c.serveThumbnail(H,A.variant)}catch(f){if(f instanceof Response)throw f;return a.error(`500 attachment=? viewer=? reason=unexpected message=${f instanceof Error?f.message:"unknown"}`),S(500,Je)}}};var zl=32*1024*1024,Gl=60,Kl=4,Jl=120,Ql=2,Xl=8*1024*1024,dr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zl=e=>{if(e===void 0)throw ft("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!dr(e))throw se("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw ft("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw se("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw se("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},ec=e=>{if(e===void 0)return null;if(!dr(e))throw se("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:Zl(e.renderer),rateLimitPerMinute:at("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Jl),concurrency:at("attachments.thumbnails.concurrency",e.concurrency,1,Ql),cacheBytes:at("attachments.thumbnails.cacheBytes",e.cacheBytes,0,Xl)})},oa=e=>{let t=e;if(t===void 0)return null;if(!dr(t))throw se("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw ft("attachments.idCodec","injected when attachments is given");if(!dr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw se("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw ft("attachments.read","injected when attachments is given");if(typeof n!="function")throw se("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:at("attachments.maxBytes",t.maxBytes,1,zl),rateLimitPerMinute:at("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,Gl),concurrency:at("attachments.concurrency",t.concurrency,1,Kl),thumbnails:ec(t.thumbnails)})},tc=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),mr=e=>{for(let[t,r]of tc)if(Object.hasOwn(e,t))throw ft(r,`given in place of the flat key ${t}`)};var ia=8,rc=8*ia,nc=128,oc=2,sa=oc*nc,ac=4*sa,ic=6e4,sc=6e4,lc="Too many reads",aa=Object.freeze(Object.keys(tt).filter(e=>tt[e].admission.includes("miss-gate"))),la=e=>{let t=Ve({limit:rc,maxHeldPerOwner:ia,queue:{max:ac,maxPerOwner:sa,maxWaitMs:ic}}),r=Oe({windowMs:sc,tallies:aa,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${aa.map(l=>`${l}:${i[l]}`).join(",")}`)}});return{admissionFor:(n,o,a)=>({signal:a,acquire:async i=>{let l=await t.acquire(n,i);return l===null&&!i.aborted&&r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=cache_miss_admission`)),l}})}},pr=(e,t)=>{let r=ae(e,t,{error:{message:lc}},503);for(let[n,o]of Object.entries(we(503)))r.headers.set(n,o);return r};var cc=/^[0-9a-f]{1,16}$/;var ca=e=>{let t=e.get(Te.cursorReportHubId),r=e.get(Te.cursorBusinessDate),n=e.get(Te.cursorSnapshot),o=n!==null&&cc.test(n)?n:null,a=null;if(t!==null){let l=Ue(t);if(l===null)return{refused:"cursor"};if(r!==null&&!Jt(r))return{refused:"cursor"};a={businessDate:r,reportHubId:l}}else if(r!==null)return{refused:"cursor"};let i=Lt(e.get(Te.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var yr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,uc=2,dc=16,mc=uc*dc,pc=6e4,ua=()=>{},yc=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},da=e=>{let t=Ve({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:mc,queue:null}),r=Oe({windowMs:pc,tallies:["sse","ids-stream"],writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`streams_per_viewer_suppressed count=${o} since=${a} viewer=${n} routes=sse:${i.sse},ids-stream:${i["ids-stream"]}`)}});return{admit:async(n,o,a)=>{if(n===null)return ua;if(a.aborted){if(t.canAcquire(n))return ua}else{let i=await t.acquire(n,a);if(i!==null)return yc(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var hr=30,fa=4e3,hc="stream interrupted by server error",fc="Too many streams",Rc=15e3,Ra=Symbol("ids-stream-heartbeat"),ma=()=>{},pa=e=>e.return(void 0).then(ma,ma),Sc=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Ra),Rc)}),stop:()=>clearTimeout(e)}};async function*ya(e,t,r,n){let o=t?$n(e,t):0,a=!0;for(;;){let i=e.slice(o,o+(a?r:fa));o+=i.length;let l=o>=e.length,c=i[i.length-1];if(yield{kind:"chunk",items:i,nextCursor:l||!c?null:{businessDate:c.businessDate,reportHubId:c.reportHubId},isLast:l,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,l)return}}var Sa=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...Fe});return e&&t.append("Set-Cookie",e),t},ha=(e,t,r,n,o)=>{let a=async(y,m)=>{o(),m&&await pa(t);try{y.close()}catch{}},i=new TextEncoder,l=!1,c=null,s=new ReadableStream({async pull(y){if(l||r.aborted){await a(y,!0);return}let m=Sc();try{c===null&&(c=t.next());let S=await Promise.race([c,m.fired]);if(m.stop(),S===Ra){if(l||r.aborted){await a(y,!0);return}y.enqueue(i.encode(`
2
+ `));return}c=null;let{value:f,done:R}=S;if(R){await a(y,!1);return}if(l||r.aborted){await a(y,!0);return}y.enqueue(i.encode(`${JSON.stringify(f)}
3
+ `))}catch(S){if(m.stop(),c=null,o(),l||r.aborted)return;S instanceof He||n.error(`ids-stream emission failed: ${S instanceof Error?S.message:String(S)}`);try{let f={kind:"error",error:hc};y.enqueue(i.encode(`${JSON.stringify(f)}
4
+ `)),y.close()}catch{}}},cancel(){l=!0,o(),pa(t)}});return new Response(s,{status:200,headers:Sa(e)})},ga=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,c,s,y,m,S,f)=>{let R=!1,A=null,b=null,w=new Promise((C,I)=>{A=C,b=I});w.catch(()=>{});let H=t.getDailyReportIdsByExternalId(s,c.id,{forceRefresh:l.forceRefresh,admission:f,onFetchStart:l.cursor?void 0:()=>{R=!0,t.readSseStreamAnchor().then(C=>t.getDailyReportIdsFirstPageByExternalId(s,c.id,hr).then(I=>({items:I,streamAnchor:C}))).then(C=>A?.(C),C=>b?.(C))}});if(H.catch(()=>{}),l.cursor){let{items:C,streamAnchor:I,snapshot:V}=await H,$=l.snapshot!==null&&l.snapshot===V;return ha(y,ya(C,$?l.cursor:null,hr,{snapshot:V,restarted:!$,streamAnchor:I}),m,r,S)}let B=(async function*(){let C=await Promise.race([H.then($=>({kind:"full",source:$}),$=>({kind:"full-error",error:$})),w.then($=>({kind:"page",page:$}),()=>({kind:"page-error"}))]),I=null,V=!1;if(C.kind==="full")I=C.source;else if(C.kind==="page"){let{items:$,streamAnchor:U}=C.page;if($.length<hr){yield{kind:"chunk",items:$,nextCursor:null,isLast:!0,total:$.length,streamAnchor:U};return}yield{kind:"chunk",items:$,nextCursor:null,isLast:!1,provisional:!0},V=!0}else if(C.kind==="full-error"&&R){let $=await w.catch(()=>null);$&&$.items.length>0&&(yield{kind:"chunk",items:$.items,nextCursor:null,isLast:!1,provisional:!0})}I===null&&(I=await H),yield*ya(I.items,null,V?fa:hr,{snapshot:I.snapshot,streamAnchor:I.streamAnchor})})();return ha(y,B,m,r,S)};return async(l,c,s,y,m)=>{let S=ca(l.searchParams);if("refused"in S)return ae(s,c,{error:{message:S.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:f}=S;if(f.forceRefresh){let w=a(y,s,c);if(w!==null)return w}let R=yr(s),A=await t.getUserIdByExternalId(y.id),b=await n.admit(A,"ids-stream",R);if(b===null){let w=ae(s,c,{error:{message:fc}},503);for(let[H,B]of Object.entries(we(503)))w.headers.set(H,B);return w}if(R.aborted)return new Response(null,{status:200,headers:Sa(c)});try{return await i(f,y,m,c,R,b,A===null?void 0:o.admissionFor(A,ue.idsStream,R))}catch(w){if(b(),w instanceof He)return pr(s,c);throw w}}};var ba=6e4,gc=1,bc=2e3,Dc=Object.freeze({search:null,reports:null,"search-marks":bc}),Ac=(e,t)=>{let r=Dc[e];return r===null?null:{max:t,maxPerOwner:Xt,maxWaitMs:r}},fr=e=>{let{concurrency:t,route:r,logger:n}=e,o=Qe({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:ba,logger:n,windowFields:()=>`route=${r}`}),a=Ve({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:Ac(r,t)}),i=Object.freeze({status:429,message:cn,headers:Object.freeze({"Retry-After":String(gc)})}),l=Oe({windowMs:ba,tallies:["busy"],writeSuppressed:(c,{count:s,since:y})=>{n.warn(`busy_suppressed count=${s} since=${y} route=${r} concurrency=${t}`)}});return{admit:async(c,s)=>{let y=o.spend(c,r);if(y!==null)return{refusal:y};let m=await a.acquire(c,s);return m!==null?{release:m}:(o.refund(c,1),s.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};var Pa=require("@aiquants/fuzzy-search");var Aa=require("crypto"),ye=require("@aiquants/fuzzy-search/normalize");var Sr=`
5
+ `,gr=4e3,Tc=1,Ta=new Set([8203,8288,65279,173]),Ec=new RegExp(`[${String.fromCodePoint(...Ta)}]`,"gu"),Ic=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),_c=/(\s+)/u,wc=/^\s+$/u,xc=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,Cc=new Set([8205,1536,1537,1538,1539,1540,1541,1757,1807,2192,2193,2274,69821,69837,70082,70083,71999,72001,72250,72324,72325,72326,72327,72328,72329,73030,73474]),vt=e=>e.replace(Ec,""),Ea=e=>{let t=vt(e);if(t.length===e.length)return{text:t,rawIndex:null};let r=new Uint32Array(t.length),n=0;for(let o=0;o<e.length;o++)Ta.has(e.charCodeAt(o))||(r[n++]=o);return{text:t,rawIndex:r}},hn=e=>(0,ye.normalizeText)(e,ye.DEFAULT_NORMALIZE_OPTIONS),Rr=e=>hn(vt(e)),Mc=(0,ye.resolveNormalizeOptions)({...ye.DEFAULT_NORMALIZE_OPTIONS,convertRomaji:!0},"[daily-report] search reading options"),Pc=3,Lc=/^[-ー]+/u,Oc=/[^\p{L}\p{M}]/gu,Nc=/ー{2,}/gu,vc=/\p{Script=Latin}/u,Da=/(?=\p{L})\p{Script=Latin}/u,kc=e=>(0,ye.clusterCountOf)(e.replace(Lc,"").replace(Oc,"").replace(Nc,"\u30FC")),Hc=(e,t)=>{for(let r of t)if(!(0,ye.isAnswerTier)(r.tier)||r.splitTier!==null)throw new Error(`[daily-report] search readings: queryNeedles gave an unfinished needle for the word ${JSON.stringify(e)} (text ${JSON.stringify(r.text)}, tier ${r.tier}, splitTier ${r.splitTier})`)},Ia=e=>{if(!Da.test(e))return[];let t=Rr(e);if(!Da.test(t))return[];let r=(0,ye.queryNeedles)(t,Mc,!1);Hc(t,r);let n=[];for(let o of r){if(o.tier===it.word)continue;let a=Rr(o.text);if(!(a.length===0||a.length>Ie.maxWordLength)&&!(a===t||vc.test(a))&&!(kc(a)<Pc||n.includes(a))&&(n.push(a),n.length===Vr))break}return n},_a=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},Uc=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&_a(e,t-1)?t-2:t-1;return xc.test(String.fromCodePoint(r))&&!Cc.has(e.codePointAt(n))},$c=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!Uc(e,i);)i--;i===a&&(i=a+r,_a(e,i)&&i--,o++),n.push({start:t+a,end:t+i}),a=i}return n.push({start:t+a,end:t+e.length}),{pieces:n,forcedCuts:o}},fn=(e,t)=>{if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let r=[],n=0,o=0,a=0,i=0,l=()=>{i>0&&r.push([{start:a,end:a+i}]),i=0};for(let c of e.split(_c)){let s=o;if(o+=c.length,i+c.length<=t){i===0&&(a=s),i+=c.length;continue}if(l(),wc.test(c))continue;if(c.length<=t){a=s,i=c.length;continue}let y=$c(c,s,t);n+=y.forcedCuts,r.push(y.pieces)}return l(),{chunks:r,forcedCuts:n}},Rn=(e,t)=>{let r=fn(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>hn(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},Sn=(e,t)=>{let r=0;for(let n of e.matchAll(Ic))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},Bc=(e,t)=>{if(e.partialReadings!==null)throw new Error(`[daily-report] search marks: the mapped forms of the piece ${JSON.stringify(t)} carry partial readings`);return e.canonical},wa=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],c=[];for(let s of a){let y=e.slice(s.start,s.end),m=Bc((0,ye.toMappedFormsInto)(y,ye.DEFAULT_NORMALIZE_OPTIONS,new ye.InteriorPairs(0)),y),[S,f]=(0,ye.trimmedRange)(m.text);i+=m.text.slice(S,f);for(let R=S;R<f;R++)l.push(s.start+m.start[R]),c.push(s.start+m.end[R])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let s=0;s<l.length;s++)n.push(l[s]),o.push(c[s])}}return{text:r,start:n,end:o}},br=(e,t=gr)=>{let r=[],n=0;return Sn(vt(e),o=>{let a=Rn(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(Sr),forcedCuts:n}},xa=e=>e.filter(t=>t.length>0).join(Sr),Fc=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
6
+ `)},Vc=[`\u3067\u3093${String.fromCodePoint(8203)}\u3077\u3093 \uFF83\uFF9E\uFF9D\uFF8C\uFF9F\uFF9D\r
7
+ \u30C7\u30F3\u30D7\u30F3`,"\u30DD\u30C6\u30C8-25kg \u30A2--1 \u30FC\u30FC\u30E1\u30F3 \u4F50\u3005\u6728","\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CA",`\uFF71\uFF72\uFF73\uFF74\uFF75\uFF76\uFF9E\uFF77\uFF9E\uFF78\uFF9E\uFF79\uFF9E\uFF7A\uFF9E${String.fromCodePoint(8232)}\u6B21\u306E\u884C`],Yc=()=>{let e=(0,Aa.createHash)("sha256");e.update(JSON.stringify(ye.DEFAULT_NORMALIZE_OPTIONS));for(let t of["","\u30A2","\u4F50"," "])e.update("\0"),e.update(hn(Fc(t)));return e.update("\0"),e.update(JSON.stringify(Vc.map(t=>br(t,8)))),`dr-search-v${Tc};fz=${e.digest("hex").slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`},yn=null,Ca=()=>(yn===null&&(yn=Yc()),yn);var qc=/^-+/u,Wc=/\s+/u,Ma=e=>{let t=qc.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},jc=(e,t)=>{let r=[...Ma(e).map(n=>({text:n,tier:it.word})),...t.flatMap(n=>Ma(n).map(o=>({text:o,tier:it.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},zc=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),gn=(e,t)=>{if(e.length>Ie.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of(0,Pa.parseQuerySets)(vt(e),t).sets){let i=[],l=new Set;for(let s of a.split(Wc)){let y=Rr(s);if(y.length===0)return{ok:!1,reason:"blank-word"};if(y.length>Ie.maxWordLength)return{ok:!1,reason:"word-too-long"};let m=jc(y,Ia(s)),S=zc(m);l.has(S)||(l.add(S),i.push({alternatives:m}))}if(i.length>Ie.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let c=JSON.stringify([...l].sort());n.has(c)||(n.add(c),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>Ie.maxSets?{ok:!1,reason:"too-many-sets"}:o>Ie.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},kt=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var Wa=require("@aiquants/sse"),ot=require("@aiquants/sse/server");var At=(e,t)=>{let r=e.message.data;if(!r)return{entry:{id:e.id,message:null},json:void 0};let n;try{n=JSON.parse(r)}catch(i){return t.error(`SSE message ${e.id} is not JSON:`,i),{entry:{id:e.id,message:null},json:void 0}}let o=Jn.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n,text:r});return{entry:Object.freeze({id:e.id,message:a}),json:n}},Gc=["externalComments","postedComments"],La=new WeakMap,Kc=e=>{let t=La.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return La.set(e,r),r},Oa=e=>{let{recipientRawUserId:t,...r}=e;return r},Na=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=Kc(e);if(t){if(n.commentsRedacted===null){let o=Oa(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(Gc.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(Oa(r))),n.recipientRemoved};var $a=require("@aiquants/sse"),Ba=require("@aiquants/sse/shared-source");var lt="daily-report:ids:",ct="daily-report:business-date:",Dr=(e,t)=>`${e}st:${t}`,bn=e=>`${lt}user:${e}:`,va=(e,t)=>Dr(bn(e),t),Jc=e=>`${ct}${e}:`,ka=(e,t)=>Dr(Jc(e),t),Ht=e=>`daily-report:date:${e}:user:`,Tt=(e,t)=>`${Ht(e)}${t}:`,Ha=(e,t,r)=>Dr(Tt(e,t),r),qe=e=>`daily-report:detail:${e}:user:`,Ar=(e,t)=>`${qe(e)}${t}:`,Ua=(e,t,r)=>Dr(Ar(e,t),r);var Ze=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},Qc=5e3,Xc=tr,Et=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=Re(t.logger,1,"SseReader"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return(0,Ba.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:$a.systemSseRuntime,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",i=>{this._logger.error("Redis client error:",i)});let o=!1,a=this._readLoop(n,t,r,()=>o);return async()=>{if(o=!0,n.isOpen)try{await n.quit()}catch{}await a}}async _readLoop(t,r,n,o){let a=n;try{for(;!o()&&t.isOpen;){let i=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:Qc,COUNT:Xc});if(i)for(let l of i)for(let c of l.messages){a=c.id;let{entry:s,json:y}=At(c,this._logger);this._invalidateCaches(y),r.next(s)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(lt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(qe(n))}};var $t=require("drizzle-orm");var Zc="",eu=64,tu=e=>e.toLowerCase(),ru=e=>e.trim().toLowerCase();function Fa(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=ru(r);n.length>0&&t.add(n)}return t}function Ne(e,t){return e===null?!0:t==null?!1:e.has(tu(t))}function ve(e){return e!==null&&e.size===0}function Bt(e,t){if(t!==null)return t.size===0?$t.sql`1 = 0`:(0,$t.inArray)($t.sql`LOWER(${e})`,[...t])}var It,_t,Ut=class Ut{constructor(t,r){vr(this,It);vr(this,_t);kr(this,It,t),kr(this,_t,r)}get visible(){return Mt(this,It)===null?null:new Set(Mt(this,It))}get commentable(){return Mt(this,_t)===null?null:new Set(Mt(this,_t))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Fa(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new Ut(n,n);let a=Fa(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new Ut(n,i)}static unrestricted(t){return new Ut(null,null)}};It=new WeakMap,_t=new WeakMap;var Ce=Ut;function Ft(e){let t=Va(e.visible),r=Va(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Va(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Zc);if(t.length<=eu)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 ja=Object.freeze({...Ot,route:"sse",frameworkDataRefusal:nr}),Ya=864e5,nu={baseMs:2e3,jitterMs:8e3},Dn=6e4,Er=tr,za=JSON.stringify({type:"connected"}),qa="0-0",ou=(e,t,r,n)=>{if(r===null&&n===null)return!0;let o=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Ne(r,e.report.sourceType);case"comment-add":case"comment-delete":return Ne(n,o??"Internal");case"report-delete":return Ne(r,o)}},au=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Ne(t,e.report.sourceType),iu=(e,t)=>{e.writeEvent({event:null,id:t,data:za})},su=(e,t,r)=>{let{message:n}=t;if(n===null)return;let{parsed:o,published:a}=n,i=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((o.type==="status-update"||i!==void 0)&&i!==r.internalUserId||!ou(o,a,r.visibleSet,r.commentableSet)){iu(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Na(n,au(o,r.commentableSet))})},Ga=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:c}=e,s=async(y,m)=>{let{request:S,internalUserId:f,cursor:R}=m,A=m.initialScope.visible,b=m.initialScope.commentable,w=0,H=setInterval(()=>{let W=++w;n(S,"refresh").then(ne=>{W===w&&(A=ne.visible,b=ne.commentable)})},Dn);y.onClose(()=>clearInterval(H));let B=R===null?qa:R,C=R!==null&&o!==void 0,I=[],V=null,$=W=>{Ze(W.id,B)||(B=W.id,su(y,W,{internalUserId:f,visibleSet:A,commentableSet:b}))},U=async(W,ne)=>{let[ee]=await W.xRange(i,"-","+",{COUNT:1});return ee!==void 0&&!Ze(ee.id,ne)},le=async(W,ne)=>{if(await U(W,ne))return!1;let ee=ne;for(;;){let ie=await W.xRange(i,ee,"+",{COUNT:Er}),me=ie[0];if(me!==void 0&&me.id!==ee&&await U(W,ee))return!1;for(let je of ie){if(V!==null&&Ze(V,je.id))return!0;Ze(je.id,B)||$(At(je,c).entry)}let fe=ie.at(-1);if(ie.length<Er||fe===void 0||y.isClosed())return!0;ee=fe.id}},de=a.subscribe(W=>{if(!C){$(W);return}Ze(W.id,B)||(V===null&&(V=W.id),I.push(W))},W=>{c.error(`[SSE:${f}] Fan-Out reader error:`,W),y.close()});if(y.onClose(de),R===null){await a.ready();try{let W=await o?.getClient();if(W){let ne=await W.xRevRange(i,"+","-",{COUNT:1});ne.length>0&&!Ze(ne[0].id,B)&&(B=ne[0].id)}}catch{}}if(y.writeEvent({event:null,id:B===qa?null:B,data:za}),(0,ot.startSseHeartbeat)(y,{intervalMs:jn,retry:nu,runtime:Wa.systemSseRuntime}),R===null||o===void 0)return;await a.ready();let Se=await o.getClient();if(Se===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await le(Se,R)){y.writeRetry(Ya),y.writeEvent({event:"resync-required",id:null,data:""}),y.close();return}C=!1;for(let W of I.splice(0))$(W)};return async({request:y,params:m})=>{let S,f=()=>{let A=new Headers;S!==void 0&&A.append("Set-Cookie",S);for(let[b,w]of Object.entries(Fe))A.set(b,w);return A},R=A=>(0,ot.terminalStreamResponse)(A,{data:"",retryMs:Ya,headers:f()});try{let A=await t(y,{failureRedirect:null});S=A.cookie;let{user:b}=A;if(!b)return R("auth-required");let w=await r.getUserIdByExternalId(b.id);if(!w)return R("forbidden");if(m.endpoint!=="updates")return new Response("Not Found",{status:404,headers:f()});let H=(0,ot.readLastEventId)(y,zn);if(H!==null&&!Gn(H))return c.warn(`[SSE:${w}] malformed resume cursor; asking the client to resync`),R("resync-required");let B=yr(y),C=await l.admit(w,"sse",B);if(C===null){let V=f();for(let[$,U]of Object.entries(we(503)))V.set($,U);return new Response("Too many streams",{status:503,headers:V})}let I=!1;try{let V=await n(y,"initial");return(0,ot.createSseResponse)({requestSignal:B,headers:f(),onError:($,U)=>c.error(`[SSE:${w}] ${U} failed:`,$),produce:$=>(I=!0,$.onClose(C),s($,{request:y,internalUserId:w,cursor:H,initialScope:V}))})}finally{I||C()}}catch(A){if(A instanceof Response)throw A;let b=A instanceof Error?A:new Error(String(A));return c.error(`500 sse name=${b.name} message=${b.message}`),new Response("Internal Server Error",{status:500,headers:f()})}}};var Ka=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...Fe});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},lu=Object.freeze({...Ot,route:"api",frameworkDataRefusal:({params:e})=>en(e.endpoint)&&tt[e.endpoint].body==="stream"?nr():null}),cu=Object.freeze({...Ot,route:"action"}),uu=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),Xa=6e4,Za=5,du=Za*Math.ceil(Xa/500),mu=2,pu=6,yu=6e4,hu=Za*mu*pu,fu=2,Ru=10,Su=2,gu=10,Ja=(e,t)=>Math.max(e,Xt)*t,Tn=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},An=(e,t,r)=>Tn(ae(e,t,{error:{message:r.message}},r.status),r.headers),Qa=e=>Tn(Ke(e,null,503),we(503));function Ir(e){mr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:te("service.titleMaxLength",r.titleMaxLength,1)},c=e.loginRedirectPath??"/auth/login",s=Re(e.logger,3,"API"),y=Re(e.logger,3,"Visibility"),m=Re(e.logger,1,"SSE"),S=Re(e.logger,1,"Attachment"),f=Re(e.logger,2,"Isolation"),R=Re(e.logger,2,"Action"),A=Re(e.logger,2,"Search"),b=Re(e.logger,2,"Refresh"),w=Re(e.logger,2,"Streams"),H=Re(e.logger,2,"Reads"),B=Qe({reason:"refresh_rate_limit",limitPerWindow:hu,windowMs:yu,logger:b,windowFields:()=>"route=api"}),C=da(w),I=la(H),V=async(v,N,E,F,j)=>{let K=await r.getUserIdByExternalId(N.id);try{return await j(K===null?void 0:I.admissionFor(K,v,E.signal))}catch(J){if(J instanceof He)return pr(E,F);throw J}},$=(v,N,E,F)=>{let j=B.spend(N.id,`endpoint=${v}`);return j===null?null:An(E,F,j)},U=async(v,N="initial")=>{let E=e.resolveVisibleSourceTypes;if(!E)return Ce.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let F=await E(v,{reason:N});return F==null?Ce.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):Ce.restrictTo(F)}catch(F){return y.error("resolveVisibleSourceTypes threw; failing closed (deny all)",F),Ce.restrictTo([])}},le=async({request:v})=>{let{user:N,cookie:E}=await t(v,{failureRedirect:c}),F=new Headers;E&&F.append("Set-Cookie",E);let j=await r.getUserIdByExternalId(N.id),K=j?n(j):null;return{data:{user:N,userId:K},headers:F}},de=r.searchLimits===null?null:fr({...r.searchLimits,route:ue.search,logger:A}),Se=r.searchLimits===null?null:fr({concurrency:Ja(r.searchLimits.concurrency,fu),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Ru,route:ue.reports,logger:A}),W=r.searchLimits===null?null:fr({concurrency:Ja(r.searchLimits.concurrency,Su),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*gu,route:ue.searchMarks,logger:A}),ne={[ue.businessDate]:async(v,N,E,F,j)=>{let K=v.searchParams.get(Te.businessDate),J=K===null?null:St(K);if(J===null)return ae(E,N,{error:{message:"Invalid business date"}},400);let z=Lt(v.searchParams.get(Te.forceRefresh));if(z===null)return ae(E,N,{error:{message:"Invalid forceRefresh"}},400);let X=z?$(ue.businessDate,F,E,N):null;return X!==null?X:V(ue.businessDate,F,E,N,async P=>{let Z=await r.getDailyReportsByBusinessDateByExternalId(j,J,F.id,{forceRefresh:z,admission:P});return ae(E,N,{businessDate:J,reports:Z},200)})},[ue.idsStream]:ga({service:r,logger:s,streamSlots:C,missGate:I,refuseForcedRead:(v,N,E)=>$(ue.idsStream,v,N,E)}),[ue.report]:async(v,N,E,F,j)=>{let K=Ue(v.searchParams.get(Te.reportHubId));if(K===null)return ae(E,N,{error:{message:"Invalid reportHubId"}},400);let J=Lt(v.searchParams.get(Te.forceRefresh));if(J===null)return ae(E,N,{error:{message:"Invalid forceRefresh"}},400);let z=J?$(ue.report,F,E,N):null;return z!==null?z:V(ue.report,F,E,N,async X=>{let P=await r.getDailyReportDetailByIdByExternalId(j,K,F.id,{snapshot:!0,forceRefresh:J,admission:X});return P?ae(E,N,{report:P},200):ae(E,N,{error:{message:"Report not found"}},404)})},[ue.search]:async(v,N,E,F,j)=>{if(de===null)return ae(E,N,{error:{message:"Unknown endpoint"}},404);let K=v.searchParams.get(Te.searchQuery),J=Xr(v.searchParams.get(Te.searchCombine));if(K===null||J===null)return ae(E,N,{error:{message:"Invalid search request"}},400);let z=gn(K,J);if(!z.ok)return ae(E,N,{error:{message:"Invalid search query",reason:z.reason}},400);let X=kt(z.plan),P=await r.getUserIdByExternalId(F.id);if(!P)return ae(E,N,Yr([],X),200);let Z=await de.admit(P,E.signal);if("refusal"in Z)return An(E,N,Z.refusal);try{let De=await r.searchDailyReports(j,P,z.plan);return ae(E,N,Yr(De,X),200)}finally{Z.release()}},[ue.reports]:async(v,N,E,F,j)=>{if(Se===null)return ae(E,N,{error:{message:"Unknown endpoint"}},404);let K=Zr(v.searchParams.get(Te.reportIds));if(K===null)return ae(E,N,{error:{message:"Invalid ids"}},400);let J=await r.getUserIdByExternalId(F.id);if(!J)return ae(E,N,{reports:[]},200);let z=await Se.admit(J,E.signal);if("refusal"in z)return An(E,N,z.refusal);try{let X=await r.getDailyReportDetailsByIdsByExternalId(j,K,F.id);return ae(E,N,{reports:X},200)}finally{z.release()}},[ue.searchMarks]:async(v,N,E,F,j)=>{if(W===null)return Ke(N,{error:{message:"Unknown endpoint"}},404);let K=v.searchParams.get(Te.searchQuery),J=Xr(v.searchParams.get(Te.searchCombine));if(K===null||J===null)return Ke(N,{error:{message:"Invalid search request"}},400);let z=gn(K,J);if(!z.ok)return Ke(N,{error:{message:"Invalid search query",reason:z.reason}},400);let X=Zr(v.searchParams.get(Te.reportIds));if(X===null)return Ke(N,{error:{message:"Invalid ids"}},400);let P=await r.getUserIdByExternalId(F.id);if(!P)return Ke(N,{wordsDigest:Qt(kt(z.plan)),reports:[]},200);let Z=await W.admit(P,E.signal);if("refusal"in Z)return E.signal.aborted?Qa(N):Tn(Ke(N,{error:{message:Z.refusal.message}},Z.refusal.status),Z.refusal.headers);try{let De=await r.markDailyReportSearchHits(j,P,z.plan,X,{signal:E.signal});return E.signal.throwIfAborted(),Ke(N,De,200)}catch(De){if(E.signal.aborted&&De===E.signal.reason)return Qa(N);throw De}finally{Z.release()}}},ee=async({request:v,params:N})=>{let{user:E,cookie:F}=await t(v,{failureRedirect:null}),j=F??null;if(!E)return ae(v,j,{error:{message:"Unauthorized"}},401);let K=N.endpoint;if(!en(K))return ae(v,j,{error:{message:"Unknown endpoint"}},404);let J=io[tt[K].body];if(!J.includes(v.method)){let X=ae(v,j,{error:{message:"Method not allowed"}},405);return X.headers.set("Allow",J.join(", ")),X}let z=ce();try{let X=new URL(v.url),P=await U(v),Z=await ne[K](X,j,v,E,P);return tt[K].body==="json"&&s.debug(`${Z.status} endpoint=${K} etag_match=${Z.status===304}`),Z}catch(X){let P=ce()-z,Z=X instanceof Error?X:new Error(String(X));return s.error(`500 endpoint=${K} elapsed=${P}ms name=${Z.name} code=${"code"in Z?Z.code:"N/A"} message=${Z.message}`,Z),ae(v,j,{error:{message:"Internal Server Error"}},500)}},ie=ao(R),me=Qe({reason:"rate_limit",limitPerWindow:du,windowMs:Xa,logger:R,windowFields:()=>"route=action"}),fe=async(v,N,E,F,j)=>{let{clientTempId:K}=v;if(v.intent==="create"){let P=await r.createDailyReport(N,v.businessDate,K);return j(v,P.reportHubId,{report:P})}let{reportHubId:J,businessDate:z}=v,X=async(P,Z)=>{try{let De=await Z(P.value);return j(P,J,{updatedStatus:{isStarred:De.isStarred,isRead:De.isRead},operationTimestamp:P.operationTimestamp})}catch(De){if(De instanceof Error&&De.message==="Not Found")return F({error:"Report not found"},{status:404});throw De}};switch(v.intent){case"update":try{return await r.updateDailyReport(J,N,v.changes,K),j(v,J,{})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return F({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return F({error:"Report not found"},{status:404})}throw P}case"publish":try{let P=await r.publishDailyReport(J,N,K);return j(v,J,{report:P})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return F({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return F({error:"Report not found"},{status:404})}throw P}case"delete":try{return await r.deleteDailyReport(J,N,K),j(v,J,{})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return F({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return F({error:"Report not found"},{status:404})}throw P}case"toggleStar":return await X(v,P=>r.setStarStatus(E,N,J,z,P,K));case"toggleRead":return await X(v,P=>r.setReadStatus(E,N,J,z,P,K));case"addComment":try{let P=await r.addComment(E,N,J,v.content,z,K);return j(v,J,{newComment:P})}catch(P){if(P instanceof Error){if(P.message==="Not Found")return F({error:"Report not found"},{status:404});if(P.message.startsWith("Comments are restricted"))return F({error:"Comments are restricted for this report"},{status:403})}throw P}case"deleteComment":try{return await r.deleteComment(E,N,J,v.commentId,z,K),j(v,J,{deletedCommentId:v.commentId})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return F({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return F({error:"Comment not found"},{status:404})}throw P}}},je=async({request:v,params:N})=>{let{user:E,cookie:F}=await t(v,{failureRedirect:null}),j=(z,X)=>Ka(z,{...X,setCookie:F}),K=(z,X,P)=>Ka(uu(z,X,P),{setCookie:F});if(!E)return j({error:"Unauthorized"},{status:401});let J=ce();try{if(N.endpoint!==ue.action)return j({error:"Unknown endpoint"},{status:404});let z=me.spend(E.id,"action");if(z!==null)return j({error:z.message},{status:z.status,headers:z.headers});let X=await oo(v,l);if("refusal"in X){let{refusal:yt}=X;return yt.status===413&&ie(yt.measuredBy),j({error:yt.error},{status:yt.status})}let{command:P}=X;if(P.intent==="clearCache"&&!e.enableDevCacheClear)return j({error:"Invalid intent"},{status:400});let Z=await r.getUserIdByExternalId(E.id);if(!Z)return j({error:"User not found"},{status:404});let De=await U(v);return P.intent==="clearCache"?(await r.clearCache(),j({status:"OK",intent:"clearCache"})):await fe(P,Z,De,j,K)}catch(z){if(z instanceof Response)throw z;let X=ce()-J,P=z instanceof Error?z:new Error(String(z));return s.error(`500 action elapsed=${X}ms name=${P.name} message=${P.message}`,P),j({error:"Internal Server Error"},{status:500})}},re=Ga({authenticate:t,service:r,resolveViewerScope:U,redis:o,sseReader:a,streamKey:i,streamSlots:C,logger:m}),Me=na({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:U,logger:S}),ke=ho(f),Ae=(v,N)=>async E=>{let F=po(E.request)?v.frameworkDataRefusal(E):null;if(F!==null)throw F;return yo(E.request,v)?(ke(v.route,E.request),v.crossSiteRejection()):N(E)};return{index:{loader:le},api:{loader:Ae(lu,ee),action:Ae(cu,je)},sse:{loader:Ae(ja,re)},attachment:{loader:Ae(ra,Me)}}}var xt=require("@aiquants/mssql"),g=require("drizzle-orm");var ut=require("drizzle-orm"),_r=(e,t,r,n)=>{if(r.length===0)return;let{hub:o,hubLabel:a,label:i}=e,l=n==="author-or-authorless"?ut.sql`${o.userId} = ${t} OR ${o.userId} IS NULL`:ut.sql`${o.userId} = ${t}`,c=ut.sql.join(r.map(s=>ut.sql`${s}`),ut.sql`, `);return ut.sql`(${l} OR NOT EXISTS (SELECT 1 FROM ${a} INNER JOIN ${i} ON ${i.id} = ${a.labelId} WHERE ${a.hubId} = ${o.id} AND ${i.name} IN (${c})))`};var ei=(e,t,r,n)=>Ne(n.commentable,t)||e.authorUserId!==null&&e.authorUserId===r;var bu=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],Du=["document","comment"],Au=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion"],Tu=["hubId","ordinal","authorUserId","commentText"],En=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},ti=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw Hr(e,n,r)},ri=(e,t,r)=>{if(typeof t!="object"||t===null)throw se(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw se(`${e}.${o}`,"a column",n[o])},ni=(e,t)=>{if(!En(e))throw se("search","a plain object",e);ti("search key",e,bu);let{tables:r}=e;if(!En(r))throw se("search.tables","a plain object with document and comment",r);ti("search.tables key",r,Du),ri("search.tables.document",r.document,Au),ri("search.tables.comment",r.comment,Tu);let n=new Map;if(e.externalSourceTexts!==void 0){if(!En(e.externalSourceTexts))throw se("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw Hr("search.externalSourceTexts key",o,t);if(typeof a!="function")throw se(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:te("search.concurrency",e.concurrency,1),rateLimitPerMinute:te("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var dt=e=>{let t=typeof e=="object"&&e!==null?e.recordset:void 0;if(!Array.isArray(t))throw new Error("[daily-report] search: the database result has no recordset");return t},mt=(e,t)=>{let r=typeof e=="string"?Ue(e):typeof e=="number"&&gt(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},wt=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};var q=require("drizzle-orm");var Eu=/[[%_]/gu,Iu=e=>e.replace(Eu,t=>`[${t}]`),oi=e=>`%${Iu(e)}%`;var Be=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),pt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),Ee=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),G=e=>q.sql`${q.sql.identifier(e.name)}`,ai=e=>q.sql.join(e.map(t=>q.sql`${t}`),q.sql`, `),ii=(e,t)=>q.sql`SELECT ${G(e.id)} AS ${q.sql.identifier(Ee.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${ai(t)}) ORDER BY ${e.id}`,_u=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(m=>oi(m.text)),l=q.sql.join(i.map(m=>q.sql`${o.searchText} LIKE ${m}`),q.sql` OR `),c=q.sql.join(i.map(m=>q.sql`${a.commentText} LIKE ${m}`),q.sql` OR `),s=Bt(n.sourceType,r.scope.commentable),y=s===void 0?q.sql``:q.sql` AND (${s} OR ${a.authorUserId} = ${r.userId})`;return q.sql`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${c})${y}))`},si=(e,t,r)=>q.sql`(${q.sql.join(t.words.map(n=>_u(e,n,r)),q.sql` AND `)})`,li=(e,t,r,n)=>{let{hub:o}=e,a=[q.sql`${o.deletedAt} IS NULL`],i=_r(e,t.userId,r,"author");i!==void 0&&a.push(i);let l=Bt(o.sourceType,t.scope.visible);return l!==void 0&&a.push(l),n!==void 0&&a.push(q.sql`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},ci=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=li(e,r,n,o),c=t.combine==="intersection"?q.sql` AND `:q.sql` OR `;return l.push(q.sql`(${q.sql.join(t.sets.map(s=>si(e,s,r)),c)})`),q.sql`SELECT ${G(a.id)} AS ${q.sql.identifier(Be.reportHubId)}, CONVERT(char(10), ${G(a.businessDate)}, 23) AS ${q.sql.identifier(Be.businessDate)}, ${G(a.sourceType)} AS ${q.sql.identifier(Be.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${q.sql.join(l,q.sql` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},ui=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=q.sql.join(t.sets.map((c,s)=>q.sql`(CASE WHEN ${si(e,c,r)} THEN ${2**s} ELSE 0 END)`),q.sql` + `);return q.sql`SELECT ${G(a.id)} AS ${q.sql.identifier(pt.reportHubId)}, ${l} AS ${q.sql.identifier(pt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${q.sql.join(li(e,r,n,o),q.sql` AND `)}`},di=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(c=>({[n.hubId.name]:c.hubId,[n.searchText.name]:c.searchText,[n.sourceDigest.name]:c.sourceDigest,[n.normalizerVersion.name]:r}))),i=JSON.stringify(t.flatMap(c=>c.comments.map(s=>({[o.hubId.name]:c.hubId,[o.ordinal.name]:s.ordinal,[o.authorUserId.name]:s.authorUserId,[o.commentText.name]:s.commentText})))),l=JSON.stringify(t.map(c=>c.hubId));return q.sql`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${G(n.hubId)} bigint, ${G(n.searchText)} nvarchar(max), ${G(n.sourceDigest)} char(64), ${G(n.normalizerVersion)} varchar(64))) AS s ON t.${G(n.hubId)} = s.${G(n.hubId)}
8
+ WHEN MATCHED THEN UPDATE SET t.${G(n.searchText)} = s.${G(n.searchText)}, t.${G(n.sourceDigest)} = CONVERT(binary(32), s.${G(n.sourceDigest)}, 2), t.${G(n.normalizerVersion)} = s.${G(n.normalizerVersion)}, t.${G(n.indexedAt)} = SYSUTCDATETIME()
9
+ WHEN NOT MATCHED THEN INSERT (${G(n.hubId)}, ${G(n.searchText)}, ${G(n.sourceDigest)}, ${G(n.normalizerVersion)}) VALUES (s.${G(n.hubId)}, s.${G(n.searchText)}, CONVERT(binary(32), s.${G(n.sourceDigest)}, 2), s.${G(n.normalizerVersion)});
10
10
  DELETE FROM ${o} WHERE ${o.hubId} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${l}));
11
- INSERT INTO ${o} (${q(o.hubId)}, ${q(o.ordinal)}, ${q(o.authorUserId)}, ${q(o.commentText)}) SELECT ${q(o.hubId)}, ${q(o.ordinal)}, ${q(o.authorUserId)}, ${q(o.commentText)} FROM OPENJSON(${i}) WITH (${q(o.hubId)} bigint, ${q(o.ordinal)} int, ${q(o.authorUserId)} bigint, ${q(o.commentText)} nvarchar(max));`},Ia=(e,t)=>J.sql`SELECT ${q(e.hubId)} AS ${J.sql.identifier(Se.hubId)}, LOWER(CONVERT(char(64), ${q(e.sourceDigest)}, 2)) AS ${J.sql.identifier(Se.sourceDigest)}, ${q(e.normalizerVersion)} AS ${J.sql.identifier(Se.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${Gr(t)})`,Ea=(e,t,r)=>J.sql`SELECT TOP (${r}) ${q(e.id)} AS ${J.sql.identifier(Se.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var wa=e=>({search:async(t,r)=>Ue(r.scope.visible)?[]:pt(await t.execute(Ta(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=ht(o[ve.sourceType],ve.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${ve.sourceType} is null`);return{reportHubId:yt(o[ve.reportHubId],ve.reportHubId),businessDate:ht(o[ve.businessDate],ve.businessDate),sourceType:a}})});var Be=require("@aiquants/mssql"),Zr=require("drizzle-orm");var _a=require("crypto");var Qr=e=>e===null?"n;":`s${e.length}:${e}`,yc=e=>{let t=(0,_a.createHash)("sha256");t.update(`F${e.fields.length};`);for(let[r,n]of e.fields)t.update(Qr(r)+Qr(n));return t.update(`C${e.comments.length};`),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${Qr(r.text)}`)}),t.digest("hex")},Xr=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=ar(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=ar(o.text);t+=a.forcedCuts,a.text.length!==0&&n.push({ordinal:n.length,authorUserId:o.authorUserId,commentText:a.text})}return{hubId:e.hubId,searchText:zo(r),comments:n,sourceDigest:yc(e),forcedCuts:t}};var xa=e=>{let t=async(p,s)=>{let f=[];for(let m of(0,Be.chunk)(s,Be.MAX_IN_LIST))for(let D of pt(await p.execute(Da(e.hub,m))))f.push(yt(D[Se.hubId],Se.hubId));return f},r=async(p,s)=>{for(let f of(0,Be.chunk)(s,Be.MAX_IN_LIST))await p.execute(Aa(e.tables,f,e.normalizerVersion))},n=async(p,s)=>{let f=new Map;for(let m of(0,Be.chunk)(s,Be.MAX_IN_LIST))for(let D of pt(await p.execute(Ia(e.tables.document,m))))f.set(yt(D[Se.hubId],Se.hubId),{sourceDigest:ht(D[Se.sourceDigest],Se.sourceDigest),normalizerVersion:ht(D[Se.normalizerVersion],Se.normalizerVersion)});return f},o=async(p,s,f)=>pt(await p.execute(Ea(e.hub,s,f))).map(m=>yt(m[Se.hubId],Se.hubId)),a=async(p,s)=>{let f=await t(p,[...new Set(s)].sort((D,h)=>D-h));if(f.length===0)return;let m=(await e.loadSources(p,f)).map(Xr);m.length>0&&await r(p,m)},i=p=>e.inTransaction(async s=>{await s.execute(Zr.sql`SET DEADLOCK_PRIORITY LOW`);let f=await t(s,p),m=await n(s,f),D=(await e.loadSources(s,f)).map(Xr),h=D.filter(b=>{let g=m.get(b.hubId);return g===void 0||g.sourceDigest!==b.sourceDigest||g.normalizerVersion!==e.normalizerVersion});return h.length>0&&await r(s,h),await s.execute(Zr.sql`SET DEADLOCK_PRIORITY NORMAL`),{scanned:D.length,written:h.length,forcedCuts:D.reduce((b,g)=>b+g.forcedCuts,0)}});return{writeHubs:a,reconcile:async(p,s)=>{let{batchSize:f,hubIds:m,signal:D,onProgress:h}=s;de("reconcileSearchIndex: batchSize",f,1,Be.MAX_IN_LIST);let b=ce(),g=m===void 0?null:(0,Be.chunk)([...new Set(m)].sort((B,C)=>B-C),f),A={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let B=0;;B++){D?.throwIfAborted();let C=g===null?await o(p,A.lastHubId===null?0:A.lastHubId,f):g[B];if(C===void 0||C.length===0)break;let k=await i(C);A={scanned:A.scanned+k.scanned,written:A.written+k.written,skipped:A.skipped+k.scanned-k.written,forcedCuts:A.forcedCuts+k.forcedCuts,lastHubId:C[C.length-1]},h?.(A)}return{...A,elapsedMs:ce()-b}}}};var je=e=>(0,d.getColumns)(e),Ca=Ut([]),De=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),p=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${p}:${s}`},fc=e=>{let{length:t}=e;if(t===void 0)throw ie("tables.hub.title","a character column with a declared length",t);return de("tables.hub.title.length",t,1)},Pa=e=>e===""?null:e,Rc=Object.freeze([]),en=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},dr=(e,t)=>e.get(t)??Rc,Ma=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(nr);function mr(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:p}=e,{hub:s,internal:f,comment:m,label:D,hubLabel:h,userStatus:b}=r,g=e.externalSources??[],A=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],B=A[0]??"\u4E0B\u66F8\u304D",C=he(e.logger,1,"[DailyReportService]");er(e);let k=Po(e.attachments),M=fc(s.title),I=c=>(0,ft.runWithTransactionRetry)(u=>t.transaction(y=>u(()=>c(y))),e.transactionRetry),V=e.search===void 0?null:ba(e.search,g.map(c=>c.sourceType)),Q=V===null?null:wa({tables:{hub:s,hubLabel:h,label:D,search:V.tables},draftLabelNames:A}),H=null,se=()=>{if(V===null)return null;if(H===null){let c=V.externalSourceTexts;H=xa({hub:s,tables:V.tables,loadSources:(u,y)=>hi(u,y,c),inTransaction:I,normalizerVersion:Wo()})}return H},be=e.idsTtlMs??18e4,ue="daily-report:ids:epoch",j=e.businessDateTtlMs??3e5,Z="daily-report:date-epoch:",ne="daily-report:detail-epoch:",oe=`${e.streamKey??"daily-report:sse-stream"}:v2`,ye=e.streamMaxLen??1e4,ee=c=>p.incrementEpoch(c),x=c=>Ct(s.sourceType,c),v=async(c,u)=>{let y=await i?.getClient();if(!y){C.warn(`[SSE] Redis client unavailable (${u})`);return}let R=JSON.stringify(c),T=Buffer.byteLength(R);if(T>6356992){C.warn(`[SSE] Event too large (${u}): ${T} bytes > ${6356992}; not published`);return}let E=ce();try{await y.xAdd(oe,"*",{data:R},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:ye}});let w=ce()-E;w>1e3&&C.warn(`[SSE] Slow publish (${u}): ${w}ms`)}catch(w){C.error(`[SSE] Redis publish failed (${u}):`,w)}},N=async()=>{try{let c=await i?.getClient();if(c===void 0)return null;let[u]=await c.xRevRange(oe,"+","-",{COUNT:1});return u===void 0?null:u.id}catch(c){return C.error("SSE stream anchor read failed",c),null}},$=c=>c==null||c===""?null:/^\d+$/.test(c)?a(Number(c)):c,Y=()=>{let c={};for(let u of g)c[`ext_${u.sourceType}`]=je(u.table);return c},G=c=>{let u=c;for(let y of g)u=u.leftJoin(y.table,(0,d.and)((0,d.eq)(s.sourceType,y.sourceType),(0,d.eq)(s.sourceIdNum,y.idColumn)));return u},F=c=>{let{hub:u,internal:y}=c,R=u.summary,T=[],E=null,w=null,U=null,P=null,W=null,O=null,re=[],K=g.find(le=>le.sourceType===u.sourceType),te=K?c[`ext_${K.sourceType}`]:void 0;if(K&&te){let le=K.mapRow(te);le.content!==void 0&&(R=le.content),le.employeeName!==void 0&&(O=le.employeeName),le.category!==void 0&&(E=le.category),le.creationCategory!==void 0&&(w=le.creationCategory),le.visitTimeFrom!==void 0&&(U=le.visitTimeFrom),le.visitTimeTo!==void 0&&(P=le.visitTimeTo),le.customerName!==void 0&&(W=le.customerName),le.interviewers!==void 0&&(T=le.interviewers),le.externalComments!==void 0&&(re=le.externalComments)}else u.sourceType==="Internal"&&y&&(R=y.body);return{content:R,author:c.creatorName??$(u.createdBy)??"",employeeName:O??c.creatorName??$(u.createdBy),updatedBy:$(u.updatedBy),category:E,creationCategory:w,visitTimeFrom:U,visitTimeTo:P,customerName:W,interviewers:T,externalComments:re}},z=(c,u,y)=>{let{hub:R}=u,T=F(u),E=(u.labels??[]).map(O=>({id:O.id,name:O.name,color:O.color})),w=u.postedCommentRows??[],U=xe(c.commentable,R.sourceType),P=T.creationCategory?A.includes(T.creationCategory):!1,W=tt?.[0]??null;return P&&W&&!E.some(O=>O.id===W)&&E.push({id:W,name:B,color:null}),{reportHubId:R.id,date:De(R.businessDate,"YYYY-MM-DD"),author:T.author,userId:R.userId?a(R.userId):"",sourceType:R.sourceType??"Internal",createdAt:De(R.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:De(R.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:T.updatedBy,employeeName:T.employeeName,category:T.category,creationCategory:T.creationCategory,visitTimeFrom:T.visitTimeFrom,visitTimeTo:T.visitTimeTo,customerName:T.customerName,interviewers:T.interviewers,subject:R.title,content:T.content,externalComments:U?T.externalComments:[],isRead:u.isRead??!1,isStarred:u.isStarred??!1,labels:E,postedComments:w.filter(O=>fa({authorUserId:O.userId},R.sourceType,y??null,c)).map(O=>({...O,userId:a(O.userId),isMine:y?O.userId===y:!1})),attachments:u.attachments}},X=async(c,u)=>{let y=(0,d.aliasedTable)(h,"draft_label"),R=await Ge();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).leftJoin(y,(0,d.and)((0,d.eq)(y.hubId,s.id),(0,d.inArray)(y.labelId,R))).where((0,d.and)((0,d.isNull)(s.deletedAt),(0,d.or)((0,d.eq)(s.userId,u),(0,d.isNull)(s.userId),(0,d.isNull)(y.hubId)),x(c.visible))).orderBy((0,d.desc)(s.businessDate),(0,d.desc)(s.id))).map(E=>({...E,businessDate:De(E.businessDate,"YYYY-MM-DD")}))},L=async(c,u,y)=>{let R=await Ce(u);if(!R)return[];if(Ue(c.visible))return[];let T=(0,d.aliasedTable)(h,"draft_label"),E=await Ge();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(y).from(s).leftJoin(T,(0,d.and)((0,d.eq)(T.hubId,s.id),(0,d.inArray)(T.labelId,E))).where((0,d.and)((0,d.isNull)(s.deletedAt),(0,d.or)((0,d.eq)(s.userId,R),(0,d.isNull)(s.userId),(0,d.isNull)(T.hubId)),x(c.visible))).orderBy((0,d.desc)(s.businessDate),(0,d.desc)(s.id))).map(U=>({...U,businessDate:De(U.businessDate,"YYYY-MM-DD")}))},fe=async(c,u)=>{let y=await G(t.select({hub:je(s),internal:je(f),creatorName:n.displayName,...Y()}).from(s)).leftJoin(f,(0,d.eq)(s.id,f.hubId)).leftJoin(n,(0,d.eq)(s.userId,n.id)).where((0,d.and)((0,d.eq)(s.businessDate,d.sql`${u}`),(0,d.isNull)(s.deletedAt),x(c.visible))).orderBy((0,d.desc)(s.id)),R=await Nt(y.map(T=>T.hub.id));return y.map(T=>z(c,{...T,attachments:R.get(T.hub.id)??[]}))},Te=new Map,Ce=async c=>{if(!e.disableUserIdCache&&Te.has(c))return Te.get(c)??null;let u=await o(c);return u!==null&&!e.disableUserIdCache&&Te.set(c,u),u},Qa=async(c,u,{forceRefresh:y=!1,snapshot:R=!1,ttlMsOverride:T,onFetchStart:E}={})=>{let w=await Ce(u);if(!w)return{items:[],streamAnchor:null,snapshot:Ca};if(Ue(c.visible))return{items:[],streamAnchor:await N(),snapshot:Ca};let U=Zo(w,Pt(c)),[P]=await l.getOrFetch({cacheKey:U,fetcher:async()=>{let W=await N(),O=await X(c,w);if(!dn(O)){C.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let re=[...O].sort(Bt);return[{items:re,streamAnchor:W,snapshot:Ut(re)}]}return[{items:O,streamAnchor:W,snapshot:Ut(O)}]},onFetchStart:E,forceRefresh:y,snapshot:R,ttlMsOverride:T??be,epochKey:ue,refreshAheadRatio:.5});if(P===void 0)throw new Error("[DailyReportService] ids cache returned no record");return P},Xa=(c,u,{forceRefresh:y=!1,snapshot:R=!1,ttlMsOverride:T}={})=>{let E=we(u);return E?Ue(c.visible)?Promise.resolve([]):l.getOrFetch({cacheKey:ea(E,Pt(c)),fetcher:()=>fe(c,E),forceRefresh:y,snapshot:R,ttlMsOverride:T??j}):Promise.resolve([])},tt=null,vt=async()=>(tt!==null||(tt=(await t.select({id:D.id}).from(D).where((0,d.inArray)(D.name,A)).orderBy(D.id)).map(u=>u.id)),tt),Ge=async()=>{let c=await vt();return c.length>0?c:[-1]},pr=async()=>{let c=await vt();if(c.length===0)return null;let[u]=await t.select({id:D.id}).top(1).from(D).where((0,d.eq)(D.name,B));return u?.id??c[0]},Za=(c,u)=>u!=null?"absent":c!=null?"present":"unknown",Nt=async c=>{let u=new Map,y=r.attachment;if(c.length===0||!y||k===null)return u;let R=k.idCodec,T=k.thumbnails!==null,E=await t.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where((0,d.inArray)(y.hubId,c)).orderBy((0,d.asc)(y.createdAt),(0,d.asc)(y.id));for(let w of E){let U=w.fileType?String(w.fileType):null,P=w.fileSize!=null?Number(w.fileSize):null,W=Za(w.objectCheckedAt,w.objectMissingAt),O={id:R.encode(Number(w.id)),fileName:String(w.fileName),fileType:U,fileSize:P,createdAt:De(w.createdAt,"YYYY-MM-DD HH:mm:ss"),state:W,hasThumbnail:T&&W!=="absent"&&Xt({fileType:U,fileSize:P},k.maxBytes)},re=u.get(Number(w.hubId));re?re.push(O):u.set(Number(w.hubId),[O])}return u},ei=async(c,u,y)=>{let R=r.attachment;if(!R||Ue(c.visible))return null;let T=await Ge(),E=(0,d.aliasedTable)(h,"draft_label");return(await t.select({fileName:R.fileName,filePath:R.filePath,fileType:R.fileType,fileSize:R.fileSize}).top(1).from(R).innerJoin(s,(0,d.eq)(s.id,R.hubId)).leftJoin(E,(0,d.and)((0,d.eq)(E.hubId,s.id),(0,d.inArray)(E.labelId,T))).where((0,d.and)((0,d.eq)(R.id,u),(0,d.isNull)(s.deletedAt),(0,d.or)((0,d.eq)(s.userId,y),(0,d.isNull)(E.hubId)),x(c.visible))))[0]??null},ti=async c=>{let u=r.attachment;if(!u)return;let y=new Date;try{await t.update(u).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where((0,d.eq)(u.id,c))}catch(R){C.error("markAttachmentMissing failed",R)}},ri=async c=>{let u=r.attachment;if(!u)return;let y=new Date;try{await t.update(u).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where((0,d.eq)(u.id,c))}catch(R){C.error("markAttachmentPresent failed",R)}},nn=async(c,u,y)=>{let R=await Ge(),T=(0,d.aliasedTable)(h,"draft_label"),E=await G(t.select({hub:je(s),internal:je(f),isRead:b.isRead,isStarred:b.isStarred,creatorName:n.displayName,...Y()}).from(s)).leftJoin(f,(0,d.eq)(s.id,f.hubId)).leftJoin(b,(0,d.and)((0,d.eq)(s.id,b.hubId),(0,d.eq)(b.userId,u))).leftJoin(T,(0,d.and)((0,d.eq)(T.hubId,s.id),(0,d.inArray)(T.labelId,R))).leftJoin(n,(0,d.eq)(s.userId,n.id)).where((0,d.and)(y,(0,d.isNull)(s.deletedAt),(0,d.or)((0,d.eq)(s.userId,u),(0,d.isNull)(T.hubId)),x(c.visible))).orderBy((0,d.desc)(s.id));if(E.length===0)return[];let w=E.map(K=>K.hub.id),U=await t.select({hubId:h.hubId,id:D.id,name:D.name,color:D.color}).from(h).innerJoin(D,(0,d.eq)(h.labelId,D.id)).where((0,d.inArray)(h.hubId,w)),P=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,d.eq)(m.userId,n.id)).where((0,d.inArray)(m.hubId,w)).orderBy((0,d.asc)(m.createdAt)),W=await Nt(w),O=new Map,re=new Map;for(let K of U){let te=O.get(K.hubId);te||(te=[],O.set(K.hubId,te)),te.push({id:K.id,name:K.name,color:K.color})}for(let K of P){let te=re.get(K.hubId);te||(te=[],re.set(K.hubId,te)),te.push({id:K.id,content:K.body,createdAt:De(K.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:K.userId,userName:K.userName||""})}return E.map(K=>{let te=K.hub.id;return z(c,{...K,attachments:W.get(te)??[],labels:O.get(te)||[],postedCommentRows:re.get(te)||[]},u)})},ni=async(c,u,y,{forceRefresh:R=!1,snapshot:T=!1,ttlMsOverride:E}={})=>{let w=await Ce(y);if(!w)return[];let U=we(u);if(!U)return[];if(Ue(c.visible))return[];let P=ta(U,w,Pt(c));return l.getOrFetch({cacheKey:P,fetcher:()=>nn(c,w,(0,d.eq)(s.businessDate,d.sql`${U}`)),forceRefresh:R,snapshot:T,ttlMsOverride:E??j,epochKey:`${Z}${U}`})},Rt=async(c,u,y,{forceRefresh:R=!1,snapshot:T=!1,ttlMsOverride:E}={})=>{if(Ue(c.visible))return null;let w=ra(u,y,Pt(c));return(await l.getOrFetch({cacheKey:w,fetcher:async()=>{let P=await Ge(),W=(0,d.aliasedTable)(h,"draft_label"),O=await G(t.select({hub:je(s),internal:je(f),isRead:b.isRead,isStarred:b.isStarred,creatorName:n.displayName,...Y()}).from(s)).leftJoin(f,(0,d.eq)(s.id,f.hubId)).leftJoin(b,(0,d.and)((0,d.eq)(s.id,b.hubId),(0,d.eq)(b.userId,y))).leftJoin(W,(0,d.and)((0,d.eq)(W.hubId,s.id),(0,d.inArray)(W.labelId,P))).leftJoin(n,(0,d.eq)(s.userId,n.id)).where((0,d.and)((0,d.eq)(s.id,u),(0,d.isNull)(s.deletedAt),(0,d.or)((0,d.eq)(s.userId,y),(0,d.isNull)(W.hubId)),x(c.visible)));if(O.length===0)return[];let re=O[0].hub.id,K=await t.select({id:D.id,name:D.name,color:D.color}).from(h).innerJoin(D,(0,d.eq)(h.labelId,D.id)).where((0,d.eq)(h.hubId,re)),te=await t.select({id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,(0,d.eq)(m.userId,n.id)).where((0,d.eq)(m.hubId,re)).orderBy((0,d.asc)(m.createdAt)),le=await Nt([re]),Ii=K.map(He=>({id:He.id,name:He.name,color:He.color})),Ei=te.map(He=>({id:He.id,content:He.body,createdAt:De(He.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:He.userId,userName:He.userName||""}));return[z(c,{...O[0],attachments:le.get(re)??[],labels:Ii,postedCommentRows:Ei},y)]},forceRefresh:R,snapshot:T,ttlMsOverride:E??j,epochKey:`${ne}${u}`}))[0]??null},oi=async(c,u,y,R={})=>{let T=await Ce(y);return T?Rt(c,u,T,R):null},ai=async(c,u,y)=>{if(u.length>Pe.maxDetailIds)throw ie("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${Pe.maxDetailIds} ids`,u.length);let R=await Ce(y);return!R||u.length===0?[]:Ue(c.visible)?[]:nn(c,R,(0,d.inArray)(s.id,[...u]))},ii=async(c,u)=>{let y=await Ge(),R=(0,d.aliasedTable)(h,"draft_label"),[T]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).leftJoin(R,(0,d.and)((0,d.eq)(R.hubId,s.id),(0,d.inArray)(R.labelId,y))).where((0,d.and)((0,d.eq)(s.id,c),(0,d.or)((0,d.eq)(s.userId,u),(0,d.isNull)(R.hubId))));return T??null},yr=async(c,u,y)=>{let R=await ii(u,y);if(!R||R.deletedAt||!xe(c.visible,R.sourceType))throw new Error("Not Found")},si=async(c,u,y,R,T,E)=>{await yr(c,y,u);let w=await t.select().top(1).from(b).where((0,d.and)((0,d.eq)(b.hubId,y),(0,d.eq)(b.userId,u))),U;if(w.length>0?w[0].isStarred!==T?U=(await t.update(b).set({isStarred:T,updatedAt:new Date,updatedBy:String(u)}).output().where((0,d.and)((0,d.eq)(b.hubId,y),(0,d.eq)(b.userId,u))))[0]:U=w[0]:U=(await t.insert(b).output().values({hubId:y,userId:u,isStarred:T,isRead:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],R){let P=we(R);P&&(l.invalidatePrefix(ct(P,u)),await ee(`${Z}${P}`))}return l.invalidatePrefix(sr(y,u)),await ee(`${ne}${y}`),await v(Ft.parse({type:"status-update",reportHubId:y,recipientRawUserId:u,statusType:"star",value:T,clientTempId:E}),"setStarStatus"),U},li=async(c,u,y,R,T,E)=>{await yr(c,y,u);let w=await t.select().top(1).from(b).where((0,d.and)((0,d.eq)(b.hubId,y),(0,d.eq)(b.userId,u))),U;if(w.length>0?w[0].isRead!==T?U=(await t.update(b).set({isRead:T,updatedAt:new Date,updatedBy:String(u)}).output().where((0,d.and)((0,d.eq)(b.hubId,y),(0,d.eq)(b.userId,u))))[0]:U=w[0]:U=(await t.insert(b).output().values({hubId:y,userId:u,isRead:T,isStarred:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],R){let P=we(R);P&&(l.invalidatePrefix(ct(P,u)),await ee(`${Z}${P}`))}return l.invalidatePrefix(sr(y,u)),await ee(`${ne}${y}`),await v(Ft.parse({type:"status-update",reportHubId:y,recipientRawUserId:u,statusType:"read",value:T,clientTempId:E}),"setReadStatus"),U},on=async(c,u)=>{if(u===null)return;let y=await Ge(),[R]=await t.select({hubId:h.hubId}).top(1).from(h).where((0,d.and)((0,d.eq)(h.hubId,c),(0,d.inArray)(h.labelId,y)));return R?u:void 0},ci=async(c,u,y,R,T,E)=>{let[w]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where((0,d.eq)(s.id,y));if(!w||w.deletedAt)throw new Error("Not Found");if(await yr(c,y,u),!xe(c.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 U=await on(y,w.userId),P=se(),W=await I(async te=>{let[le]=await te.insert(m).output().values({hubId:y,userId:u,body:R,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)});return P!==null&&await P.writeHubs(te,[y]),le}),[O]=await t.select({displayName:n.displayName}).top(1).from(n).where((0,d.eq)(n.id,u)),re=O?.displayName??"";if(T){let te=we(T);te&&(l.invalidatePrefix(wt(te)),await ee(`${Z}${te}`))}l.invalidatePrefix(ke(y)),await ee(`${ne}${y}`);let K={id:W.id,userId:a(W.userId),userName:re,content:W.body,createdAt:De(W.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await v(Er.parse({type:"comment-add",reportHubId:y,comment:K,clientTempId:E,recipientRawUserId:U,sourceType:w.sourceType}),"addComment"),K},ui=async(c,u)=>await c.select().top(1).from(m).where((0,d.eq)(m.id,u)),di=async(c,u,y,R,T,E)=>{let w=await ui(t,R);if(w.length===0)throw new Error("Not Found");if(w[0].hubId!==y)throw new Error("Not Found");let[U]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where((0,d.eq)(s.id,w[0].hubId));if(!(U&&xe(c.visible,U.sourceType)))throw new Error("Not Found");if(w[0].userId!==u)throw new Error("Unauthorized");let P=await on(y,U.userId),W=se();if(await I(async O=>{await O.delete(m).where((0,d.eq)(m.id,R)),W!==null&&await W.writeHubs(O,[y])}),T){let O=we(T);O&&(l.invalidatePrefix(wt(O)),await ee(`${Z}${O}`))}l.invalidatePrefix(ke(y)),await ee(`${ne}${y}`),await v(wr.parse({type:"comment-delete",reportHubId:y,commentId:R,clientTempId:E,recipientRawUserId:P,sourceType:U?.sourceType}),"deleteComment")},mi=async(c,u)=>{let y=new Map,R=r.attachment;if(!R||k===null)return y;let T=await c.select({hubId:R.hubId,fileName:R.fileName}).from(R).where((0,d.inArray)(R.hubId,[...u])).orderBy((0,d.asc)(R.hubId),(0,d.asc)(R.createdAt),(0,d.asc)(R.id));for(let E of T)en(y,Number(E.hubId),String(E.fileName));return y},pi=async(c,u,y)=>{let R=new Map;for(let[T,E]of y){let w=new Map;for(let{hub:P}of u)P.sourceType===T&&P.sourceIdNum!==null&&w.set(P.sourceIdNum,P.id);if(w.size===0)continue;let U=await E(c,[...w.keys()]);for(let[P,W]of U){let O=w.get(P);if(O===void 0)throw ie(`search.externalSourceTexts.${T} answer key`,"a source id that was asked for",P);if(!(Array.isArray(W)&&W.every(re=>typeof re=="string")))throw ie(`search.externalSourceTexts.${T} answer for ${P}`,"an array of strings",W);R.set(O,W)}}return R},yi=(c,u)=>{let y=F(c),R=[["subject",c.hub.title],["content",y.content],["author",y.author],["employeeName",y.employeeName],["updatedBy",y.updatedBy],["category",y.category],["creationCategory",y.creationCategory],["customerName",y.customerName]];for(let E of y.interviewers)R.push(["interviewerName",E.name??null],["interviewerAffiliation",E.affiliation??null]);for(let E of u.labelNames)R.push(["label",E]);for(let E of u.attachmentNames)R.push(["attachment",E]);for(let E of u.extraTexts)R.push(["extra",E]);let T=[];for(let E of y.externalComments)T.push({authorUserId:null,text:Ma(E.name,E.text)});for(let E of u.postedComments)T.push({authorUserId:E.userId,text:Ma(E.userName,E.body)});return{hubId:c.hub.id,fields:R,comments:T}},hi=async(c,u,y)=>{let R=[];for(let T of(0,ft.chunk)(u,ft.MAX_IN_LIST)){let E=await G(c.select({hub:je(s),internal:je(f),creatorName:n.displayName,...Y()}).from(s)).leftJoin(f,(0,d.eq)(s.id,f.hubId)).leftJoin(n,(0,d.eq)(s.userId,n.id)).where((0,d.inArray)(s.id,[...T])).orderBy((0,d.asc)(s.id)),w=new Map,U=await c.select({hubId:h.hubId,name:D.name}).from(h).innerJoin(D,(0,d.eq)(h.labelId,D.id)).where((0,d.inArray)(h.hubId,[...T])).orderBy((0,d.asc)(h.hubId),(0,d.asc)(D.id));for(let K of U)en(w,K.hubId,K.name);let P=new Map,W=await c.select({hubId:m.hubId,userId:m.userId,body:m.body,userName:n.displayName}).from(m).leftJoin(n,(0,d.eq)(m.userId,n.id)).where((0,d.inArray)(m.hubId,[...T])).orderBy((0,d.asc)(m.hubId),(0,d.asc)(m.createdAt),(0,d.asc)(m.id));for(let K of W)en(P,K.hubId,K);let O=await mi(c,T),re=await pi(c,E,y);for(let K of E){let te=K.hub.id;R.push(yi(K,{labelNames:dr(w,te),postedComments:dr(P,te),attachmentNames:dr(O,te),extraTexts:dr(re,te)}))}}return R},fi=(c,u,y)=>Q===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):Q.search(t,{plan:y,viewerUserId:u,scope:c}),Ri=c=>{let u=se();return u===null?Promise.reject(new Error("[daily-report] reconcileSearchIndex: the search setting is not configured")):u.reconcile(t,c)},gi=async(c,u,y)=>{if(!Ht(u))throw ie("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",u);C.info("createDailyReport called",{userId:c,businessDate:u});let[R]=await t.select({displayName:n.displayName}).from(n).where((0,d.eq)(n.id,c)),T=R?.displayName??a(c),E=se();try{let w=await I(async P=>{C.info("Starting transaction");let W=`internal-temp-${Date.now()}-${Math.random()}`,[O]=await P.insert(s).output().values({sourceType:"Internal",sourceId:W,businessDate:new Date(`${u}T00:00:00Z`),userId:c,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)});await P.update(s).set({sourceId:String(O.id)}).where((0,d.eq)(s.id,O.id)),C.info("Hub created",O),await P.insert(f).values({hubId:O.id,body:"",createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)}),C.info("Internal created"),C.info("Calling getDraftLabelId");let re=await pr();C.info("draftLabelId",re);let K=[];return re&&(await P.insert(h).values({hubId:O.id,labelId:re,createdAt:new Date,createdBy:String(c)}),K.push({id:re,name:B,color:null})),C.info("Label assigned"),E!==null&&await E.writeHubs(P,[O.id]),{reportHubId:O.id,date:u,createdAt:De(O.createdAt,"YYYY-MM-DD HH:mm:ss"),author:T,userId:a(c),sourceType:"Internal",employeeName:T,updatedBy:a(c),updatedAt:De(O.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:O.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:K,postedComments:[],attachments:[]}});l.invalidatePrefix(ct(u,c)),l.invalidatePrefix(et),l.invalidatePrefix(zr(c)),await ee(ue),await ee(`${Z}${u}`);let U=await Rt(Ee.unrestricted("post-write self read: the writer always sees the row they just wrote"),w.reportHubId,c,{forceRefresh:!0});if(U){let P=await vt(),W=U.labels.some(O=>P.includes(O.id));await v(_r.parse({type:"report-create",reportHubId:U.reportHubId,report:U,clientTempId:y,recipientRawUserId:W?c:void 0}),"createDailyReport")}return U??w}catch(w){throw C.error("Error in createDailyReport",w),w}},Ot=async(c,u)=>await c.select().top(1).from(s).where((0,d.eq)(s.id,u)),hr=async(c,u,y)=>{await c.update(s).set(y).where((0,d.eq)(s.id,u))},an=async(c,u,y)=>{await c.update(f).set(y).where((0,d.eq)(f.hubId,u))},sn=async(c,u,y)=>{await c.delete(h).where((0,d.and)((0,d.eq)(h.hubId,u),(0,d.eq)(h.labelId,y)))},bi=async(c,u,y)=>{let R=await Ot(t,c);if(!R.length||R[0].deletedAt)throw new Error("Not Found");if(R[0].userId!==u)throw new Error("Unauthorized");let T=se();if(await I(async E=>{await hr(E,c,{deletedAt:new Date,deletedBy:String(u),updatedAt:new Date,updatedBy:String(u)}),T!==null&&await T.writeHubs(E,[c])}),l.invalidatePrefix(ke(c)),l.invalidatePrefix(et),l.invalidatePrefix(Ze),await ee(ue),R[0].businessDate){let E=we(De(R[0].businessDate,"YYYY-MM-DD"));E&&await ee(`${Z}${E}`)}await v(Pr.parse({type:"report-delete",reportHubId:c,clientTempId:y,sourceType:R[0].sourceType}),"deleteDailyReport")},Si=async(c,u,y,R)=>{let T=await Ot(t,c);if(!T.length||T[0].deletedAt)throw new Error("Not Found");if(T[0].userId!==u)throw new Error("Unauthorized");let E=se();await I(async P=>{y.title!==void 0&&await hr(P,c,{title:Pa(y.title),updatedAt:new Date,updatedBy:String(u)}),y.content!==void 0&&await an(P,c,{body:Pa(y.content),updatedAt:new Date,updatedBy:String(u)}),E!==null&&await E.writeHubs(P,[c])}),l.invalidatePrefix(ke(c)),l.invalidatePrefix(et),await ee(`${ne}${c}`);let w=we(De(T[0].businessDate,"YYYY-MM-DD"));w&&(l.invalidatePrefix(wt(w)),await ee(`${Z}${w}`));let U=await Rt(Ee.unrestricted("post-write self read: the writer always sees the row they just wrote"),c,u,{forceRefresh:!0});if(U){let P=await vt(),W=U.labels.some(O=>P.includes(O.id));await v(xr.parse({type:"report-update",reportHubId:U.reportHubId,report:U,clientTempId:R,recipientRawUserId:W?u:void 0}),"updateDailyReport")}},Di=async(c,u,y)=>{let R=await Ot(t,c);if(!R.length)throw new Error("Not Found");if(R[0].userId!==u)throw new Error("Unauthorized");let T=await pr();if(!T)return null;let E=se();if(await I(async P=>{await sn(P,c,T),E!==null&&await E.writeHubs(P,[c])}),l.invalidatePrefix(ke(c)),l.invalidatePrefix(et),l.invalidatePrefix(Ze),await ee(ue),R[0].businessDate){let P=we(De(R[0].businessDate,"YYYY-MM-DD"));P&&await ee(`${Z}${P}`)}let w=we(De(R[0].businessDate,"YYYY-MM-DD"));w&&l.invalidatePrefix(ct(w,u));let U=await Rt(Ee.unrestricted("post-write self read: the writer always sees the row they just wrote"),c,u,{forceRefresh:!0});return U&&await v(Cr.parse({type:"report-publish",reportHubId:U.reportHubId,report:U,clientTempId:y}),"publishDailyReport"),U??null},Ti=async(c,u)=>{l.invalidatePrefix(et),l.invalidatePrefix(Ze),await ee(ue);for(let y of new Set(c))l.invalidatePrefix(ke(y)),await ee(`${ne}${y}`);for(let y of new Set(u)){let R=we(y);R&&await ee(`${Z}${R}`)}},Ai=async()=>{l.clearAll(),Te.clear(),tt=null,p&&await ee(ue),C.info("Server-side DB/SQL caches cleared successfully.")};return{streamKey:oe,streamMaxLen:ye,attachmentDelivery:k,titleMaxLength:M,searchLimits:V===null?null:{concurrency:V.concurrency,rateLimitPerMinute:V.rateLimitPerMinute},clearCache:Ai,invalidateHubReadCaches:Ti,getUserIdByExternalId:Ce,getDailyReportIdsByExternalId:Qa,getDailyReportIdsFirstPageByExternalId:L,readSseStreamAnchor:N,getDailyReportsByBusinessDate:Xa,getDailyReportsByBusinessDateByExternalId:ni,getDailyReportDetailById:Rt,getDailyReportDetailByIdByExternalId:oi,getDailyReportDetailsByIdsByExternalId:ai,getDraftLabelId:pr,searchDailyReports:fi,reconcileSearchIndex:Ri,getAttachmentsByHubIds:Nt,getAttachmentForUser:ei,markAttachmentMissing:ti,markAttachmentPresent:ri,setStarStatus:si,setReadStatus:li,addComment:ci,deleteComment:di,createDailyReport:gi,updateDailyReport:Si,publishDailyReport:Di,deleteDailyReport:bi,findDailyReportHubById:Ot,updateDailyReportHub:hr,updateDailyReportInternal:an,deleteDailyReportLabel:sn}}var La="[DailyReportExternalSource]",va=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(he(n,1,La).warn(`Unexpected ${t} format: not an array`),[])}catch(o){return he(n,1,La).warn(`Failed to parse ${t}:`,o),[]}};var Mt=require("drizzle-orm"),S=require("drizzle-orm/mssql-core");function Na(e,t){let r=(0,S.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,S.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,S.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,S.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,S.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(Mt.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,S.date)("business_date"),userId:(0,S.bigint)("user_id",{mode:"number"}),title:(0,S.nvarchar)("title",{length:200}),summary:(0,S.nvarchar)("summary",{length:"max"}),createdAt:(0,S.datetime2)("created_at").notNull(),createdBy:(0,S.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,S.datetime2)("updated_at").notNull(),updatedBy:(0,S.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,S.datetime2)("deleted_at"),deletedBy:(0,S.nvarchar)("deleted_by",{length:50})},m=>[(0,S.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[m.id]}),(0,S.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,S.index)(`${e}_DailyReportHub_business_date_index`).on(m.businessDate),(0,S.index)(`${e}_DailyReportHub_updated_at_index`).on(m.updatedAt),(0,S.index)(`${e}_DailyReportHub_source_index`).on(m.sourceType,m.sourceId),(0,S.index)(`${e}_DailyReportHub_user_id_index`).on(m.userId),(0,S.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,Mt.desc)(m.businessDate),(0,Mt.desc)(m.id)),(0,S.index)(`${e}_DailyReportHub_deleted_at_index`).on(m.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,S.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,S.nvarchar)("body",{length:"max"}),metadata:(0,S.nvarchar)("metadata",{length:"max"}),createdAt:(0,S.datetime2)("created_at").notNull(),createdBy:(0,S.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,S.datetime2)("updated_at").notNull(),updatedBy:(0,S.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,S.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[m.hubId]}),(0,S.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:(0,S.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,S.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,S.bigint)("user_id",{mode:"number"}).notNull(),body:(0,S.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,S.datetime2)("created_at").notNull(),createdBy:(0,S.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,S.datetime2)("updated_at").notNull(),updatedBy:(0,S.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,S.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[m.id]}),(0,S.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,S.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,S.index)(`${e}_DailyReportComment_hub_id_index`).on(m.hubId)]),l=r.table("DailyReportLabel",{id:(0,S.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,S.bigint)("user_id",{mode:"number"}),name:(0,S.nvarchar)("name",{length:50}).notNull(),color:(0,S.nvarchar)("color",{length:20}),sortOrder:(0,S.int)("sort_order"),createdAt:(0,S.datetime2)("created_at").notNull(),createdBy:(0,S.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,S.datetime2)("updated_at").notNull(),updatedBy:(0,S.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,S.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[m.id]}),(0,S.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),p=r.table("DailyReportHub_Label",{hubId:(0,S.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,S.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,S.datetime2)("created_at").notNull(),createdBy:(0,S.nvarchar)("created_by",{length:50}).notNull()},m=>[(0,S.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[m.hubId,m.labelId]}),(0,S.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,S.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[m.labelId],foreignColumns:[l.id]})]),s=r.table("DailyReportUserStatus",{hubId:(0,S.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,S.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,S.bit)("is_read").default(!1).notNull(),isStarred:(0,S.bit)("is_starred").default(!1).notNull(),createdAt:(0,S.datetime2)("created_at").notNull(),createdBy:(0,S.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,S.datetime2)("updated_at").notNull(),updatedBy:(0,S.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,S.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[m.hubId,m.userId]}),(0,S.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,S.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),f=r.table("DailyReportAttachment",{id:(0,S.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,S.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,S.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,S.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,S.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,S.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,S.nvarchar)("file_type",{length:100}),fileSize:(0,S.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,S.datetime2)("object_checked_at"),objectMissingAt:(0,S.datetime2)("object_missing_at"),createdAt:(0,S.datetime2)("created_at").notNull(),createdBy:(0,S.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,S.datetime2)("updated_at").notNull(),updatedBy:(0,S.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,S.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[m.id]}),(0,S.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,S.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[m.uploadedBy],foreignColumns:[n.id]}),(0,S.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(m.hubId,m.sourceKey),(0,S.index)(`${e}_DailyReportAttachment_hub_id_index`).on(m.hubId,m.createdAt)]);return{hub:o,internal:a,comment:i,attachment:f,label:l,hubLabel:p,userStatus:s}}var me=require("drizzle-orm/mssql-core");function Oa(e){let t=(0,me.mssqlSchema)(e),r=t.table("DailyReportSearchDocument",{hubId:(0,me.bigint)("hub_id",{mode:"number"}).notNull(),searchText:(0,me.nvarchar)("search_text",{length:"max"}).notNull(),sourceDigest:(0,me.binary)("source_digest",{length:32}).notNull(),normalizerVersion:(0,me.varchar)("normalizer_version",{length:64}).notNull(),indexedAt:(0,me.datetime2)("indexed_at").notNull(),rowVersion:(0,me.binary)("row_version",{length:8}).notNull()},o=>[(0,me.primaryKey)({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:(0,me.bigint)("hub_id",{mode:"number"}).notNull(),ordinal:(0,me.int)("ordinal").notNull(),authorUserId:(0,me.bigint)("author_user_id",{mode:"number"}),commentText:(0,me.nvarchar)("comment_text",{length:"max"}).notNull()},o=>[(0,me.primaryKey)({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var gc=5e7,tn=2e8,bc=1,rn=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})})}),ka=125,Ua=4,Ba=16,Ha=50,$a=2,Lt=Object.freeze({renderMs:Ie.renderMs,nanosecondsPerBlockVisit:ka,margin:Ua,maxBlockVisits:Math.floor(Ie.renderMs*1e6/(ka*Ua)),walkBudgetMs:Ba,nanosecondsPerWalkStep:Ha,walkMargin:$a,maxWalkSteps:Math.floor(Ba*1e6/(Ha*$a))}),Sc=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Fa=75,Va=4,Ya="#ffffff",Dc=1,Tc={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Ac=[/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/],qa=Object.freeze({ok:!1,reason:"failed"}),ja=Object.freeze({ok:!1,reason:"unsupported"}),za=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:uo(e)}),Wa=(e,t)=>{switch(t){case"jpeg":{let r=Fr(e);return r===null?null:za(r)}case"png":{let r=yo(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=ho(e,Lt.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},Ka=(e,t)=>{let r=Sc.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=rn,a=o.wholeImageBuffer[e.layout];return(a.kind==="none"?0:a.kind==="decoded-raster"?t.width*t.height*n:a.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*a.bytesPerPixel)+o.pipelineRows*t.width*n+o.fixedBytes},Ja=(e,t,r)=>{let n=Wa(e,t);return n===null?null:Ka(n,r)},Ic=e=>e!==null&&e<=tn,Ec=(e,t)=>{if(t!=="jpeg")return Wa(e,t);let r=mo(e,Lt);return r===null||r.blockVisits>Lt.maxBlockVisits?null:za(r.header)},wc=e=>{let t=e instanceof Error?e.message:"";return Ac.some(r=>r.test(t))?"failed":"unsupported"},Ga=e=>{e.cache(!1),e.concurrency(bc),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Tc)});let t=async(n,o,a,i,l)=>{let p=Ec(n,o);if(p===null)return ja;try{let s=e(n,{limitInputPixels:gc,animated:!1});if(!Ic(Ka(p,await s.metadata())))return ja;if(l.aborted)return qa;let f=await s.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Ya}).webp({quality:Fa,effort:Va}).toBuffer();return{ok:!0,bytes:new Uint8Array(f),contentType:"image/webp"}}catch(s){return{ok:!1,reason:wc(s)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?qa:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Fa}-e${Va}/flatten-${Ya}/v${Dc}`,render:r}};function _c(e){e.redis||he(e.logger,2,"[DailyReportServer]").warn("redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=kt(e.redis),r=new rt({defaultTtlMs:e.cacheDefaultTtlMs??6e4},t),n=mr({...e,cache:r,epochs:t}),o=new ut({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=ur({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(i=>i.sourceType)])],...a}}0&&(module.exports={DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,DAILY_REPORT_SSE_CATCH_UP_BATCH,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createEpochStore,createSharpThumbnailRenderer,defineDailyReportSchema,defineDailyReportSearchSchema,generateETag,isStreamIdLte,jsonResponseWithETag,parseClientTempId,predictSharpThumbnailWorkingSetBytes,readDailyReportSseStreamEntry,transformJsonArray});
11
+ INSERT INTO ${o} (${G(o.hubId)}, ${G(o.ordinal)}, ${G(o.authorUserId)}, ${G(o.commentText)}) SELECT ${G(o.hubId)}, ${G(o.ordinal)}, ${G(o.authorUserId)}, ${G(o.commentText)} FROM OPENJSON(${i}) WITH (${G(o.hubId)} bigint, ${G(o.ordinal)} int, ${G(o.authorUserId)} bigint, ${G(o.commentText)} nvarchar(max));`},mi=(e,t)=>q.sql`SELECT ${G(e.hubId)} AS ${q.sql.identifier(Ee.hubId)}, LOWER(CONVERT(char(64), ${G(e.sourceDigest)}, 2)) AS ${q.sql.identifier(Ee.sourceDigest)}, ${G(e.normalizerVersion)} AS ${q.sql.identifier(Ee.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${ai(t)})`,pi=(e,t,r)=>q.sql`SELECT TOP (${r}) ${G(e.id)} AS ${q.sql.identifier(Ee.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var yi=e=>({search:async(t,r)=>ve(r.scope.visible)?[]:dt(await t.execute(ci(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=wt(o[Be.sourceType],Be.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${Be.sourceType} is null`);return{reportHubId:mt(o[Be.reportHubId],Be.reportHubId),businessDate:wt(o[Be.businessDate],Be.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(ve(r.scope.visible))return new Map;let n=dt(await t.execute(ui(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames,r.ids))),o=2**r.plan.sets.length-1,a=new Map;for(let i of n){let l=i[pt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${pt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(mt(i[pt.reportHubId],pt.reportHubId),l)}return a}});var We=require("@aiquants/mssql"),wn=require("drizzle-orm");var hi=require("crypto");var In=e=>e===null?"n;":`s${e.length}:${e}`,wu=e=>{let t=(0,hi.createHash)("sha256");t.update(`F${e.fields.length};`);for(let[r,n]of e.fields)t.update(In(r)+In(n));return t.update(`C${e.comments.length};`),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${In(r.text)}`)}),t.digest("hex")},_n=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=br(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=br(o.text);t+=a.forcedCuts,a.text.length!==0&&n.push({ordinal:n.length,authorUserId:o.authorUserId,commentText:a.text})}return{hubId:e.hubId,searchText:xa(r),comments:n,sourceDigest:wu(e),forcedCuts:t}};var fi=e=>{let t=async(c,s)=>{let y=[];for(let m of(0,We.chunk)(s,We.MAX_IN_LIST))for(let S of dt(await c.execute(ii(e.hub,m))))y.push(mt(S[Ee.hubId],Ee.hubId));return y},r=async(c,s)=>{for(let y of(0,We.chunk)(s,We.MAX_IN_LIST))await c.execute(di(e.tables,y,e.normalizerVersion))},n=async(c,s)=>{let y=new Map;for(let m of(0,We.chunk)(s,We.MAX_IN_LIST))for(let S of dt(await c.execute(mi(e.tables.document,m))))y.set(mt(S[Ee.hubId],Ee.hubId),{sourceDigest:wt(S[Ee.sourceDigest],Ee.sourceDigest),normalizerVersion:wt(S[Ee.normalizerVersion],Ee.normalizerVersion)});return y},o=async(c,s,y)=>dt(await c.execute(pi(e.hub,s,y))).map(m=>mt(m[Ee.hubId],Ee.hubId)),a=async(c,s)=>{let y=await t(c,[...new Set(s)].sort((S,f)=>S-f));if(y.length===0)return;let m=(await e.loadSources(c,y)).map(_n);m.length>0&&await r(c,m)},i=c=>e.inTransaction(async s=>{await s.execute(wn.sql`SET DEADLOCK_PRIORITY LOW`);let y=await t(s,c),m=await n(s,y),S=(await e.loadSources(s,y)).map(_n),f=S.filter(R=>{let A=m.get(R.hubId);return A===void 0||A.sourceDigest!==R.sourceDigest||A.normalizerVersion!==e.normalizerVersion});return f.length>0&&await r(s,f),await s.execute(wn.sql`SET DEADLOCK_PRIORITY NORMAL`),{scanned:S.length,written:f.length,forcedCuts:S.reduce((R,A)=>R+A.forcedCuts,0)}});return{writeHubs:a,reconcile:async(c,s)=>{let{batchSize:y,hubIds:m,signal:S,onProgress:f}=s;te("reconcileSearchIndex: batchSize",y,1,We.MAX_IN_LIST);let R=ce(),A=m===void 0?null:(0,We.chunk)([...new Set(m)].sort((w,H)=>w-H),y),b={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let w=0;;w++){S?.throwIfAborted();let H=A===null?await o(c,b.lastHubId===null?0:b.lastHubId,y):A[w];if(H===void 0||H.length===0)break;let B=await i(H);b={scanned:b.scanned+B.scanned,written:b.written+B.written,skipped:b.skipped+B.scanned-B.written,forcedCuts:b.forcedCuts+B.forcedCuts,lastHubId:H[H.length-1]},f?.(b)}return{...b,elapsedMs:ce()-R}}}};var Ri=require("@aiquants/fuzzy-search/normalize");var xn=255,wr=Object.values(it).sort((e,t)=>e-t),xu=new Intl.Segmenter("und",{granularity:"grapheme"}),Cu=(e,t)=>{if(e.text!==t)throw new Error(`[daily-report] search marks: the position-mapped line (${e.text.length} units) differs from the index line (${t.length} units)`);return e},Mu=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length,Pu=(e,t,r)=>{let n=e.slice(t,r);if(!(0,Ri.holdsMultiUnitCluster)(n))return null;let o=new Int32Array(r-t),a=new Int32Array(r-t);for(let{index:i,segment:l}of xu.segment(n))o.fill(t+i,i,i+l.length),a.fill(t+i+l.length,i,i+l.length);return{start:t,clusterStarts:o,clusterEnds:a}},Lu=(e,t,r)=>({start:e.clusterStarts[t-e.start],end:e.clusterEnds[r-1-e.start]}),Ou=(e,t,r=gr)=>{let n=new Map;for(let l of t){if(l.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let c=n.get(l.text);(c===void 0||l.tier<c)&&n.set(l.text,l.tier)}let o=[];if(n.size===0)return o;let a=Ea(e),i=l=>a.rawIndex===null?l:a.rawIndex[l];return Sn(a.text,(l,c)=>{let s=Rn(l,r).text,y=null,m=null;for(let[S,f]of n){let R=s.indexOf(S);if(!(R<0)){if(y===null){let A=fn(l,r);y=Cu(wa(l,A),s),m=Mu(A,l)?null:Pu(e,i(c),i(c+l.length-1)+1)}for(;R>=0;){let A=i(c+y.start[R]),b=i(c+y.end[R+S.length-1]-1)+1;m===null?o.push({start:A,end:b,tier:f}):o.push({...Lu(m,A,b),tier:f}),R=s.indexOf(S,R+1)}}}}),o},Nu=(e,t,r=gr)=>{let n=Ou(e,t,r),o=[];if(n.length===0)return o;let a=wr.map(()=>new Int32Array(e.length+1));for(let{start:s,end:y,tier:m}of n)a[m][s]++,a[m][y]--;let i=new Int32Array(wr.length),l=0,c=xn;for(let s=0;s<=e.length;s++){let y=xn;for(let m=wr.length-1;m>=0;m--){let S=wr[m];i[S]+=a[S][s],i[S]>0&&(y=S)}y!==c&&(c!==xn&&o.push(l,s,c),l=s,c=y)}return o},Si=(e,t)=>{if(e.combine==="intersection"||e.sets.length===1)return e.sets.flatMap(r=>r.words);if(t===null)throw new Error(`[daily-report] search marks: a union of ${e.sets.length} keywords needs the report's mask of matched keywords`);return e.sets.flatMap((r,n)=>(t&1<<n)===0?[]:r.words)},gi=(e,t)=>{let r=t.flatMap(a=>a.alternatives),n={},o=(a,i)=>{typeof i!="string"||i.length===0||(n[a]={fingerprint:Fr(i),ranges:Nu(i,r)})};for(let a of qn)o(Ge.field(a),e[a]);e.interviewers.forEach((a,i)=>{o(Ge.interviewer(i,"name"),a.name),o(Ge.interviewer(i,"affiliation"),a.affiliation)}),e.attachments.forEach((a,i)=>{o(Ge.attachment(i),a.fileName)}),e.externalComments.forEach((a,i)=>{o(Ge.comment(Ur(i),"author"),a.name),o(Ge.comment(Ur(i),"content"),a.text)});for(let a of e.postedComments)o(Ge.comment(a.id,"author"),a.userName),o(Ge.comment(a.id,"content"),a.content);return n};var et=e=>(0,g.getColumns)(e),bi=Gt([]),_e=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),c=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${c}:${s}`},ku=e=>{let{length:t}=e;if(t===void 0)throw se("tables.hub.title","a character column with a declared length",t);return te("tables.hub.title.length",t,1)},Di=e=>e===""?null:e,Hu=Object.freeze([]),Cn=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},xr=(e,t)=>e.get(t)??Hu,Ai=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Sr);function Cr(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:c}=e,{hub:s,internal:y,comment:m,label:S,hubLabel:f,userStatus:R}=r,A=e.externalSources??[],b=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],w=b[0]??"\u4E0B\u66F8\u304D",H=Re(e.logger,1,"Service");mr(e);let B=oa(e.attachments),C=ku(s.title),I=d=>(0,xt.runWithTransactionRetry)(u=>t.transaction(p=>u(()=>d(p))),e.transactionRetry),V=e.search===void 0?null:ni(e.search,A.map(d=>d.sourceType)),$={hub:s,hubLabel:f,label:S},U=V===null?null:yi({tables:{...$,search:V.tables},draftLabelNames:b}),le=null,de=()=>{if(V===null)return null;if(le===null){let d=V.externalSourceTexts;le=fi({hub:s,tables:V.tables,loadSources:(u,p)=>ns(u,p,d),inTransaction:I,normalizerVersion:Ca()})}return le},Se=e.idsTtlMs??18e4,W="daily-report:ids:epoch",ne=e.businessDateTtlMs??3e5,ee="daily-report:date-epoch:",ie="daily-report:detail-epoch:",fe=`${e.streamKey??"daily-report:sse-stream"}:v2`,je=e.streamMaxLen??1e4,re=d=>c.incrementEpoch(d),Me=d=>Bt(s.sourceType,d),ke=(d,u)=>_r($,d,b,u),Ae=async(d,u)=>{let p=await i?.getClient();if(!p){H.warn(`[SSE] Redis client unavailable (${u})`);return}let h=JSON.stringify(d),T=Buffer.byteLength(h);if(T>6356992){H.warn(`[SSE] Event too large (${u}): ${T} bytes > ${6356992}; not published`);return}let x=ce();try{await p.xAdd(fe,"*",{data:h},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:je}});let M=ce()-x;M>1e3&&H.warn(`[SSE] Slow publish (${u}): ${M}ms`)}catch(M){H.error(`[SSE] Redis publish failed (${u}):`,M)}},v=async()=>{try{let d=await i?.getClient();if(d===void 0)return null;let[u]=await d.xRevRange(fe,"+","-",{COUNT:1});return u===void 0?null:u.id}catch(d){return H.error("SSE stream anchor read failed",d),null}},N=d=>d==null||d===""?null:/^\d+$/.test(d)?a(Number(d)):d,E=()=>{let d={};for(let u of A)d[`ext_${u.sourceType}`]=et(u.table);return d},F=d=>{let u=d;for(let p of A)u=u.leftJoin(p.table,(0,g.and)((0,g.eq)(s.sourceType,p.sourceType),(0,g.eq)(s.sourceIdNum,p.idColumn)));return u},j=d=>{let{hub:u,internal:p}=d,h=u.summary,T=[],x=null,M=null,k=null,L=null,Y=null,_=null,Q=[],oe=A.find(pe=>pe.sourceType===u.sourceType),ge=oe?d[`ext_${oe.sourceType}`]:void 0;if(oe&&ge){let pe=oe.mapRow(ge);pe.content!==void 0&&(h=pe.content),pe.employeeName!==void 0&&(_=pe.employeeName),pe.category!==void 0&&(x=pe.category),pe.creationCategory!==void 0&&(M=pe.creationCategory),pe.visitTimeFrom!==void 0&&(k=pe.visitTimeFrom),pe.visitTimeTo!==void 0&&(L=pe.visitTimeTo),pe.customerName!==void 0&&(Y=pe.customerName),pe.interviewers!==void 0&&(T=pe.interviewers),pe.externalComments!==void 0&&(Q=pe.externalComments)}else u.sourceType==="Internal"&&p&&(h=p.body);return{content:h,author:d.creatorName??N(u.createdBy)??"",employeeName:_??d.creatorName??N(u.createdBy),updatedBy:N(u.updatedBy),category:x,creationCategory:M,visitTimeFrom:k,visitTimeTo:L,customerName:Y,interviewers:T,externalComments:Q}},K=(d,u,p)=>{let{hub:h}=u,T=j(u),x=(u.labels??[]).map(_=>({id:_.id,name:_.name,color:_.color})),M=u.postedCommentRows??[],k=Ne(d.commentable,h.sourceType),L=T.creationCategory?b.includes(T.creationCategory):!1,Y=ht?.[0]??null;return L&&Y&&!x.some(_=>_.id===Y)&&x.push({id:Y,name:w,color:null}),{reportHubId:h.id,date:_e(h.businessDate,"YYYY-MM-DD"),author:T.author,userId:h.userId?a(h.userId):"",sourceType:h.sourceType??"Internal",createdAt:_e(h.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:_e(h.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:T.updatedBy,employeeName:T.employeeName,category:T.category,creationCategory:T.creationCategory,visitTimeFrom:T.visitTimeFrom,visitTimeTo:T.visitTimeTo,customerName:T.customerName,interviewers:T.interviewers,subject:h.title,content:T.content,externalComments:k?T.externalComments:[],isRead:u.isRead??!1,isStarred:u.isStarred??!1,labels:x,postedComments:M.filter(_=>ei({authorUserId:_.userId},h.sourceType,p??null,d)).map(_=>({..._,userId:a(_.userId),isMine:p?_.userId===p:!1})),attachments:u.attachments}},J=async(d,u)=>(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).where((0,g.and)((0,g.isNull)(s.deletedAt),ke(u,"author-or-authorless"),Me(d.visible))).orderBy((0,g.desc)(s.businessDate),(0,g.desc)(s.id))).map(h=>({...h,businessDate:_e(h.businessDate,"YYYY-MM-DD")})),z=async(d,u,p)=>{let h=await Z(u);return h?ve(d.visible)?[]:(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(p).from(s).where((0,g.and)((0,g.isNull)(s.deletedAt),ke(h,"author-or-authorless"),Me(d.visible))).orderBy((0,g.desc)(s.businessDate),(0,g.desc)(s.id))).map(x=>({...x,businessDate:_e(x.businessDate,"YYYY-MM-DD")})):[]},X=async(d,u)=>{let p=await F(t.select({hub:et(s),internal:et(y),creatorName:n.displayName,...E()}).from(s)).leftJoin(y,(0,g.eq)(s.id,y.hubId)).leftJoin(n,(0,g.eq)(s.userId,n.id)).where((0,g.and)((0,g.eq)(s.businessDate,g.sql`${u}`),(0,g.isNull)(s.deletedAt),Me(d.visible))).orderBy((0,g.desc)(s.id)),h=await Wt(p.map(T=>T.hub.id));return p.map(T=>K(d,{...T,attachments:h.get(T.hub.id)??[]}))},P=new Map,Z=async d=>{if(!e.disableUserIdCache&&P.has(d))return P.get(d)??null;let u=await o(d);return u!==null&&!e.disableUserIdCache&&P.set(d,u),u},De=async(d,u,{forceRefresh:p=!1,snapshot:h=!1,ttlMsOverride:T,onFetchStart:x,admission:M}={})=>{let k=await Z(u);if(!k)return{items:[],streamAnchor:null,snapshot:bi};if(ve(d.visible))return{items:[],streamAnchor:await v(),snapshot:bi};let L=va(k,Ft(d)),[Y]=await l.getOrFetch({cacheKey:L,fetcher:async()=>{let _=await v(),Q=await J(d,k);if(!Un(Q)){H.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let oe=[...Q].sort(Kt);return[{items:oe,streamAnchor:_,snapshot:Gt(oe)}]}return[{items:Q,streamAnchor:_,snapshot:Gt(Q)}]},onFetchStart:x,forceRefresh:p,snapshot:h,admission:M,ttlMsOverride:T??Se,epochKey:W,refreshAheadRatio:.5});if(Y===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return Y},yt=(d,u,{forceRefresh:p=!1,snapshot:h=!1,ttlMsOverride:T}={})=>{let x=Pe(u);return x?ve(d.visible)?Promise.resolve([]):l.getOrFetch({cacheKey:ka(x,Ft(d)),fetcher:()=>X(d,x),forceRefresh:p,snapshot:h,ttlMsOverride:T??ne}):Promise.resolve([])},ht=null,qt=async()=>(ht!==null||(ht=(await t.select({id:S.id}).from(S).where((0,g.inArray)(S.name,b)).orderBy(S.id)).map(u=>u.id)),ht),Mr=async()=>{let d=await qt();if(d.length===0)return null;let[u]=await t.select({id:S.id}).top(1).from(S).where((0,g.eq)(S.name,w));return u?.id??d[0]},Fi=(d,u)=>u!=null?"absent":d!=null?"present":"unknown",Wt=async d=>{let u=new Map,p=r.attachment;if(d.length===0||!p||B===null)return u;let h=B.idCodec,T=B.thumbnails!==null,x=await t.select({id:p.id,hubId:p.hubId,fileName:p.fileName,fileType:p.fileType,fileSize:p.fileSize,createdAt:p.createdAt,objectCheckedAt:p.objectCheckedAt,objectMissingAt:p.objectMissingAt}).from(p).where((0,g.inArray)(p.hubId,d)).orderBy((0,g.asc)(p.createdAt),(0,g.asc)(p.id));for(let M of x){let k=M.fileType?String(M.fileType):null,L=M.fileSize!=null?Number(M.fileSize):null,Y=Fi(M.objectCheckedAt,M.objectMissingAt),_={id:h.encode(Number(M.id)),fileName:String(M.fileName),fileType:k,fileSize:L,createdAt:_e(M.createdAt,"YYYY-MM-DD HH:mm:ss"),state:Y,hasThumbnail:T&&Y!=="absent"&&ur({fileType:k,fileSize:L},B.maxBytes)},Q=u.get(Number(M.hubId));Q?Q.push(_):u.set(Number(M.hubId),[_])}return u},Vi=async(d,u,p)=>{let h=r.attachment;return!h||ve(d.visible)?null:(await t.select({fileName:h.fileName,filePath:h.filePath,fileType:h.fileType,fileSize:h.fileSize}).top(1).from(h).innerJoin(s,(0,g.eq)(s.id,h.hubId)).where((0,g.and)((0,g.eq)(h.id,u),(0,g.isNull)(s.deletedAt),ke(p,"author"),Me(d.visible))))[0]??null},Yi=async d=>{let u=r.attachment;if(!u)return;let p=new Date;try{await t.update(u).set({objectCheckedAt:p,objectMissingAt:p,updatedAt:p}).where((0,g.eq)(u.id,d))}catch(h){H.error("markAttachmentMissing failed",h)}},qi=async d=>{let u=r.attachment;if(!u)return;let p=new Date;try{await t.update(u).set({objectCheckedAt:p,objectMissingAt:null,updatedAt:p}).where((0,g.eq)(u.id,d))}catch(h){H.error("markAttachmentPresent failed",h)}},Pr=async(d,u,p)=>{let h=await F(t.select({hub:et(s),internal:et(y),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,...E()}).from(s)).leftJoin(y,(0,g.eq)(s.id,y.hubId)).leftJoin(R,(0,g.and)((0,g.eq)(s.id,R.hubId),(0,g.eq)(R.userId,u))).leftJoin(n,(0,g.eq)(s.userId,n.id)).where((0,g.and)(p,(0,g.isNull)(s.deletedAt),ke(u,"author"),Me(d.visible))).orderBy((0,g.desc)(s.id));if(h.length===0)return[];let T=h.map(_=>_.hub.id),x=await t.select({hubId:f.hubId,id:S.id,name:S.name,color:S.color}).from(f).innerJoin(S,(0,g.eq)(f.labelId,S.id)).where((0,g.inArray)(f.hubId,T)),M=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,g.eq)(m.userId,n.id)).where((0,g.inArray)(m.hubId,T)).orderBy((0,g.asc)(m.createdAt)),k=await Wt(T),L=new Map,Y=new Map;for(let _ of x){let Q=L.get(_.hubId);Q||(Q=[],L.set(_.hubId,Q)),Q.push({id:_.id,name:_.name,color:_.color})}for(let _ of M){let Q=Y.get(_.hubId);Q||(Q=[],Y.set(_.hubId,Q)),Q.push({id:_.id,content:_.body,createdAt:_e(_.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:_.userId,userName:_.userName||""})}return h.map(_=>{let Q=_.hub.id;return K(d,{..._,attachments:k.get(Q)??[],labels:L.get(Q)||[],postedCommentRows:Y.get(Q)||[]},u)})},Wi=async(d,u,p,{forceRefresh:h=!1,snapshot:T=!1,ttlMsOverride:x,admission:M}={})=>{let k=await Z(p);if(!k)return[];let L=Pe(u);if(!L)return[];if(ve(d.visible))return[];let Y=Ha(L,k,Ft(d));return l.getOrFetch({cacheKey:Y,fetcher:()=>Pr(d,k,(0,g.eq)(s.businessDate,g.sql`${L}`)),forceRefresh:h,snapshot:T,admission:M,ttlMsOverride:x??ne,epochKey:`${ee}${L}`})},Ct=async(d,u,p,{forceRefresh:h=!1,snapshot:T=!1,ttlMsOverride:x,admission:M}={})=>{if(ve(d.visible))return null;let k=Ua(u,p,Ft(d));return(await l.getOrFetch({cacheKey:k,fetcher:async()=>{let Y=await F(t.select({hub:et(s),internal:et(y),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,...E()}).from(s)).leftJoin(y,(0,g.eq)(s.id,y.hubId)).leftJoin(R,(0,g.and)((0,g.eq)(s.id,R.hubId),(0,g.eq)(R.userId,p))).leftJoin(n,(0,g.eq)(s.userId,n.id)).where((0,g.and)((0,g.eq)(s.id,u),(0,g.isNull)(s.deletedAt),ke(p,"author"),Me(d.visible)));if(Y.length===0)return[];let _=Y[0].hub.id,Q=await t.select({id:S.id,name:S.name,color:S.color}).from(f).innerJoin(S,(0,g.eq)(f.labelId,S.id)).where((0,g.eq)(f.hubId,_)),oe=await t.select({id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,(0,g.eq)(m.userId,n.id)).where((0,g.eq)(m.hubId,_)).orderBy((0,g.asc)(m.createdAt)),ge=await Wt([_]),pe=Q.map(ze=>({id:ze.id,name:ze.name,color:ze.color})),ps=oe.map(ze=>({id:ze.id,content:ze.body,createdAt:_e(ze.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ze.userId,userName:ze.userName||""}));return[K(d,{...Y[0],attachments:ge.get(_)??[],labels:pe,postedCommentRows:ps},p)]},forceRefresh:h,snapshot:T,admission:M,ttlMsOverride:x??ne,epochKey:`${ie}${u}`}))[0]??null},ji=async(d,u,p,h={})=>{let T=await Z(p);return T?Ct(d,u,T,h):null},zi=async(d,u,p)=>{if(u.length>Ie.maxDetailIds)throw se("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${Ie.maxDetailIds} ids`,u.length);let h=await Z(p);return!h||u.length===0?[]:ve(d.visible)?[]:Pr(d,h,(0,g.inArray)(s.id,[...u]))},Gi=async(d,u)=>{let[p]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).where((0,g.and)((0,g.eq)(s.id,d),ke(u,"author")));return p??null},Lr=async(d,u,p)=>{let h=await Gi(u,p);if(!h||h.deletedAt||!Ne(d.visible,h.sourceType))throw new Error("Not Found")},Ki=async(d,u,p,h,T,x)=>{await Lr(d,p,u);let M=await t.select().top(1).from(R).where((0,g.and)((0,g.eq)(R.hubId,p),(0,g.eq)(R.userId,u))),k;if(M.length>0?M[0].isStarred!==T?k=(await t.update(R).set({isStarred:T,updatedAt:new Date,updatedBy:String(u)}).output().where((0,g.and)((0,g.eq)(R.hubId,p),(0,g.eq)(R.userId,u))))[0]:k=M[0]:k=(await t.insert(R).output().values({hubId:p,userId:u,isStarred:T,isRead:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],h){let L=Pe(h);L&&(l.invalidatePrefix(Tt(L,u)),await re(`${ee}${L}`))}return l.invalidatePrefix(Ar(p,u)),await re(`${ie}${p}`),await Ae(er.parse({type:"status-update",reportHubId:p,recipientRawUserId:u,statusType:"star",value:T,clientTempId:x}),"setStarStatus"),k},Ji=async(d,u,p,h,T,x)=>{await Lr(d,p,u);let M=await t.select().top(1).from(R).where((0,g.and)((0,g.eq)(R.hubId,p),(0,g.eq)(R.userId,u))),k;if(M.length>0?M[0].isRead!==T?k=(await t.update(R).set({isRead:T,updatedAt:new Date,updatedBy:String(u)}).output().where((0,g.and)((0,g.eq)(R.hubId,p),(0,g.eq)(R.userId,u))))[0]:k=M[0]:k=(await t.insert(R).output().values({hubId:p,userId:u,isRead:T,isStarred:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],h){let L=Pe(h);L&&(l.invalidatePrefix(Tt(L,u)),await re(`${ee}${L}`))}return l.invalidatePrefix(Ar(p,u)),await re(`${ie}${p}`),await Ae(er.parse({type:"status-update",reportHubId:p,recipientRawUserId:u,statusType:"read",value:T,clientTempId:x}),"setReadStatus"),k},Ln=async(d,u)=>{if(u===null)return;let p=await qt();if(p.length===0)return;let[h]=await t.select({hubId:f.hubId}).top(1).from(f).where((0,g.and)((0,g.eq)(f.hubId,d),(0,g.inArray)(f.labelId,p)));return h?u:void 0},Qi=async(d,u,p,h,T,x)=>{let[M]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where((0,g.eq)(s.id,p));if(!M||M.deletedAt)throw new Error("Not Found");if(await Lr(d,p,u),!Ne(d.commentable,M.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(M.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let k=await Ln(p,M.userId),L=de(),Y=await I(async ge=>{let[pe]=await ge.insert(m).output().values({hubId:p,userId:u,body:h,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)});return L!==null&&await L.writeHubs(ge,[p]),pe}),[_]=await t.select({displayName:n.displayName}).top(1).from(n).where((0,g.eq)(n.id,u)),Q=_?.displayName??"";if(T){let ge=Pe(T);ge&&(l.invalidatePrefix(Ht(ge)),await re(`${ee}${ge}`))}l.invalidatePrefix(qe(p)),await re(`${ie}${p}`);let oe={id:Y.id,userId:a(Y.userId),userName:Q,content:Y.body,createdAt:_e(Y.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await Ae(jr.parse({type:"comment-add",reportHubId:p,comment:oe,clientTempId:x,recipientRawUserId:k,sourceType:M.sourceType}),"addComment"),oe},Xi=async(d,u)=>await d.select().top(1).from(m).where((0,g.eq)(m.id,u)),Zi=async(d,u,p,h,T,x)=>{let M=await Xi(t,h);if(M.length===0)throw new Error("Not Found");if(M[0].hubId!==p)throw new Error("Not Found");let[k]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where((0,g.eq)(s.id,M[0].hubId));if(!(k&&Ne(d.visible,k.sourceType)))throw new Error("Not Found");if(M[0].userId!==u)throw new Error("Unauthorized");let L=await Ln(p,k.userId),Y=de();if(await I(async _=>{await _.delete(m).where((0,g.eq)(m.id,h)),Y!==null&&await Y.writeHubs(_,[p])}),T){let _=Pe(T);_&&(l.invalidatePrefix(Ht(_)),await re(`${ee}${_}`))}l.invalidatePrefix(qe(p)),await re(`${ie}${p}`),await Ae(zr.parse({type:"comment-delete",reportHubId:p,commentId:h,clientTempId:x,recipientRawUserId:L,sourceType:k?.sourceType}),"deleteComment")},es=async(d,u)=>{let p=new Map,h=r.attachment;if(!h||B===null)return p;let T=await d.select({hubId:h.hubId,fileName:h.fileName}).from(h).where((0,g.inArray)(h.hubId,[...u])).orderBy((0,g.asc)(h.hubId),(0,g.asc)(h.createdAt),(0,g.asc)(h.id));for(let x of T)Cn(p,Number(x.hubId),String(x.fileName));return p},ts=async(d,u,p)=>{let h=new Map;for(let[T,x]of p){let M=new Map;for(let{hub:L}of u)L.sourceType===T&&L.sourceIdNum!==null&&M.set(L.sourceIdNum,L.id);if(M.size===0)continue;let k=await x(d,[...M.keys()]);for(let[L,Y]of k){let _=M.get(L);if(_===void 0)throw se(`search.externalSourceTexts.${T} answer key`,"a source id that was asked for",L);if(!(Array.isArray(Y)&&Y.every(Q=>typeof Q=="string")))throw se(`search.externalSourceTexts.${T} answer for ${L}`,"an array of strings",Y);h.set(_,Y)}}return h},rs=(d,u)=>{let p=j(d),h=[["subject",d.hub.title],["content",p.content],["author",p.author],["employeeName",p.employeeName],["updatedBy",p.updatedBy],["category",p.category],["creationCategory",p.creationCategory],["customerName",p.customerName]];for(let x of p.interviewers)h.push(["interviewerName",x.name??null],["interviewerAffiliation",x.affiliation??null]);for(let x of u.labelNames)h.push(["label",x]);for(let x of u.attachmentNames)h.push(["attachment",x]);for(let x of u.extraTexts)h.push(["extra",x]);let T=[];for(let x of p.externalComments)T.push({authorUserId:null,text:Ai(x.name,x.text)});for(let x of u.postedComments)T.push({authorUserId:x.userId,text:Ai(x.userName,x.body)});return{hubId:d.hub.id,fields:h,comments:T}},ns=async(d,u,p)=>{let h=[];for(let T of(0,xt.chunk)(u,xt.MAX_IN_LIST)){let x=await F(d.select({hub:et(s),internal:et(y),creatorName:n.displayName,...E()}).from(s)).leftJoin(y,(0,g.eq)(s.id,y.hubId)).leftJoin(n,(0,g.eq)(s.userId,n.id)).where((0,g.inArray)(s.id,[...T])).orderBy((0,g.asc)(s.id)),M=new Map,k=await d.select({hubId:f.hubId,name:S.name}).from(f).innerJoin(S,(0,g.eq)(f.labelId,S.id)).where((0,g.inArray)(f.hubId,[...T])).orderBy((0,g.asc)(f.hubId),(0,g.asc)(S.id));for(let oe of k)Cn(M,oe.hubId,oe.name);let L=new Map,Y=await d.select({hubId:m.hubId,userId:m.userId,body:m.body,userName:n.displayName}).from(m).leftJoin(n,(0,g.eq)(m.userId,n.id)).where((0,g.inArray)(m.hubId,[...T])).orderBy((0,g.asc)(m.hubId),(0,g.asc)(m.createdAt),(0,g.asc)(m.id));for(let oe of Y)Cn(L,oe.hubId,oe);let _=await es(d,T),Q=await ts(d,x,p);for(let oe of x){let ge=oe.hub.id;h.push(rs(oe,{labelNames:xr(M,ge),postedComments:xr(L,ge),attachmentNames:xr(_,ge),extraTexts:xr(Q,ge)}))}}return h},os=(d,u,p)=>U===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):U.search(t,{plan:p,viewerUserId:u,scope:d}),as=async(d,u,p,h,T)=>{if(U===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(h.length>Ie.maxDetailIds)throw se("markDailyReportSearchHits: reportHubIds",`at most ${Ie.maxDetailIds} ids`,h.length);let{signal:x}=T,M=Qt(kt(p));if(h.length===0||ve(d.visible))return{wordsDigest:M,reports:[]};x.throwIfAborted();let k=await Pr(d,u,(0,g.inArray)(s.id,[...h]));x.throwIfAborted();let L=p.combine==="union"&&p.sets.length>=2&&k.length>0?await U.matchedSets(t,{plan:p,viewerUserId:u,scope:d,ids:k.map(_=>_.reportHubId)}):null,Y=[];for(let _ of k){Y.length>0&&await new Promise(ge=>setImmediate(ge)),x.throwIfAborted();let Q=L===null?null:L.get(_.reportHubId),oe=Q===void 0?0:Q;Y.push({reportHubId:_.reportHubId,matchedSets:oe,fields:gi(_,Si(p,oe))})}return{wordsDigest:M,reports:Y}},is=d=>{let u=de();return u===null?Promise.reject(new Error("[daily-report] reconcileSearchIndex: the search setting is not configured")):u.reconcile(t,d)},ss=async(d,u,p)=>{if(!Jt(u))throw se("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",u);H.info("createDailyReport called",{userId:d,businessDate:u});let[h]=await t.select({displayName:n.displayName}).from(n).where((0,g.eq)(n.id,d)),T=h?.displayName??a(d),x=de();try{let M=await I(async L=>{H.info("Starting transaction");let Y=`internal-temp-${Date.now()}-${Math.random()}`,[_]=await L.insert(s).output().values({sourceType:"Internal",sourceId:Y,businessDate:new Date(`${u}T00:00:00Z`),userId:d,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)});await L.update(s).set({sourceId:String(_.id)}).where((0,g.eq)(s.id,_.id)),H.info("Hub created",_),await L.insert(y).values({hubId:_.id,body:"",createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}),H.info("Internal created"),H.info("Calling getDraftLabelId");let Q=await Mr();H.info("draftLabelId",Q);let oe=[];return Q&&(await L.insert(f).values({hubId:_.id,labelId:Q,createdAt:new Date,createdBy:String(d)}),oe.push({id:Q,name:w,color:null})),H.info("Label assigned"),x!==null&&await x.writeHubs(L,[_.id]),{reportHubId:_.id,date:u,createdAt:_e(_.createdAt,"YYYY-MM-DD HH:mm:ss"),author:T,userId:a(d),sourceType:"Internal",employeeName:T,updatedBy:a(d),updatedAt:_e(_.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:_.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:oe,postedComments:[],attachments:[]}});l.invalidatePrefix(Tt(u,d)),l.invalidatePrefix(ct),l.invalidatePrefix(bn(d)),await re(W),await re(`${ee}${u}`);let k=await Ct(Ce.unrestricted("post-write self read: the writer always sees the row they just wrote"),M.reportHubId,d,{forceRefresh:!0});if(k){let L=await qt(),Y=k.labels.some(_=>L.includes(_.id));await Ae(Gr.parse({type:"report-create",reportHubId:k.reportHubId,report:k,clientTempId:p,recipientRawUserId:Y?d:void 0}),"createDailyReport")}return k??M}catch(M){throw H.error("Error in createDailyReport",M),M}},jt=async(d,u)=>await d.select().top(1).from(s).where((0,g.eq)(s.id,u)),Or=async(d,u,p)=>{await d.update(s).set(p).where((0,g.eq)(s.id,u))},On=async(d,u,p)=>{await d.update(y).set(p).where((0,g.eq)(y.hubId,u))},Nn=async(d,u,p)=>{await d.delete(f).where((0,g.and)((0,g.eq)(f.hubId,u),(0,g.eq)(f.labelId,p)))},ls=async(d,u,p)=>{let h=await jt(t,d);if(!h.length||h[0].deletedAt)throw new Error("Not Found");if(h[0].userId!==u)throw new Error("Unauthorized");let T=de();if(await I(async x=>{await Or(x,d,{deletedAt:new Date,deletedBy:String(u),updatedAt:new Date,updatedBy:String(u)}),T!==null&&await T.writeHubs(x,[d])}),l.invalidatePrefix(qe(d)),l.invalidatePrefix(ct),l.invalidatePrefix(lt),await re(W),h[0].businessDate){let x=Pe(_e(h[0].businessDate,"YYYY-MM-DD"));x&&await re(`${ee}${x}`)}await Ae(Qr.parse({type:"report-delete",reportHubId:d,clientTempId:p,sourceType:h[0].sourceType}),"deleteDailyReport")},cs=async(d,u,p,h)=>{let T=await jt(t,d);if(!T.length||T[0].deletedAt)throw new Error("Not Found");if(T[0].userId!==u)throw new Error("Unauthorized");let x=de();await I(async L=>{p.title!==void 0&&await Or(L,d,{title:Di(p.title),updatedAt:new Date,updatedBy:String(u)}),p.content!==void 0&&await On(L,d,{body:Di(p.content),updatedAt:new Date,updatedBy:String(u)}),x!==null&&await x.writeHubs(L,[d])}),l.invalidatePrefix(qe(d)),l.invalidatePrefix(ct),await re(`${ie}${d}`);let M=Pe(_e(T[0].businessDate,"YYYY-MM-DD"));M&&(l.invalidatePrefix(Ht(M)),await re(`${ee}${M}`));let k=await Ct(Ce.unrestricted("post-write self read: the writer always sees the row they just wrote"),d,u,{forceRefresh:!0});if(k){let L=await qt(),Y=k.labels.some(_=>L.includes(_.id));await Ae(Kr.parse({type:"report-update",reportHubId:k.reportHubId,report:k,clientTempId:h,recipientRawUserId:Y?u:void 0}),"updateDailyReport")}},us=async(d,u,p)=>{let h=await jt(t,d);if(!h.length)throw new Error("Not Found");if(h[0].userId!==u)throw new Error("Unauthorized");let T=await Mr();if(!T)return null;let x=de();if(await I(async L=>{await Nn(L,d,T),x!==null&&await x.writeHubs(L,[d])}),l.invalidatePrefix(qe(d)),l.invalidatePrefix(ct),l.invalidatePrefix(lt),await re(W),h[0].businessDate){let L=Pe(_e(h[0].businessDate,"YYYY-MM-DD"));L&&await re(`${ee}${L}`)}let M=Pe(_e(h[0].businessDate,"YYYY-MM-DD"));M&&l.invalidatePrefix(Tt(M,u));let k=await Ct(Ce.unrestricted("post-write self read: the writer always sees the row they just wrote"),d,u,{forceRefresh:!0});return k&&await Ae(Jr.parse({type:"report-publish",reportHubId:k.reportHubId,report:k,clientTempId:p}),"publishDailyReport"),k??null},ds=async(d,u)=>{l.invalidatePrefix(ct),l.invalidatePrefix(lt),await re(W);for(let p of new Set(d))l.invalidatePrefix(qe(p)),await re(`${ie}${p}`);for(let p of new Set(u)){let h=Pe(p);h&&await re(`${ee}${h}`)}},ms=async()=>{l.clearAll(),P.clear(),ht=null,c&&await re(W),H.info("Server-side DB/SQL caches cleared successfully.")};return{streamKey:fe,streamMaxLen:je,attachmentDelivery:B,titleMaxLength:C,searchLimits:V===null?null:{concurrency:V.concurrency,rateLimitPerMinute:V.rateLimitPerMinute},clearCache:ms,invalidateHubReadCaches:ds,getUserIdByExternalId:Z,getDailyReportIdsByExternalId:De,getDailyReportIdsFirstPageByExternalId:z,readSseStreamAnchor:v,getDailyReportsByBusinessDate:yt,getDailyReportsByBusinessDateByExternalId:Wi,getDailyReportDetailById:Ct,getDailyReportDetailByIdByExternalId:ji,getDailyReportDetailsByIdsByExternalId:zi,getDraftLabelId:Mr,searchDailyReports:os,markDailyReportSearchHits:as,reconcileSearchIndex:is,getAttachmentsByHubIds:Wt,getAttachmentForUser:Vi,markAttachmentMissing:Yi,markAttachmentPresent:qi,setStarStatus:Ki,setReadStatus:Ji,addComment:Qi,deleteComment:Zi,createDailyReport:ss,updateDailyReport:cs,publishDailyReport:us,deleteDailyReport:ls,findDailyReportHubById:jt,updateDailyReportHub:Or,updateDailyReportInternal:On,deleteDailyReportLabel:Nn}}var Ti=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(Re(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return Re(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};var Vt=require("drizzle-orm"),D=require("drizzle-orm/mssql-core");function Ei(e,t){let r=(0,D.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,D.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,D.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,D.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,D.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(Vt.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,D.date)("business_date"),userId:(0,D.bigint)("user_id",{mode:"number"}),title:(0,D.nvarchar)("title",{length:200}),summary:(0,D.nvarchar)("summary",{length:"max"}),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,D.datetime2)("deleted_at"),deletedBy:(0,D.nvarchar)("deleted_by",{length:50})},m=>[(0,D.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[m.id]}),(0,D.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,D.index)(`${e}_DailyReportHub_business_date_index`).on(m.businessDate),(0,D.index)(`${e}_DailyReportHub_updated_at_index`).on(m.updatedAt),(0,D.index)(`${e}_DailyReportHub_source_index`).on(m.sourceType,m.sourceId),(0,D.index)(`${e}_DailyReportHub_user_id_index`).on(m.userId),(0,D.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,Vt.desc)(m.businessDate),(0,Vt.desc)(m.id)),(0,D.index)(`${e}_DailyReportHub_deleted_at_index`).on(m.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,D.nvarchar)("body",{length:"max"}),metadata:(0,D.nvarchar)("metadata",{length:"max"}),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[m.hubId]}),(0,D.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:(0,D.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,D.bigint)("user_id",{mode:"number"}).notNull(),body:(0,D.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[m.id]}),(0,D.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,D.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,D.index)(`${e}_DailyReportComment_hub_id_index`).on(m.hubId)]),l=r.table("DailyReportLabel",{id:(0,D.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,D.bigint)("user_id",{mode:"number"}),name:(0,D.nvarchar)("name",{length:50}).notNull(),color:(0,D.nvarchar)("color",{length:20}),sortOrder:(0,D.int)("sort_order"),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[m.id]}),(0,D.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),c=r.table("DailyReportHub_Label",{hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,D.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[m.hubId,m.labelId]}),(0,D.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,D.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[m.labelId],foreignColumns:[l.id]})]),s=r.table("DailyReportUserStatus",{hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,D.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,D.bit)("is_read").default(!1).notNull(),isStarred:(0,D.bit)("is_starred").default(!1).notNull(),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[m.hubId,m.userId]}),(0,D.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,D.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),y=r.table("DailyReportAttachment",{id:(0,D.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,D.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,D.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,D.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,D.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,D.nvarchar)("file_type",{length:100}),fileSize:(0,D.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,D.datetime2)("object_checked_at"),objectMissingAt:(0,D.datetime2)("object_missing_at"),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[m.id]}),(0,D.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,D.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[m.uploadedBy],foreignColumns:[n.id]}),(0,D.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(m.hubId,m.sourceKey),(0,D.index)(`${e}_DailyReportAttachment_hub_id_index`).on(m.hubId,m.createdAt)]);return{hub:o,internal:a,comment:i,attachment:y,label:l,hubLabel:c,userStatus:s}}var he=require("drizzle-orm/mssql-core");function Ii(e){let t=(0,he.mssqlSchema)(e),r=t.table("DailyReportSearchDocument",{hubId:(0,he.bigint)("hub_id",{mode:"number"}).notNull(),searchText:(0,he.nvarchar)("search_text",{length:"max"}).notNull(),sourceDigest:(0,he.binary)("source_digest",{length:32}).notNull(),normalizerVersion:(0,he.varchar)("normalizer_version",{length:64}).notNull(),indexedAt:(0,he.datetime2)("indexed_at").notNull(),rowVersion:(0,he.binary)("row_version",{length:8}).notNull()},o=>[(0,he.primaryKey)({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:(0,he.bigint)("hub_id",{mode:"number"}).notNull(),ordinal:(0,he.int)("ordinal").notNull(),authorUserId:(0,he.bigint)("author_user_id",{mode:"number"}),commentText:(0,he.nvarchar)("comment_text",{length:"max"}).notNull()},o=>[(0,he.primaryKey)({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var Uu=5e7,Mn=2e8,$u=1,Pn=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})})}),_i=125,wi=4,xi=16,Ci=50,Mi=2,Yt=Object.freeze({renderMs:xe.renderMs,nanosecondsPerBlockVisit:_i,margin:wi,maxBlockVisits:Math.floor(xe.renderMs*1e6/(_i*wi)),walkBudgetMs:xi,nanosecondsPerWalkStep:Ci,walkMargin:Mi,maxWalkSteps:Math.floor(xi*1e6/(Ci*Mi))}),Bu=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Pi=75,Li=4,Oi="#ffffff",Fu=1,Vu={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Yu=[/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/],Ni=Object.freeze({ok:!1,reason:"failed"}),vi=Object.freeze({ok:!1,reason:"unsupported"}),ki=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:$o(e)}),Hi=(e,t)=>{switch(t){case"jpeg":{let r=dn(e);return r===null?null:ki(r)}case"png":{let r=Vo(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Yo(e,Yt.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},Ui=(e,t)=>{let r=Bu.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Pn,a=o.wholeImageBuffer[e.layout];return(a.kind==="none"?0:a.kind==="decoded-raster"?t.width*t.height*n:a.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*a.bytesPerPixel)+o.pipelineRows*t.width*n+o.fixedBytes},$i=(e,t,r)=>{let n=Hi(e,t);return n===null?null:Ui(n,r)},qu=e=>e!==null&&e<=Mn,Wu=(e,t)=>{if(t!=="jpeg")return Hi(e,t);let r=Bo(e,Yt);return r===null||r.blockVisits>Yt.maxBlockVisits?null:ki(r.header)},ju=e=>{let t=e instanceof Error?e.message:"";return Yu.some(r=>r.test(t))?"failed":"unsupported"},Bi=e=>{e.cache(!1),e.concurrency($u),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Vu)});let t=async(n,o,a,i,l)=>{let c=Wu(n,o);if(c===null)return vi;try{let s=e(n,{limitInputPixels:Uu,animated:!1});if(!qu(Ui(c,await s.metadata())))return vi;if(l.aborted)return Ni;let y=await s.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Oi}).webp({quality:Pi,effort:Li}).toBuffer();return{ok:!0,bytes:new Uint8Array(y),contentType:"image/webp"}}catch(s){return{ok:!1,reason:ju(s)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?Ni:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Pi}-e${Li}/flatten-${Oi}/v${Fu}`,render:r}};var zu=4096,Gu=6e4;function Ku(e){e.redis||Re(e.logger,2,"Server").warn("redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=zt(e.redis),r=new Rt({defaultTtlMs:te("cacheDefaultTtlMs",e.cacheDefaultTtlMs??Gu,1),maxBuckets:te("cacheMaxBuckets",e.cacheMaxBuckets??zu,1)},t),n=Cr({...e,cache:r,epochs:t}),o=new Et({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Ir({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(i=>i.sourceType)])],...a}}0&&(module.exports={DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,DAILY_REPORT_SSE_CATCH_UP_BATCH,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createEpochStore,createSharpThumbnailRenderer,defineDailyReportSchema,defineDailyReportSearchSchema,isStreamIdLte,parseClientTempId,predictSharpThumbnailWorkingSetBytes,readDailyReportSseStreamEntry,transformJsonArray});
12
12
  /* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */