@aiquants/daily-report 0.46.1 → 0.47.1

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,15 +1,15 @@
1
- "use strict";var wn=Object.defineProperty;var mc=Object.getOwnPropertyDescriptor;var yc=Object.getOwnPropertyNames;var hc=Object.prototype.hasOwnProperty;var Yo=e=>{throw TypeError(e)};var fc=(e,t)=>{for(var r in t)wn(e,r,{get:t[r],enumerable:!0})},Rc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of yc(t))!hc.call(e,o)&&o!==r&&wn(e,o,{get:()=>t[o],enumerable:!(n=mc(t,o))||n.enumerable});return e};var Sc=e=>Rc(wn({},"__esModule",{value:!0}),e);var zo=(e,t,r)=>t.has(e)||Yo("Cannot "+r);var sr=(e,t,r)=>(zo(e,t,"read from private field"),r?r.call(e):t.get(e)),In=(e,t,r)=>t.has(e)?Yo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),_n=(e,t,r,n)=>(zo(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Bm={};fc(Bm,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>Jr,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>Kr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>Uo,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Lr,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>Bo,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>dn,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>_o,DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS:()=>Vo,DailyReportSseReader:()=>nr,DailyReportViewerScope:()=>Qe,SqlResultCache:()=>Yt,buildDailyReportRedisKeys:()=>gn,createDailyReportHandlers:()=>pn,createDailyReportServer:()=>Um,createDailyReportService:()=>Tn,createDailyReportVisibilityCache:()=>ic,createEpochStore:()=>vr,createSharpThumbnailRenderer:()=>ac,dailyReportSseStreamMessageSchema:()=>$r,defineDailyReportSchema:()=>ql,defineDailyReportSearchSchema:()=>jl,encodeIdsStreamRows:()=>Ft,isStreamIdLte:()=>mt,parseClientTempId:()=>jr,predictSharpThumbnailWorkingSetBytes:()=>oc,readDailyReportSseStreamEntry:()=>er,transformJsonArray:()=>Vl});module.exports=Sc(Bm);var Nt=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,Z=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Nt(r)}`),Ke=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),xn=(e,t,r)=>Z(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),le=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw Z(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},Ne=(e,t,r,n)=>t===void 0?n:le(e,t,r),lr=(e,t)=>{if(t===void 0)throw Ke(e,"a function");if(typeof t!="function")throw Z(e,"a function",t);return t};var ce=()=>Math.floor(performance.now());var Cn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),tt=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},vr=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{}}}),cr=(e,t)=>t?e.map(r=>structuredClone(r)):e,gc=8,bc=32,Dc=24,Ac=16,Tc=-(2**30),Ec=2**30-1,wc=e=>Number.isInteger(e)&&e>=Tc&&e<=Ec&&!Object.is(e,-0),Ic=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=bc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=gc*a.length;for(let i of a)typeof i=="string"?r+=Dc+2*i.length:typeof i=="number"&&!wc(i)?r+=Ac:typeof i=="object"&&i!==null&&n.push(i)}return r},Yt=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;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 s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:c,expireAt:ce()+a,epoch:s}),c})(),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,s=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&s===null)throw new tt(o.signal.aborted?"aborted":"busy");try{for(let d of r)d();let c=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:c,expireAt:ce()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),c}finally{s?.()}})(),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 tt("aborted");return this.dropBucket(r),cr(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ce())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),cr(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),cr(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return cr(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new tt("aborted");return cr(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 tt&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.totalBytes=0,this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.dropBucket(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=Ne("cacheDefaultTtlMs",t.defaultTtlMs,1,Cn.defaultTtlMs),this.maxBuckets=Ne("cacheMaxBuckets",t.maxBuckets,1,Cn.maxBuckets),this.maxBytes=Ne("cacheMaxBytes",t.maxBytes,1,Cn.maxBytes),this.lastSweepAt=ce()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=Ic(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=ce();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};var Ks=require("@aiquants/request-isolation");var _c=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Go=e=>e<10?`0${e}`:`${e}`,xc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Go(e.getMonth()+1),n=Go(e.getDate());return`${t}-${r}-${n}`},zt=e=>{let t=_c.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 s=new Date(0);return s.setUTCFullYear(a,i-1,l),s.getUTCFullYear()!==a||s.getUTCMonth()!==i-1||s.getUTCDate()!==l?null:`${r}-${n}-${o}`},Nr=e=>zt(e)===e;var qe=e=>e==null?null:e instanceof Date?xc(e):zt(e);var Ko=require("zod/v3"),lt=e=>Number.isSafeInteger(e)&&e>0,Oe=Ko.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var re=require("zod/v3");var Or=/^(?:[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 Ot=Symbol("daily-report wire mismatch"),ct=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),Ot),Zo=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,Ht=(e,t)=>({code:"invalid_type",expected:e,received:Zo(t)}),Cc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Mc=e=>{let t=0;for(let r in e)t+=1;return t},Jo=(e,t,r)=>{let n={};for(let o=0;o<r;o+=1){let a=t[o];a in e&&(n[a]=e[a])}return n},Gt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!Cc(n))return ct(o,null,Ht("object",n));let a=null,i=!1,l=0;for(let s=0;s<t.length;s+=1){let c=t[s],d=n[c];d!==void 0&&(l+=1);let u=r[s](d,o,c);if(u===Ot){i=!0;continue}a===null&&u!==d&&(a=Jo(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?Ot:a!==null?a:Mc(n)===l?n:Jo(n,t,t.length)}},ur=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},dr=e=>(t,r,n)=>{if(!Array.isArray(t))return ct(r,n,Ht("array",t));r.path.push(n);let o=t,a=!1;for(let i=0;i<t.length;i+=1){let l=t[i],s=e(l,r,i);s===Ot?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?Ot:o},me=(e,t,r)=>e==null||typeof e=="string"?e:ct(t,r,Ht("string",e)),Qo=(e,t,r)=>e===null||typeof e=="string"?e:ct(t,r,Ht("string",e)),Xo=(e,t,r)=>typeof e=="string"?e:ct(t,r,Ht("string",e)),Pc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:ct(t,r,Ht("number",e)),pr=(e,t,r)=>typeof e=="boolean"?e:ct(t,r,Ht("boolean",e)),Mn=(e,t,r)=>{if(typeof e=="number"&&lt(e))return e;for(let{message:n,path:o,...a}of Oe.safeParse(e).error.issues)ct(t,r,a);return Ot},ea={present:!0,absent:!0,unknown:!0},ta=Object.keys(ea),kc=ta.map(e=>`'${e}'`).join(" | "),Lc=(e,t,r)=>typeof e!="string"?ct(t,r,{code:"invalid_type",expected:kc,received:Zo(e)}):Object.hasOwn(ea,e)?e:ct(t,r,{code:"invalid_enum_value",received:e,options:[...ta]}),ra=Gt({name:me,affiliation:me}),na=Gt({name:me,text:me,color:me}),oa=Gt({id:Mn,name:me,color:me}),aa=Gt({id:Mn,userId:me,userName:me,content:me,createdAt:me,isMine:pr}),vc=Gt({id:Xo,fileName:Xo,fileType:Qo,fileSize:Pc,createdAt:Qo,state:Lc,hasThumbnail:pr}),Nc=Gt({reportHubId:Mn,date:me,createdAt:me,author:me,userId:me,sourceType:me,employeeName:me,updatedBy:me,updatedAt:me,category:me,creationCategory:me,visitTimeFrom:me,visitTimeTo:me,customerName:me,interviewers:dr(ur(ra)),subject:me,content:me,externalComments:dr(ur(na)),isRead:pr,isStarred:pr,isDraft:pr,labels:dr(ur(oa)),postedComments:dr(ur(aa)),attachments:dr(ur(vc))}),mr=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===Ot?{ok:!1,issues:r.issues}:{ok:!0,value:n}},ia=e=>mr(Nc,e),sa=e=>mr(ra,e),la=e=>mr(na,e),ca=e=>mr(oa,e),ua=e=>mr(aa,e);var da=15e3,pa="lastEventId",Oc=/^\d{1,15}-\d{1,15}$/,ma=e=>Oc.test(e),_t="0-0",yr=e=>re.z.unknown().transform((t,r)=>{let n=e(t);if(n.ok)return n.value;for(let o of n.issues)r.addIssue({...o,fatal:!0});return re.z.NEVER}),ry=yr(sa),ny=yr(la),oy=yr(ca),Hc=yr(ua),hr=yr(ia),fr=re.z.string().regex(Or),ya=re.z.object({type:re.z.literal("connected")}),ha=re.z.object({type:re.z.literal("status-update"),reportHubId:Oe,statusType:re.z.enum(["star","read"]),value:re.z.boolean(),clientTempId:fr}),Pn=re.z.string(),fa=re.z.object({type:re.z.literal("comment-add"),reportHubId:Oe,comment:Hc,clientTempId:fr,sourceType:Pn}),Ra=re.z.object({type:re.z.literal("comment-delete"),reportHubId:Oe,commentId:Oe,clientTempId:fr,sourceType:Pn}),Hr={recipientRawUserId:Oe.optional()},kn=ha.extend(Hr),Ln=fa.extend(Hr),vn=Ra.extend(Hr),Kt={reportHubId:Oe,report:hr,clientTempId:fr},Nn={...Hr,actorRawUserId:Oe},On={viewerIsActor:re.z.boolean()},Fc=re.z.object({type:re.z.literal("report-create"),...Kt,...On}),$c=re.z.object({type:re.z.literal("report-update"),...Kt,...On}),Uc=re.z.object({type:re.z.literal("report-publish"),...Kt,...On}),Hn=re.z.object({type:re.z.literal("report-create"),...Kt,...Nn}),Fn=re.z.object({type:re.z.literal("report-update"),...Kt,...Nn}),$n=re.z.object({type:re.z.literal("report-publish"),...Kt,...Nn}),Fr=re.z.object({type:re.z.literal("report-delete"),reportHubId:Oe,clientTempId:fr,sourceType:Pn}),ay=re.z.discriminatedUnion("type",[ya,ha,fa,Ra,Fc,$c,Uc,Fr]),$r=re.z.discriminatedUnion("type",[ya,kn,Ln,vn,Hn,Fn,$n,Fr]);var Sa="ids-columns";var Bc=/^[0-9a-f]{1,16}$/,ga=e=>lt(e.reportHubId)&&(e.businessDate===null||Nr(e.businessDate)),ba=e=>typeof e=="string"&&Bc.test(e),cy=Object.freeze({kind:"absent"}),uy=Object.freeze({kind:"value",value:null});var Ft=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:h}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let p=h===void 0?null:h,y=s.get(p);y===void 0&&(y=i.length,i.push(p),s.set(p,y)),l.push(y)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},Ur=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+(?=.)/,"")},Da=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Vc=(e,t,r,n)=>Da(e,t,r,n)<0,Un=(e,t)=>Da(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Aa=e=>{for(let t=1;t<e.length;t++)if(!Vc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},Ta=(e,t)=>{let r=e.findIndex(n=>Un({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var ue=Object.freeze({businessDate:"business-date",idsStream:Sa,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),Te=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var Ea=(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)}}},yy=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),wa=e=>`[DailyReport${e}]`,Ee=(e,t,r)=>e===void 0?Ea(t,wa(r)):Ea(0,wa(r),e);var xt=require("zod/v3");var Rr=e=>({reportHubId:e,outcome:"not_found"}),Sy=xt.z.discriminatedUnion("outcome",[xt.z.object({reportHubId:Oe,outcome:xt.z.literal("ok"),report:hr}).strict(),xt.z.object({reportHubId:Oe,outcome:xt.z.literal("not_found")}).strict(),xt.z.object({reportHubId:Oe,outcome:xt.z.literal("failed")}).strict()]);var qc="legacy-",Bn=e=>`${qc}${e}`;var jc=/^[1-9][0-9]*$/,Wc=/^(?:0|[1-9][0-9]*)$/,rt=e=>{if(e===null||!jc.test(e))return null;let t=Number(e);return lt(t)?t:null},Vn=e=>{if(e===null||!Wc.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},qn=e=>e==="true"?!0:e==="false"?!1:null,Sr=e=>e===null?!1:qn(e);var Ia=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),Rt=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var Yc=16777619,jn=2166136261,Wn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,Yc);return o>>>0},_a=e=>Wn(jn,e,0,e.length),zc=String.fromCodePoint(3),Gc=String.fromCodePoint(2),Kc=String.fromCodePoint(1),Br=e=>_a(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(zc)).join(Gc)).join(Kc));var xa=e=>e==="intersection"||e==="union",Pe=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Yn=2,Vr=2,$t=Object.freeze({word:0,reading:1});var zn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var Ey=2*(1+Yn);var Jc=require("zod/v3");var Ca=e=>e.issues.map(t=>`${t.path.length===0?"(root)":t.path.join(".")}: ${t.code}`).join("; ");var Je=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var qr=Math.max(1,Math.floor(10.556701030927835));var nt=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var ke=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(c=>[c,0]))};o.set(i,l),nt(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var St=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var ky=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),Qc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Gn=e=>{let t=e.trim();return t.length===0?null:t.replace(Qc,"\uFFFD")},Xc=e=>{let t=Gn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>St.maxValueLength?"filter-value-too-long":null},Zc=e=>{if(e.length>St.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=Xc(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},eu=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Ma=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Zc(t);if(r!==null)return r}return eu(e)>St.maxTotalValueLength?"filters-too-long":null};var Pa=e=>e.trim().length===0;var jr=e=>e!==null&&Or.test(e)?e:null,Kn=e=>xa(e)?e:null,Jn=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=rt(n);if(o===null||r.includes(o))return null;r.push(o)}return r},ka=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},La=(e,t)=>{let r={authors:e.getAll(Te.searchAuthor),sourceTypes:e.getAll(Te.searchSourceType),customers:e.getAll(Te.searchCustomer)},n=Ma(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:ka(r.authors),customers:ka(r.customers)}}},va=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Oa=Object.freeze({status:400,error:"Invalid form"}),Ha=e=>({status:413,error:"Form too large",measuredBy:e}),tu=(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)}}))},ru=async e=>{let t=Vn(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Ha("declared")};let r=!1,n=e.body===null?null:tu(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?Ha("counted"):Oa}}let l=va(i);return l===null?{refusal:Oa}:{fields:l}},Fa=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=qn(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},Ua=Object.freeze({update:(e,t,r)=>{let n=e.get(Je.title),o=e.get(Je.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:Fa("toggleStar",Je.isStarred),toggleRead:Fa("toggleRead",Je.isRead),addComment:(e,t)=>{let r=e.get(Je.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=rt(e.get(Je.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),nu=e=>Object.hasOwn(Ua,e),ou=(e,t)=>{let r=e.get(Je.intent),n=e.get(Je.businessDate),o=n===null?null:zt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Je.operationTimestamp),i=Vn(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Je.clientTempId);if(!l)return{error:"clientTempId required"};let s=jr(l);if(s===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:i}};let c=rt(e.get(Je.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!nu(r)?{error:"Invalid intent"}:Ua[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Ba=async(e,t)=>{let r=await ru(e);if("refusal"in r)return r;let n=ou(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},au=6e4,iu="form_too_large",$a=["declared","counted"],Va=e=>{let t=ke({windowMs:au,tallies:$a,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${$a.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(iu,r,n)}};var Ut=Object.freeze({[ue.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ue.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[ue.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ue.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[ue.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[ue.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[ue.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),qa=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Qn=e=>e!==void 0&&Object.hasOwn(Ut,e);var Xn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),ja=e=>Object.hasOwn(Xn,e);var su="download",lu="thumbnail",cu="1";var Zn=e=>{let t=e.getAll(lu),r=e.getAll(su);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&ja(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===cu?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var Ka=require("@aiquants/request-isolation");var Wa=require("crypto"),eo=e=>`"${(0,Wa.createHash)("sha256").update(e).digest("hex")}"`,Ya=e=>eo(JSON.stringify(e));var ut=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),to=(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},za=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=eo(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...ut});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&to(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},ro=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...ut});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},no=e=>(t,r,n,o)=>{if(o!==200)return ro(r,n,o);if(e===null||n===null)throw new Error(`[daily-report] API route: a 200 JSON answer needs an answer of a JSON 200 and a body; got ${e===null?"a responder without one":"an answer"} and ${n===null?"no body":"a body"}`);return e(t,r,n)},uu=5e3/1e3,du=new Map([[503,uu]]),_e=e=>{let t=du.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var ao="Cross-site request rejected",pu="Not Found",Ga=["api","action","sse","attachment"],Ja=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...ut}}),mu=()=>Ja(403,ao),Wr=()=>Ja(404,pu),gr=Object.freeze({...Ka.NO_CROSS_ORIGIN_NAVIGATION,frameworkDataRefusal:()=>null,crossSiteRejection:mu}),Qa=e=>new URL(e.url).pathname.endsWith(".data"),yu=6e4,hu="refusals",fu=32,Ru=/^[a-z-]+$/,oo=e=>{if(e===null)return"-";let t=e.slice(0,fu);return Ru.test(t)&&t===e?e:JSON.stringify(t)},Xa=e=>{let t=ke({windowMs:yu,tallies:Ga,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${Ga.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n,o)=>{let a=()=>{let{headers:i}=o;e.warn(`cross_site_rejected route=${r} reason=${n} site=${oo(i.get("Sec-Fetch-Site"))} mode=${oo(i.get("Sec-Fetch-Mode"))} dest=${oo(i.get("Sec-Fetch-Dest"))} method=${o.method}`)};t.record(hu,r,a)}};var Za=(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 Su="same-origin",gu="SAMEORIGIN",Jt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Su,"X-Frame-Options":gu}),Yr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Jt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},ei=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),bu=/^[\x20-\x7E]+$/,Du=/^[\w.+-]+\/[\w.+-]+/,io=e=>e&&bu.test(e)&&Du.test(e)?e:null,Au=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,ti=e=>encodeURIComponent(e.replace(Au,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),ri=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),br={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},ni={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},zr=e=>typeof e=="string"&&Object.hasOwn(ni,e),Gr=e=>ni[e],gt="Attachment request failed";var dt=e=>{let t=le("limit",e.limit,1),r=le("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:le("queue.max",e.queue.max,0),maxPerOwner:le("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:le("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(m,R)=>m.get(R)??0,c=(m,R,A)=>{let w=s(m,R)+A;w<=0?m.delete(R):m.set(R,w)},d=m=>s(l,m)<r,u=m=>o<t&&d(m),h=m=>(o+=1,c(l,m,1),f(m)),p=()=>{let m=-1,R=r;for(let[A,w]of a.entries()){let S=s(l,w.owner);if(S<R&&(m=A,R=S,S===0))break}return m},y=()=>{for(;o<t;){let m=p();if(m<0)return;let[R]=a.splice(m,1);c(i,R.owner,-1),R.grant(h(R.owner))}},f=m=>{let R=!1;return()=>{R||(R=!0,o-=1,c(l,m,-1),y())}};return{canAcquire:u,acquire:(m,R)=>{if(R.aborted)return Promise.resolve(null);if(u(m))return Promise.resolve(h(m));if(n===null||a.length>=n.max||s(i,m)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:A}=n,w=S=>{let g=()=>{let F=a.indexOf(x);F<0||(a.splice(F,1),c(i,m,-1),D(),S(null))},M=nt(g,A),D=()=>{clearTimeout(M),R.removeEventListener("abort",g)},x={owner:m,grant:F=>{D(),S(F)}};a.push(x),c(i,m,1),R.addEventListener("abort",g,{once:!0})};return new Promise(w)}}};var Tu=1024,so="Too many requests",Eu=(e,t)=>{le("limitPerWindow",e,1),le("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 s=l??{tokens:e,lastRefillMs:i};n(s,i),r.set(a,s);for(let c of r.keys()){if(r.size<=Tu)break;r.delete(c)}return s};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let s=r.get(a);s&&(n(s,i),s.tokens=Math.min(e,s.tokens+l))}}},bt=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(le("windowMs",r,1e3)%1e3!==0)throw Z("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Eu(e.limitPerWindow,r),i=Object.freeze({status:429,message:so,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=ke({windowMs:r,tallies:[t],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`${t}_suppressed count=${c} since=${d} ${o(s)}`)}});return{spend:(s,c)=>a.consume(s,ce())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,ce(),c)}}};var Iu=256*1024,oi=6e4,_u=e=>Math.ceil(e/2),xu=new Uint8Array(new ArrayBuffer(0)),Cu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=xu,t()},i=l=>{clearTimeout(o),o=nt(()=>{l.error(new Error(`attachment body idle for ${oi} ms`)),a()},oi)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Iu,r.byteLength);if(s>n&&l.enqueue(r.slice(n,s)),n=s,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},ai=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=bt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=dt({limit:e.concurrency,maxHeldPerOwner:_u(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:h,readAttachment:p,cookie:y,fail:f}=s,m=e.maxBytes,R=i.spend(h,`attachment=${u} viewer=${h}`);if(R)return f(R.status,R.message,R.headers);let A=await n(c,"initial");if(!A.ok)return f(503,br[503],_e(503));let w=await t.getAttachmentForUser(A.scope,u,h);if(!w)return o.warn(`404 attachment=${u} viewer=${h} reason=not_visible`),f(404,"Attachment not found");if(w.fileSize!=null&&w.fileSize>m)return o.warn(`413 attachment=${u} viewer=${h} reason=db_size`),f(413,"Attachment too large");let S=io(w.fileType),g=`filename="${ri(w.fileName)}"; filename*=UTF-8''${ti(w.fileName)}`,M=await l.acquire(h,c.signal);if(!M)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${h} reason=aborted`),f(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${h} reason=concurrency`),f(503,"Too many concurrent downloads",_e(503)));let D=!1;try{let x=await p(w.filePath,{maxBytes:m,head:c.method==="HEAD",principal:r(h),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${h} reason=aborted`),f(503,"Attachment request aborted");if(!x.ok){if(!zr(x.reason))return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=failure_reason`),f(500,gt);let $=Gr(x.reason);return x.reason==="not_found"&&a(u,!1),o.warn(`${$} attachment=${u} viewer=${h} reason=${x.reason} code=${x.code??"-"}`),f($,br[$],_e($))}if(x.bytes.byteLength>m)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),f(500,gt);let F=c.method==="HEAD";if(F&&x.size!==void 0&&x.size>m)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),f(500,gt);if(!F&&x.size!==void 0&&x.size!==x.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=size_mismatch`),f(500,gt);let I=S??io(x.contentType),v=I!==null&&ei.has(I),C=v?I:"application/octet-stream",j=v&&d.kind!=="download"?"inline":"attachment",Q=F?x.size:x.bytes.byteLength,J=new Headers({"Content-Type":C,"Content-Disposition":`${j}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Jt});return Q!==void 0&&J.set("Content-Length",String(Q)),y&&J.append("Set-Cookie",y),a(u,!0),o.info(`200 attachment=${u} viewer=${h} type=${C} disposition=${j} bytes=${Q??"-"}`),F?new Response(null,{status:200,headers:J}):(D=!0,new Response(Cu(x.bytes,M),{status:200,headers:J}))}finally{D||M()}}};var je=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),gh=je.queueWaitMs+je.readMs+je.renderMs+je.transferMarginMs;var li=require("buffer"),ci=new Set([194,198,202,206]),Mu=new Set([192,193,194,195]),ui=216,Pu=217,di=218,ku=4,Lu=64,vu=2,ii=8,si=28,Ct=12,lo=8,Nu=20,pi=Ct+lo+10,Ou=2,Dt=(e,t)=>e[t]<<8|e[t+1],Qt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},pt=(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},mi=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,yi=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),hi=e=>(e.stepsLeft-=1,e.stepsLeft>=0),fi=e=>e[0]===255&&e[1]===ui,Ri=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!hi(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===Pu)return"eoi";if(o===0||o===ui)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=Dt(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")}},Hu=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!hi(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}},Si=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=Dt(e,r+1),a=Dt(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let s=0;s<i;s+=1){let c=e[r+7+3*s],d=c>>4,u=c&15;if(d<1||d>4||u<1||u>4)return null;l.push({id:e[r+6+3*s],horizontal:d,vertical:u})}return{marker:t,width:a,height:o,components:l}},gi=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>ku||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},bi=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:ci.has(e.marker)||t<e.components.length}),co=e=>{if(!fi(e))return null;let t=yi(e.byteLength),r=null;for(let n=2;;){if(Ri(e,n,t)!=="segment")return null;if(mi(t.marker)){if(r!==null||(r=Si(e,t),r===null))return null}else if(t.marker===di){if(r===null)return null;let o=gi(e,t);return o===null?null:bi(r,o.length)}n=t.end}},Di=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*ii)),i=Math.ceil(e.height*o/(r*ii));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},Ai=e=>e.multiScan?Di(e).reduce((r,n)=>r+n,0)*Lu*vu:0,Fu=896,Ti=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!fi(e))return null;let n=li.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=yi(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let h=Ri(e,u,o);if(h===null)return null;if(h==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,mi(o.marker)){if(a!==null||!Mu.has(o.marker)||(a=Si(e,o),a===null))return null;let p=Di(a);l=new Map;for(let[y,f]of a.components.entries()){let m=l.get(f.id);l.set(f.id,m===void 0?p[y]:Math.max(m,p[y]))}s=a.components.length*(ci.has(a.marker)?Fu:1)}else if(o.marker===di){if(a===null||d===s)return null;let p=gi(e,o);if(p===null)return null;for(let f of p){let m=l.get(f);if(m===void 0)return null;c+=m}if(d+=1,i===null&&(i=bi(a,p.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let y=Hu(n,o.end,o);if(y===null)return null;u=y}}},Ei=e=>{if(e.byteLength<24||Dt(e,8)!==0||Dt(e,10)!==13||!pt(e,12,"IHDR"))return null;let t=Dt(e,16)*65536+Dt(e,18),r=Dt(e,20)*65536+Dt(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},$u=e=>{if(pt(e,Ct,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Qt(e,26,2)&16383,r=Qt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(pt(e,Ct,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Qt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return pt(e,Ct,"VP8X")?e.byteLength<pi?null:{width:Qt(e,24,3)+1,height:Qt(e,27,3)+1}:null},wi=e=>{if(Ei(e)===null||e.byteLength<=si)return null;switch(e[si]){case 0:return!1;case 1:return!0;default:return null}},Ii=(e,t)=>{if(pt(e,Ct,"VP8 "))return"lossy";if(pt(e,Ct,"VP8L"))return"lossless";if(!pt(e,Ct,"VP8X")||e.byteLength<pi)return null;if((e[Nu]&Ou)!==0)return"animated";let r=!1,n=t;for(let o=Ct;o+lo<=e.byteLength;){if(n-=1,n<0)return null;if(pt(e,o,"VP8L"))return"lossless";if(pt(e,o,"VP8 "))return r?"lossy-alpha":"lossy";pt(e,o,"ALPH")&&(r=!0);let a=Qt(e,o+4,4);o+=lo+a+a%2}return null},_i={png:Ei,jpeg:co,webp:$u};var Kr=Object.freeze(["image/webp","image/jpeg","image/png"]),Jr=1024*1024;var Uu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Bu={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Vu=new Set(Kr),qu=e=>typeof e=="string"&&Vu.has(e),ju=256,Qr=(e,t)=>e.fileType===null||!Uu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Wu=[137,80,78,71,13,10,26,10],Yu=[255,216,255],zu=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Gu=[82,73,70,70],Ku=[87,69,66,80],Dr=(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},uo=e=>{if(Dr(e,Wu,0))return"png";if(Dr(e,Yu,0))return"jpeg";for(let t of zu)if(Dr(e,t,0))return"gif";return Dr(e,Gu,0)&&Dr(e,Ku,8)?"webp":null},xi=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:Ya([t])}},Ci=(e,t)=>{if(!qu(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Jr)return"too_large";let r=Bu[e.contentType];if(uo(e.bytes)!==r)return"signature";let n=_i[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Mi=e=>{le("maxBytes",e.maxBytes,0),le("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)+ju;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 s of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(s)}}}};var po=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ce(),l=new AbortController,s=!1,c,d,u=()=>{a(ce()-i)},h=S=>{c=nt(()=>{s=!0,S({timedOut:!0}),d=nt(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},p=new Promise(h),y=AbortSignal.any([r,l.signal]),f=S=>{S(n(y))},m=new Promise(f),R=S=>(clearTimeout(c),clearTimeout(d),s&&o(ce()-i,S.kind==="error"?{error:S.error}:null),S),A=m.then(S=>R({kind:"value",value:S}),S=>R({kind:"error",error:S}));return{outcome:Promise.race([m.then(S=>({timedOut:!1,value:S})),p]),settled:A}};var At={404:"Attachment not found",500:gt,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Pi=(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=Ci(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Ju=e=>{let t=new AbortController,r=()=>{t.abort()},n=nt(r,je.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},ki=()=>{},Qu=(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)}),Li=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(p,y)=>{let f=y.then(ki,ki);l.set(p,f);let m=()=>{l.get(p)===f&&l.delete(p)};f.then(m)},c=async(p,y)=>{let f=l.get(p.key);if(f===void 0)return t.acquire(p.owner,y);let m=Ju(y);try{if(await Qu(f,m.signal),m.signal.aborted)return null;let R=r.get(p.key);return R!==void 0?{...R,identity:"verified"}:await t.acquire(p.owner,m.signal)}finally{m.end()}},d=(p,y)=>{if(p.fileSize===null)return y.kind==="exact"?"verified":"unrecorded";if(y.kind==="exact"?y.bytes===p.fileSize:p.fileSize>y.maxBytes)return"verified";let m=y.kind==="exact"?String(y.bytes):`>${y.maxBytes}`;return i.warn(`size_mismatch expected=${p.fileSize} got=${m} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`),"unverified"},u=(p,y)=>(f,m)=>{let R=m===null?"":` message=${m.error instanceof Error?m.error.message:"unknown"}`;i.warn(`${p}_overrun ms=${f} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail${R}`)},h=(p,y)=>f=>{i.warn(`${p}_stuck ms=${f} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail`)};return async(p,y)=>{let f=await c(p,y);if(f===null)return{kind:"failure",status:503,reason:y.aborted?"aborted":"queue"};if(typeof f!="function")return f;let m=f,R=null;try{if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let A=r.get(p.key);if(A!==void 0)return{...A,identity:"verified"};let w=po({budgetMs:je.readMs,flightSignal:y,call:$=>p.readAttachment(p.filePath,{maxBytes:n,head:!1,principal:o(p.owner),signal:$}),onOverrun:u("read",p),onStuck:h("read",p)}),S=await w.outcome;if(S.timedOut)return R=w.settled,y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=S.value;if(!g.ok&&g.reason!=="too_large")return zr(g.reason)?(g.reason==="not_found"&&a(p.attachmentId,!1),{kind:"failure",status:Gr(g.reason),reason:g.reason,code:g.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(g.ok&&g.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let M=d(p,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),D=$=>{M==="verified"&&r.set(p.key,$)},x=$=>(D($),{...$,identity:M});if(!g.ok)return x({kind:"unrenderable",reason:"too_large"});let F=uo(g.bytes);if(F===null)return x({kind:"unrenderable",reason:"signature"});let I=po({budgetMs:je.renderMs,flightSignal:y,call:$=>p.renderer.render(g.bytes,{format:F,maxWidth:p.box.maxWidth,maxHeight:p.box.maxHeight,signal:$}),onOverrun:u("render",p),onStuck:h("render",p)}),v=$=>{if($.kind==="error")return;let _=Pi($.value,p.box);"entry"in _&&D(_.entry)},C=null,j=()=>(C===null&&(C=I.settled.then(v),s(p.key,C)),C);y.addEventListener("abort",j,{once:!0});let Q=await I.outcome.finally(()=>y.removeEventListener("abort",j));if(Q.timedOut||y.aborted)return R=j(),y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let J=Pi(Q.value,p.box);return"entry"in J?x(J.entry):J.failure}finally{R===null?m():R.then(m,m)}}};var vi=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let s=new AbortController,c=()=>{e.get(t)?.controller===s&&e.delete(t)},u={promise:n(s.signal).finally(c),controller:s,waiters:0};return e.set(t,u),u},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 Hi=10,Xu=1/Hi,Ni=1-Xu,Zu=1024,ed=64,td=8,Oi="private, no-cache",rd="no-store",nd=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),od=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Fi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(S,g)=>bt({reason:S,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:M=>`viewer=${M} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*Hi),h=dt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:ed,maxPerOwner:td,maxWaitMs:je.queueWaitMs}}),p=Mi({maxBytes:l.cacheBytes,maxEntries:Zu}),y=vi(),f=Li({gate:h,cache:p,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),m=(S,g,M,D)=>{let x=`attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail cache=${D}`;if(g.kind==="failure")return o[od(g)](`${g.status} ${x} reason=${g.reason} code=${g.code??"-"}`),S.fail(g.status,At[g.status],_e(g.status));let F=nd[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${x} reason=${g.reason}${F}`),S.fail(404,At[404]);let I=g.identity==="verified"?{"Cache-Control":Oi,ETag:M}:{"Cache-Control":rd},v=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...I,"Content-Security-Policy":"default-src 'none'; sandbox",...Jt});return S.cookie&&v.append("Set-Cookie",S.cookie),o.info(`200 ${x} type=${g.contentType} bytes=${g.bytes.byteLength}${F}`),new Response(g.bytes,{status:200,headers:v})},R=(S,g)=>{let M=S.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return M===null?null:g.fail(M.status,M.message,M.headers)},A=S=>R(d,S),w=(S,g)=>g?R(u,S):A(S);return async(S,g)=>{let{request:M,attachmentId:D,internalUserId:x,readAttachment:F,cookie:I,fail:v}=S,C=Xn[g],j=M.headers.get("If-None-Match"),Q=j!==null,J=w(S,Q);if(J)return J;let $=await n(M,"initial");if(!$.ok)return v(503,At[503],_e(503));let _=await t.getAttachmentForUser($.scope,D,x),Y=_!==null&&Qr(_,i)?xi({rendererId:s.id,box:C,attachmentId:D,filePath:_.filePath,fileType:_.fileType,fileSize:_.fileSize}):null;if(Y&&to(j,Y.etag)){let b=new Headers({"Cache-Control":Oi,ETag:Y.etag,...Jt});return I&&b.append("Set-Cookie",I),o.info(`304 attachment=${D} viewer=${x} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:b})}if(Q){let b=A(S);if(b)return b}if(!_)return o.warn(`404 attachment=${D} viewer=${x} variant=thumbnail reason=not_visible`),v(404,At[404]);if(!Y)return d.refund(x,Ni),o.info(`404 attachment=${D} viewer=${x} variant=thumbnail reason=not_eligible`),v(404,At[404]);let{key:de,etag:ae}=Y,pe=p.get(de);if(pe)return d.refund(x,Ni),m(S,{...pe,identity:"verified"},ae,"hit");let De=b=>f({key:de,attachmentId:D,filePath:_.filePath,fileSize:_.fileSize,box:C,owner:x,readAttachment:F,renderer:s},b),X;try{X=await y.join(de,M.signal,De)}catch(b){return o.error(`500 attachment=${D} viewer=${x} variant=thumbnail cache=miss reason=port_exception message=${b instanceof Error?b.message:"unknown"}`),v(500,At[500])}return m(S,X,ae,"miss")}};var ad='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',id=()=>Yr(403,ao,{cookie:null}),$i=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Zn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Yr(404,br[404],{cookie:null}),crossSiteRejection:id}),Ui=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:Za(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:ai({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Fi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,h=(p,y,f={})=>Yr(p,y,{cookie:u,extraHeaders:f});try{let{user:p,cookie:y}=await t(c,{failureRedirect:null});if(u=y??null,!p)return h(401,"Unauthorized");let f=Zn(new URL(c.url).searchParams);if(f.kind==="invalid")return h(400,"Invalid attachment request");if(f.kind==="thumbnail"&&c.method!=="GET")return h(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return h(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return h(404,"Attachment not found");if(d.token===void 0)throw new Error(ad);let m=s.idCodec.decode(d.token);if(m===null||!lt(m))return h(400,"Invalid attachment token");let R=await r.getUserIdByExternalId(p.id);if(!R)return h(403,"Forbidden");let A={request:c,delivery:f,attachmentId:m,internalUserId:R,readAttachment:s.read,cookie:u,fail:h};return f.kind!=="thumbnail"?await s.serveOriginal(A):s.serveThumbnail===null?h(404,At[404]):await s.serveThumbnail(A,f.variant)}catch(p){if(p instanceof Response)throw p;return a.error(`500 attachment=? viewer=? reason=unexpected message=${p instanceof Error?p.message:"unknown"}`),h(500,gt)}}};var sd=32*1024*1024,ld=60,cd=4,ud=120,dd=2,pd=8*1024*1024,Xr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),md=e=>{if(e===void 0)throw Ke("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Xr(e))throw Z("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Ke("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw Z("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Z("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},yd=e=>{if(e===void 0)return null;if(!Xr(e))throw Z("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:md(e.renderer),rateLimitPerMinute:Ne("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,ud),concurrency:Ne("attachments.thumbnails.concurrency",e.concurrency,1,dd),cacheBytes:Ne("attachments.thumbnails.cacheBytes",e.cacheBytes,0,pd)})},Bi=e=>{let t=e;if(t===void 0)return null;if(!Xr(t))throw Z("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Ke("attachments.idCodec","injected when attachments is given");if(!Xr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw Z("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Ke("attachments.read","injected when attachments is given");if(typeof n!="function")throw Z("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Ne("attachments.maxBytes",t.maxBytes,1,sd),rateLimitPerMinute:Ne("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,ld),concurrency:Ne("attachments.concurrency",t.concurrency,1,cd),thumbnails:yd(t.thumbnails)})},hd=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"]]),Zr=e=>{for(let[t,r]of hd)if(Object.hasOwn(e,t))throw Ke(r,`given in place of the flat key ${t}`)};var qi=8,fd=8*qi,Rd=128,Sd=2,ji=Sd*Rd,gd=4*ji,bd=6e4,Dd=6e4,Ad="Too many reads",Vi=Object.freeze(Object.keys(Ut).filter(e=>Ut[e].admission.includes("miss-gate"))),Wi=e=>{let t=dt({limit:fd,maxHeldPerOwner:qi,queue:{max:gd,maxPerOwner:ji,maxWaitMs:bd}}),r=ke({windowMs:Dd,tallies:Vi,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Vi.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}})}},en=(e,t,r)=>{let n=e(t,r,{error:{message:Ad}},503);for(let[o,a]of Object.entries(_e(503)))n.headers.set(o,a);return n};var Yi=e=>{let t=e.get(Te.cursorReportHubId),r=e.get(Te.cursorBusinessDate),n=e.get(Te.cursorSnapshot),o=ba(n)?n:null,a=null;if(t!==null){let l=rt(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!ga(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=Sr(e.get(Te.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var tn=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Td=2,Ed=16,wd=Td*Ed,Id=6e4,zi=()=>{},_d=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Gi=e=>{let t=dt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:wd,queue:null}),r=ke({windowMs:Id,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 zi;if(a.aborted){if(t.canAcquire(n))return zi}else{let i=await t.acquire(n,a);if(i!==null)return _d(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var rn=30,Zi=4e3,xd="stream interrupted by server error",Cd="Too many streams",Md=15e3,es=Symbol("ids-stream-heartbeat"),Ki=()=>{},Ji=e=>e.return(void 0).then(Ki,Ki),Pd=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(es),Md)}),stop:()=>clearTimeout(e)}};async function*Qi(e,t,r,n){let o=t?Ta(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Zi),e.length),l=Ft(e,o,i),s=i>o?e[i-1]:void 0;o=i;let c=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:c||s===void 0?null:{businessDate:s.businessDate,reportHubId:s.reportHubId},isLast:c,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,c)return}}var ts=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...ut});return e&&t.append("Set-Cookie",e),t},Xi=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await Ji(t);try{d.close()}catch{}},i=new TextEncoder,l=!1,s=null,c=new ReadableStream({async pull(d){if(l||r.aborted){await a(d,!0);return}let u=Pd();try{s===null&&(s=t.next());let h=await Promise.race([s,u.fired]);if(u.stop(),h===es){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
2
- `));return}s=null;let{value:p,done:y}=h;if(y){await a(d,!1);return}if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`${JSON.stringify(p)}
3
- `))}catch(h){if(u.stop(),s=null,o(),l||r.aborted)return;h instanceof tt||n.error(`ids-stream emission failed: ${h instanceof Error?h.message:String(h)}`);try{let p={kind:"error",error:xd};d.enqueue(i.encode(`${JSON.stringify(p)}
4
- `)),d.close()}catch{}}},cancel(){l=!0,o(),Ji(t)}});return new Response(c,{status:200,headers:ts(e)})},rs=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,s,c,d,u,h,p)=>{let y=!1,f=null,m=null,R=new Promise((S,g)=>{f=S,m=g});R.catch(()=>{});let A=t.getDailyReportIdsByExternalId(c,s.id,{forceRefresh:l.forceRefresh,admission:p,onFetchStart:l.cursor?void 0:()=>{y=!0,t.readSseStreamAnchor().then(S=>t.getDailyReportIdsFirstPageByExternalId(c,s.id,rn).then(g=>({items:g,streamAnchor:S}))).then(S=>f?.(S),S=>m?.(S))}});if(A.catch(()=>{}),l.cursor){let{items:S,streamAnchor:g,snapshot:M}=await A,D=l.snapshot!==null&&l.snapshot===M;return Xi(d,Qi(S,D?l.cursor:null,rn,{snapshot:M,restarted:!D,streamAnchor:g}),u,r,h)}let w=(async function*(){let S=await Promise.race([A.then(D=>({kind:"full",source:D}),D=>({kind:"full-error",error:D})),R.then(D=>({kind:"page",page:D}),()=>({kind:"page-error"}))]),g=null,M=!1;if(S.kind==="full")g=S.source;else if(S.kind==="page"){let{items:D,streamAnchor:x}=S.page;if(D.length<rn){yield{kind:"chunk",...Ft(D,0,D.length),nextCursor:null,isLast:!0,total:D.length,streamAnchor:x};return}yield{kind:"chunk",...Ft(D,0,D.length),nextCursor:null,isLast:!1,provisional:!0},M=!0}else if(S.kind==="full-error"&&y){let D=await R.catch(()=>null);D&&D.items.length>0&&(yield{kind:"chunk",...Ft(D.items,0,D.items.length),nextCursor:null,isLast:!1,provisional:!0})}g===null&&(g=await A),yield*Qi(g.items,null,M?Zi:rn,{snapshot:g.snapshot,streamAnchor:g.streamAnchor})})();return Xi(d,w,u,r,h)};return async(l,s,c,d,u,h)=>{let p=Yi(l.searchParams);if("refused"in p)return h(c,s,{error:{message:p.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:y}=p;if(y.forceRefresh){let A=a(d,c,s,h);if(A!==null)return A}let f=tn(c),m=await t.getUserIdByExternalId(d.id),R=await n.admit(m,"ids-stream",f);if(R===null){let A=h(c,s,{error:{message:Cd}},503);for(let[w,S]of Object.entries(_e(503)))A.headers.set(w,S);return A}if(f.aborted)return new Response(null,{status:200,headers:ts(s)});try{return await i(y,d,u,s,f,R,m===null?void 0:o.admissionFor(m,ue.idsStream,f))}catch(A){if(R(),A instanceof tt)return en(h,c,s);throw A}}};var Bt=require("drizzle-orm");var We="Internal",ns=e=>e.trim().toLowerCase();var kd="",Ld=64,vd=e=>e.toLowerCase(),os=e=>{let t=new Set;if(!Array.isArray(e))return t;for(let r of e){if(typeof r!="string")continue;let n=ns(r);n.length>0&&t.add(n)}return t};function Ce(e,t){return e===null?!0:t==null?!1:e.has(vd(t))}function Fe(e){return e!==null&&e.size===0}var Nd=4e3,yo=e=>{let t=e.getSQLType();if(!t.startsWith("nvarchar("))throw Z("tables.hub.sourceType","an nvarchar(n) column with a declared length (source types compare as UTF-16 bytes)",t);return le("tables.hub.sourceType.length",e.length,1,Nd)};function Tr(e,t){if(t===null)return;let r=yo(e),n=[...t].filter(a=>a.length<=r);if(n.length===0)return Bt.sql`1 = 0`;let o=Bt.sql.raw(`VARBINARY(${2*r})`);return(0,Bt.inArray)(Bt.sql`CAST(LOWER(${e}) AS ${o})`,n.map(a=>Bt.sql`CAST(${a} AS ${o})`))}var Xt,Zt,Ar=class Ar{constructor(t,r){In(this,Xt);In(this,Zt);_n(this,Xt,t),_n(this,Zt,r)}get visible(){return sr(this,Xt)===null?null:new Set(sr(this,Xt))}get commentable(){return sr(this,Zt)===null?null:new Set(sr(this,Zt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=os(r?t.read:t);if(!r||t.comment===void 0)return new Ar(n,n);let o=new Set;for(let a of os(t.comment))n.has(a)&&o.add(a);return new Ar(n,o)}static unrestricted(t){return new Ar(null,null)}};Xt=new WeakMap,Zt=new WeakMap;var Qe=Ar,mo=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),Od=new Set(["read","comment"]),is=e=>{if(mo(e))return Qe.restrictTo(e);if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=Object.keys(e);if("unrestricted"in e){let o=e.unrestricted;return t.length===1&&typeof o=="string"&&o.trim().length>0?Qe.unrestricted(o):null}let{read:r,comment:n}=e;return t.every(o=>Od.has(o))&&mo(r)?n===void 0?Qe.restrictTo({read:r}):mo(n)?Qe.restrictTo({read:r,comment:n}):null:null};function nn(e){let t=as(e.visible),r=as(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function as(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(kd);if(t.length<=Ld)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 ss=(e,t,r,n)=>Ce(n.commentable,t)||e.authorUserId===r;var Ts=require("@aiquants/fuzzy-search");var ds=require("crypto"),ho=require("timers/promises"),ge=require("@aiquants/fuzzy-search/normalize");var an=`
5
- `,fo=4e3,Hd=1,ps=new Set([8203,8288,65279,173]),Fd=new RegExp(`[${String.fromCodePoint(...ps)}]`,"gu"),ms=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),ys=/(\s+)/u,$d=/^\s+$/u,Ud=new RegExp(ys.source,"gu"),Bd=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,Vd=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]),sn=e=>e.replace(Fd,"");var Ro=e=>(0,ge.normalizeText)(e,ge.DEFAULT_NORMALIZE_OPTIONS),on=e=>Ro(sn(e)),qd=(0,ge.resolveNormalizeOptions)({...ge.DEFAULT_NORMALIZE_OPTIONS,convertRomaji:!0},"[daily-report] search reading options"),jd=3,Wd=/^[-ー]+/u,Yd=/[^\p{L}\p{M}]/gu,zd=/ー{2,}/gu,Gd=/\p{Script=Latin}/u,ls=/(?=\p{L})\p{Script=Latin}/u,Kd=e=>(0,ge.clusterCountOf)(e.replace(Wd,"").replace(Yd,"").replace(zd,"\u30FC")),Jd=(e,t)=>{for(let r of t)if(!(0,ge.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})`)},hs=e=>{if(!ls.test(e))return[];let t=on(e);if(!ls.test(t))return[];let r=(0,ge.queryNeedles)(t,qd,!1);Jd(t,r);let n=[];for(let o of r){if(o.tier===$t.word)continue;let a=on(o.text);if(!(a.length===0||a.length>Pe.maxWordLength)&&!(a===t||Gd.test(a))&&!(Kd(a)<jd||n.includes(a))&&(n.push(a),n.length===Yn))break}return n},So=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},fs=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&So(e,t-1)?t-2:t-1;return Bd.test(String.fromCodePoint(r))&&!Vd.has(e.codePointAt(n))},Qd=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!fs(e,i);)i--;i===a&&(i=a+r,So(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}},go=(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 s of e.split(ys)){let c=o;if(o+=s.length,i+s.length<=t){i===0&&(a=c),i+=s.length;continue}if(l(),$d.test(s))continue;if(s.length<=t){a=c,i=s.length;continue}let d=Qd(s,c,t);n+=d.forcedCuts,r.push(d.pieces)}return l(),{chunks:r,forcedCuts:n}},bo=(e,t)=>{let r=go(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>Ro(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},Xd=(e,t)=>{let r=0;for(let n of e.matchAll(ms))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},Zd=(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},Rs=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],s=[];for(let c of a){let d=e.slice(c.start,c.end),u=Zd((0,ge.toMappedFormsInto)(d,ge.DEFAULT_NORMALIZE_OPTIONS,new ge.InteriorPairs(0)),d),[h,p]=(0,ge.trimmedRange)(u.text);i+=u.text.slice(h,p);for(let y=h;y<p;y++)l.push(c.start+u.start[y]),s.push(c.start+u.end[y])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let c=0;c<l.length;c++)n.push(l[c]),o.push(s[c])}}return{text:r,start:n,end:o}},ln=(e,t=fo)=>{let r=[],n=0;return Xd(sn(e),o=>{let a=bo(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(an),forcedCuts:n}},Ss=e=>e.filter(t=>t.length>0).join(an),Do=(e,t)=>{let r=null;return{advance:n=>{if(r!==null)return 0;e.units=le("search text steps: units",n,1);let o=t.next();return o.done===!0&&(r={result:o.value}),n-e.units},done:()=>r!==null,result:()=>{if(r===null)throw new Error("[daily-report] search text: the steps are not done (advance until done() is true)");return r.result}}},cs=4096;function*ep(e,t){let r=[],n=new Uint32Array(e.length),o=0,a=!1;for(let i=0;i<e.length;){for(;t.units===0;)yield;let l=Math.min(e.length,i+t.units);t.units-=l-i;let s=o,c=new Uint16Array(l-i);for(let d=i;d<l;d++){let u=e.charCodeAt(d);ps.has(u)||(c[o-s]=u,n[o++]=d)}if(o-s===l-i)a&&r.push(e.slice(i,l));else{a||r.push(e.slice(0,i)),a=!0;for(let d=s;d<o;d+=cs)r.push(Reflect.apply(String.fromCharCode,null,c.subarray(d-s,Math.min(o,d+cs)-s)))}i=l}return a?{text:r.join(""),rawIndex:n.subarray(0,o)}:{text:e,rawIndex:null}}var gs=e=>{let t={units:0};return Do(t,ep(e,t))};function*tp(e,t,r){let n=0;for(let o=0;o<e.length;){for(;r.units===0;)yield;let a=Math.min(e.length,o+r.units);r.units-=a-o;let i=a;for(let l of e.slice(o,Math.min(e.length,a+1)).matchAll(ms)){let s=o+l.index;if(s>=a)break;t(e.slice(n,s),n),n=s+l[0].length,i=Math.max(i,n)}o=i}t(e.slice(n),n)}var bs=(e,t)=>{let r={units:0};return Do(r,tp(e,t,r))};function*us(e,t,r,n,o){let a=[],i=0,l=t;for(;r-l>n;){let s=l+n;for(;s>l;s--){for(;o.units===0;)yield;if(o.units-=1,fs(e,s))break}s===l&&(s=l+n,So(e,s)&&s--,i++),a.push({start:l,end:s}),l=s}return a.push({start:l,end:r}),{pieces:a,forcedCuts:i}}function*rp(e,t,r){if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let n=[],o=0,a=0,i=0,l=0,s=0,c=!1,d=(p,y,f)=>{let m=y-p;return i+m<=t?(i===0&&(a=p),i+=m,!1):(i>0&&n.push([{start:a,end:a+i}]),i=0,f?!1:m<=t?(a=p,i=m,!1):!0)},u=p=>{c&&(d(l,s,!0),l=s),c=!1,s=p},h=p=>{let y=-1;return!c&&s>l&&(d(l,s,!1)&&(y=l),l=s),c=!0,s=p,y};for(let p=0;p<e.length;){for(;r.units===0;)yield;let y=Math.min(e.length,p+r.units);r.units-=y-p;let f=p;for(let m of e.slice(p,y).matchAll(Ud)){let R=p+m.index;R>f&&u(R),f=R+m[0].length;let A=h(f);if(A>=0){let w=yield*us(e,A,R,t,r);o+=w.forcedCuts,n.push(w.pieces)}}y>f&&u(y),p=y}if(d(l,s,c)){let p=yield*us(e,l,s,t,r);o+=p.forcedCuts,n.push(p.pieces)}return i>0&&n.push([{start:a,end:a+i}]),{chunks:n,forcedCuts:o}}var Ds=(e,t)=>{let r={units:0};return Do(r,rp(e,t,r))},np=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
6
- `)},op=[`\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`],ap=["","\u30A2","\u4F50"," "],ip=()=>JSON.stringify(op.map(e=>ln(e,8))),sp=e=>`dr-search-v${Hd};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var lp=async()=>{let e=(0,ds.createHash)("sha256");e.update(JSON.stringify(ge.DEFAULT_NORMALIZE_OPTIONS));for(let t of ap)await(0,ho.setImmediate)(),e.update("\0"),e.update(Ro(np(t)));return await(0,ho.setImmediate)(),e.update("\0"),e.update(ip()),sp(e.digest("hex"))},cp=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},Ao=cp(lp);var up=/^-+/u,dp=/\s+/u,As=e=>{let t=up.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},pp=(e,t)=>{let r=[...As(e).map(n=>({text:n,tier:$t.word})),...t.flatMap(n=>As(n).map(o=>({text:o,tier:$t.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},mp=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),cn=(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,Ts.parseQuerySets)(sn(e),t).sets){let i=[],l=new Set;for(let c of a.split(dp)){let d=on(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>Pe.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=pp(d,hs(c)),h=mp(u);l.has(h)||(l.add(h),i.push({alternatives:u}))}if(i.length>Pe.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let s=JSON.stringify([...l].sort());n.has(s)||(n.add(s),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}}},Er=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var Bf=Object.freeze({sourceTypes:null,authors:null,customers:null}),yp=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,Es=(e,t,r)=>{if(Pa(e)&&yp(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=cn(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var ws=6e4,hp=1,fp=3200,Is=2e3,Rp=Object.freeze({search:fp,reports:Is,"search-marks":Is,"search-facets":null}),Sp=(e,t)=>{let r=Rp[e];return r===null?null:{max:t,maxPerOwner:Vr,maxWaitMs:r}},wr=e=>{let{concurrency:t,route:r,logger:n}=e,o=bt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:ws,logger:n,windowFields:()=>`route=${r}`}),a=dt({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:Sp(r,t)}),i=Object.freeze({status:429,message:so,headers:Object.freeze({"Retry-After":String(hp)})}),l=ke({windowMs:ws,tallies:["busy"],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`busy_suppressed count=${c} since=${d} route=${r} concurrency=${t}`)}});return{admit:async(s,c)=>{let d=o.spend(s,r);if(d!==null)return{refusal:d};let u=await a.acquire(s,c);return u!==null?{release:u}:(o.refund(s,1),c.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};var Us=require("@aiquants/sse"),Pt=require("@aiquants/sse/server");var er=(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=$r.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});return{entry:Object.freeze({id:e.id,message:a}),json:n}},_s=new WeakMap,xs=(e,t,r)=>{let n=_s.get(e);n===void 0&&(n=new Map,_s.set(e,n));let o=n.get(t);if(o!==void 0)return o;let a=r();return n.set(t,a),a},To=e=>e,gp=e=>{switch(e.type){case"connected":case"report-delete":return To(e);case"status-update":case"comment-add":case"comment-delete":{let{recipientRawUserId:t,...r}=e;return To(r)}}},bp=(e,t,r)=>{let{recipientRawUserId:n,actorRawUserId:o,...a}=e,i=r?{...a.report,externalComments:[],postedComments:[]}:a.report;return To({...a,report:i,viewerIsActor:t})},Cs=(e,t,r)=>{let{parsed:n}=e;if(n.type!=="report-create"&&n.type!=="report-update"&&n.type!=="report-publish")return xs(e,"every-viewer",()=>JSON.stringify(gp(n)));let o=n.actorRawUserId===t;return xs(e,`${o?"actor":"observer"}${r?"-comments-redacted":""}`,()=>JSON.stringify(bp(n,o,r)))};var Ls=require("@aiquants/sse"),vs=require("@aiquants/sse/shared-source");var Mt="daily-report:ids:",Eo=(e,t)=>`${e}st:${t}`,wo=e=>`${Mt}user:${e}:`,Ms=(e,t)=>Eo(wo(e),t),tr=e=>`daily-report:date:${e}:user:`,rr=(e,t)=>`${tr(e)}${t}:`,Ps=(e,t,r)=>Eo(rr(e,t),r),Xe=e=>`daily-report:detail:${e}:user:`,Io=(e,t)=>`${Xe(e)}${t}:`,ks=(e,t,r)=>Eo(Io(e,t),r);var mt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},Dp=5e3,Ap=qr,nr=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=Ee(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:_t}_createSource(){return(0,vs.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Ls.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:Dp,COUNT:Ap});if(i)for(let l of i)for(let s of l.messages){a=s.id;let{entry:c,json:d}=er(s,this._logger);this._invalidateCaches(d),r.next(c)}}}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(Mt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Xe(n))}};var Tp=6e4,Ir="Report visibility is unavailable",Ns=["initial","refresh"],Os=Object.freeze({ok:!1}),Ep=e=>e===null?"null":Array.isArray(e)?"array":typeof e,Hs=(e,t)=>{let r=ke({windowMs:Tp,tallies:Ns,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{t.error(`visibility_unavailable_suppressed count=${o} since=${a} cause=${n} reasons=${Ns.map(l=>`${l}:${i[l]}`).join(",")}`)}});return async(n,o)=>{let a;try{a=await e(n,{reason:o})}catch(l){return r.record("port_failure",o,()=>t.error(`visibility unavailable cause=port_failure reason=${o}`,l)),Os}let i=is(a);return i===null?(r.record("port_contract",o,()=>t.error(`visibility unavailable cause=port_contract reason=${o} answer=${Ep(a)}`)),Os):{ok:!0,scope:i}}},Fs=(e,t,r)=>{let n=e(t,r,{error:{message:Ir}},503);for(let[o,a]of Object.entries(_e(503)))n.headers.set(o,a);return n};var Bs=Object.freeze({...gr,route:"sse",frameworkDataRefusal:Wr}),$s=864e5,wp={baseMs:2e3,jitterMs:8e3},_o=6e4,dn=qr,Vs=JSON.stringify({type:"connected"}),Ip=e=>{let t=e.length,r=e["entries-added"];if(typeof t!="number"||!Number.isSafeInteger(t)||t<0||typeof r!="number"||!Number.isSafeInteger(r)||r<t)throw new Error(`XINFO STREAM must report length and entries-added as safe integers with entries-added >= length >= 0 (Redis 7.0 or later); got length=${String(t)} entries-added=${String(r)}`);return r-t},_p=(e,t,r)=>{if(t===null&&r===null)return!0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Ce(t,e.report.sourceType);case"comment-add":case"comment-delete":return Ce(r,e.sourceType);case"report-delete":return Ce(t,e.sourceType)}},xp=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Ce(t,e.report.sourceType),Cp=(e,t)=>{e.writeEvent({event:null,id:t,data:Vs})},Mp=(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||!_p(o,r.visibleSet,r.commentableSet)){Cp(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Cs(n,r.internalUserId,xp(o,r.commentableSet))})},qs=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:s}=e,c=async(d,u)=>{let{request:h,internalUserId:p,cursor:y}=u,f=u.initialScope.visible,m=u.initialScope.commentable,R=0,A=setInterval(()=>{let C=++R;n(h,"refresh").then(j=>{if(C===R){if(!j.ok){d.close();return}f=j.scope.visible,m=j.scope.commentable}})},_o);d.onClose(()=>clearInterval(A));let w=y===null?_t:y,S=y!==null&&o!==void 0,g=[],M=null,D=C=>{mt(C.id,w)||(w=C.id,Mp(d,C,{internalUserId:p,visibleSet:f,commentableSet:m}))},x=async(C,j)=>{let[Q]=await C.xRange(i,"-","+",{COUNT:1});return Q!==void 0&&!mt(Q.id,j)},F=async(C,j)=>{let[Q]=await C.xRange(i,"-","+",{COUNT:1});if(Q===void 0)return!0;let J;if(j===_t){if(Ip(await C.xInfoStream(i))>0)return!1;J=Q.id}else{if(!mt(Q.id,j))return!1;J=j}for(;;){let $=await C.xRange(i,J,"+",{COUNT:dn}),_=$[0];if(_!==void 0&&_.id!==J&&await x(C,J))return!1;for(let Y of $){if(M!==null&&mt(M,Y.id))return!0;mt(Y.id,w)||D(er(Y,s).entry)}let B=$.at(-1);if($.length<dn||B===void 0||d.isClosed())return!0;J=B.id}},I=a.subscribe(C=>{if(!S){D(C);return}mt(C.id,w)||(M===null&&(M=C.id),g.push(C))},C=>{s.error(`[SSE:${p}] Fan-Out reader error:`,C),d.close()});if(d.onClose(I),y===null){await a.ready();try{let C=await o?.getClient();if(C){let j=await C.xRevRange(i,"+","-",{COUNT:1});j.length>0&&!mt(j[0].id,w)&&(w=j[0].id)}}catch{}}if(d.writeEvent({event:null,id:w===_t?null:w,data:Vs}),(0,Pt.startSseHeartbeat)(d,{intervalMs:da,retry:wp,runtime:Us.systemSseRuntime}),y===null||o===void 0)return;await a.ready();let v=await o.getClient();if(v===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await F(v,y)){d.writeRetry($s),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}S=!1;for(let C of g.splice(0))D(C)};return async({request:d,params:u})=>{let h,p=()=>{let f=new Headers;h!==void 0&&f.append("Set-Cookie",h);for(let[m,R]of Object.entries(ut))f.set(m,R);return f},y=f=>(0,Pt.terminalStreamResponse)(f,{data:"",retryMs:$s,headers:p()});try{let f=await t(d,{failureRedirect:null});h=f.cookie;let{user:m}=f;if(!m)return y("auth-required");let R=await r.getUserIdByExternalId(m.id);if(!R)return y("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:p()});let A=(0,Pt.readLastEventId)(d,pa);if(A!==null&&!ma(A))return s.warn(`[SSE:${R}] malformed resume cursor; asking the client to resync`),y("resync-required");let w=tn(d),S=await l.admit(R,"sse",w);if(S===null){let M=p();for(let[D,x]of Object.entries(_e(503)))M.set(D,x);return new Response("Too many streams",{status:503,headers:M})}let g=!1;try{let M=await n(d,"initial");if(!M.ok){let x=p();for(let[F,I]of Object.entries(_e(503)))x.set(F,I);return new Response(Ir,{status:503,headers:x})}let D=M.scope;return(0,Pt.createSseResponse)({requestSignal:w,headers:p(),onError:(x,F)=>s.error(`[SSE:${R}] ${F} failed:`,x),produce:x=>(g=!0,x.onClose(S),c(x,{request:d,internalUserId:R,cursor:A,initialScope:D}))})}finally{g||S()}}catch(f){if(f instanceof Response)throw f;let m=f instanceof Error?f:new Error(String(f));return s.error(`500 sse name=${m.name} message=${m.message}`),new Response("Internal Server Error",{status:500,headers:p()})}}};var js=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...ut});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Pp=Object.freeze({...gr,route:"api",frameworkDataRefusal:({params:e})=>Qn(e.endpoint)&&Ut[e.endpoint].body==="stream"?Wr():null}),kp=Object.freeze({...gr,route:"action"}),Lp=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),Js=6e4,Qs=5,vp=Qs*Math.ceil(Js/500),Np=2,Op=6,Hp=6e4,Fp=Qs*Np*Op,$p=2,Up=10,Bp=2,Vp=10,Ws=(e,t)=>Math.max(e,Vr)*t,Xs=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},qp=Object.freeze({etag:(e,t,r)=>za(e,t,r,200),"no-store":(e,t,r)=>ro(t,r,200)}),jp=e=>no(e.body==="json"?qp[e.cache]:null),Ys=no(null),zs=(e,t,r,n)=>Xs(e(t,r,{error:{message:n.message}},n.status),n.headers),Gs=(e,t,r)=>Xs(e(t,r,null,503),_e(503));function pn(e){Zr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:le("service.titleMaxLength",r.titleMaxLength,1)},{loginRedirectPath:s}=e;if(typeof s!="string"||s.trim()==="")throw Z("loginRedirectPath","the non-blank path of the host's sign-in route",s);let c=Ee(e.logger,3,"API"),d=Ee(e.logger,3,"Visibility"),u=Hs(lr("resolveVisibleSourceTypes",e.resolveVisibleSourceTypes),d),h=Ee(e.logger,1,"SSE"),p=Ee(e.logger,1,"Attachment"),y=Ee(e.logger,2,"Isolation"),f=Ee(e.logger,2,"Action"),m=Ee(e.logger,2,"Search"),R=Ee(e.logger,2,"Refresh"),A=Ee(e.logger,2,"Streams"),w=Ee(e.logger,2,"Reads"),S=bt({reason:"refresh_rate_limit",limitPerWindow:Fp,windowMs:Hp,logger:R,windowFields:()=>"route=api"}),g=Gi(A),M=Wi(w),D=async(b,O,N,L,H,z)=>{let ee=await r.getUserIdByExternalId(O.id);try{return await z(ee===null?void 0:M.admissionFor(ee,b,N.signal))}catch(G){if(G instanceof tt)return en(H,N,L);throw G}},x=(b,O,N,L,H)=>{let z=S.spend(O.id,`endpoint=${b}`);return z===null?null:zs(H,N,L,z)},F=async({request:b})=>{let{user:O,cookie:N}=await t(b,{failureRedirect:s}),L=new Headers;N&&L.append("Set-Cookie",N);let H=await r.getUserIdByExternalId(O.id),z=H?n(H):null;return{data:{user:O,userId:z},headers:L}},I=b=>{let{limiter:O}=b;return async(N,L,H,z,ee,G)=>{if(O===null)return G(H,L,{error:{message:"Unknown endpoint"}},404);let P=b.parse(N);if(!P.ok)return G(H,L,P.invalid,400);let k=await r.getUserIdByExternalId(z.id);if(!k)return G(H,L,b.emptyAnswer(P.parsed),200);let{signal:T}=H,U=await O.admit(k,T);if("refusal"in U)return T.aborted?Gs(G,H,L):zs(G,H,L,U.refusal);try{T.throwIfAborted();let W=await b.read(P.parsed,{userId:k,user:z,scope:ee},T);return T.throwIfAborted(),G(H,L,W,200)}catch(W){if(T.aborted&&W===T.reason)return Gs(G,H,L);throw W}finally{U.release()}}},v=r.searchLimits===null?null:wr({...r.searchLimits,route:ue.search,logger:m}),C=r.searchLimits===null?null:wr({concurrency:Ws(r.searchLimits.concurrency,$p),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Up,route:ue.reports,logger:m}),j=r.searchLimits===null?null:wr({concurrency:Ws(r.searchLimits.concurrency,Bp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Vp,route:ue.searchMarks,logger:m}),Q=r.searchLimits===null?null:wr({...r.searchLimits,route:ue.searchFacets,logger:m}),J={[ue.businessDate]:async(b,O,N,L,H,z)=>{let ee=b.searchParams.get(Te.businessDate),G=ee===null?null:zt(ee);if(G===null)return z(N,O,{error:{message:"Invalid business date"}},400);let P=Sr(b.searchParams.get(Te.forceRefresh));if(P===null)return z(N,O,{error:{message:"Invalid forceRefresh"}},400);let k=P?x(ue.businessDate,L,N,O,z):null;return k!==null?k:D(ue.businessDate,L,N,O,z,async T=>{let U=await r.getDailyReportsByBusinessDateByExternalId(H,G,L.id,{forceRefresh:P,admission:T});return z(N,O,{businessDate:G,reports:U},200)})},[ue.idsStream]:rs({service:r,logger:c,streamSlots:g,missGate:M,refuseForcedRead:(b,O,N,L)=>x(ue.idsStream,b,O,N,L)}),[ue.report]:async(b,O,N,L,H,z)=>{let ee=rt(b.searchParams.get(Te.reportHubId));if(ee===null)return z(N,O,{error:{message:"Invalid reportHubId"}},400);let G=Sr(b.searchParams.get(Te.forceRefresh));if(G===null)return z(N,O,{error:{message:"Invalid forceRefresh"}},400);let P=G?x(ue.report,L,N,O,z):null;return P!==null?P:D(ue.report,L,N,O,z,async k=>{let T=await r.getDailyReportDetailByIdByExternalId(H,ee,L.id,{snapshot:!0,forceRefresh:G,admission:k});return T?z(N,O,{report:T},200):z(N,O,{error:{message:"Report not found"}},404)})},[ue.search]:I({limiter:v,parse:b=>{let O=b.searchParams.get(Te.searchQuery),N=Kn(b.searchParams.get(Te.searchCombine));if(O===null||N===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let L=La(b.searchParams,r.searchFilterSourceTypes);if(!L.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:L.reason}}};let H=Es(O,N,L.filters);if(!H.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:H.reason}}};let{criteria:z}=H;return{ok:!0,parsed:{criteria:z,words:z.plan===null?[]:Er(z.plan)}}},emptyAnswer:({words:b})=>zn([],b),read:async({criteria:b,words:O},{userId:N,scope:L})=>zn(await r.searchDailyReports(L,N,b),O)}),[ue.reports]:I({limiter:C,parse:b=>{let O=Jn(b.searchParams.get(Te.reportIds));return O===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:O}},emptyAnswer:b=>({outcomes:b.map(Rr)}),read:async(b,{user:O,scope:N},L)=>({outcomes:await r.getDailyReportDetailsByIdsByExternalId(N,b,O.id,{signal:L})})}),[ue.searchMarks]:I({limiter:j,parse:b=>{let O=b.searchParams.get(Te.searchQuery),N=Kn(b.searchParams.get(Te.searchCombine));if(O===null||N===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let L=cn(O,N);if(!L.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:L.reason}}};let H=Jn(b.searchParams.get(Te.reportIds));return H===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:L.plan,ids:H}}},emptyAnswer:({plan:b})=>({wordsDigest:Br(Er(b)),reports:[],deferred:[]}),read:({plan:b,ids:O},{userId:N,scope:L},H)=>r.markDailyReportSearchHits(L,N,b,O,{signal:H})}),[ue.searchFacets]:I({limiter:Q,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(b,{userId:O,scope:N})=>r.listDailyReportSearchFacets(N,O)})},$=async({request:b,params:O})=>{let{user:N,cookie:L}=await t(b,{failureRedirect:null}),H=L??null;if(!N)return Ys(b,H,{error:{message:"Unauthorized"}},401);let z=O.endpoint;if(!Qn(z))return Ys(b,H,{error:{message:"Unknown endpoint"}},404);let ee=Ut[z],G=jp(ee),P=qa[ee.body];if(!P.includes(b.method)){let T=G(b,H,{error:{message:"Method not allowed"}},405);return T.headers.set("Allow",P.join(", ")),T}let k=ce();try{let T=new URL(b.url),U=await u(b,"initial"),W=U.ok?await J[z](T,H,b,N,U.scope,G):Fs(G,b,H);return ee.body==="json"&&c.debug(W.headers.has("ETag")?`${W.status} endpoint=${z} etag_match=${W.status===304}`:`${W.status} endpoint=${z}`),W}catch(T){let U=ce()-k,W=T instanceof Error?T:new Error(String(T));return c.error(`500 endpoint=${z} elapsed=${U}ms name=${W.name} code=${"code"in W?W.code:"N/A"} message=${W.message}`,W),G(b,H,{error:{message:"Internal Server Error"}},500)}},_=Va(f),B=bt({reason:"rate_limit",limitPerWindow:vp,windowMs:Js,logger:f,windowFields:()=>"route=action"}),Y=async(b,O,N,L,H)=>{let{clientTempId:z}=b;if(b.intent==="create")try{let T=await r.createDailyReport(N,O,b.businessDate,z);return H(b,T.reportHubId,{report:T})}catch(T){if(T instanceof Error&&T.message==="Forbidden")return L({error:"Creating reports is restricted"},{status:403});throw T}let{reportHubId:ee,businessDate:G}=b,P=async(T,U)=>{try{let W=await U(T.value);return H(T,ee,{updatedStatus:{isStarred:W.isStarred,isRead:W.isRead},operationTimestamp:T.operationTimestamp})}catch(W){if(W instanceof Error&&W.message==="Not Found")return L({error:"Report not found"},{status:404});throw W}},k=T=>T instanceof Error?T.message==="Forbidden"?L({error:"Reports from this source are read-only"},{status:403}):T.message==="Unauthorized"?L({error:"Unauthorized"},{status:403}):T.message==="Not Found"?L({error:"Report not found"},{status:404}):null:null;switch(b.intent){case"update":try{return await r.updateDailyReport(N,ee,O,b.changes,z),H(b,ee,{})}catch(T){let U=k(T);if(U===null)throw T;return U}case"publish":try{let T=await r.publishDailyReport(N,ee,O,z);return H(b,ee,{report:T})}catch(T){let U=k(T);if(U===null)throw T;return U}case"delete":try{return await r.deleteDailyReport(N,ee,O,z),H(b,ee,{})}catch(T){let U=k(T);if(U===null)throw T;return U}case"toggleStar":return await P(b,T=>r.setStarStatus(N,O,ee,G,T,z));case"toggleRead":return await P(b,T=>r.setReadStatus(N,O,ee,G,T,z));case"addComment":try{let T=await r.addComment(N,O,ee,b.content,G,z);return H(b,ee,{newComment:T})}catch(T){if(T instanceof Error){if(T.message==="Not Found")return L({error:"Report not found"},{status:404});if(T.message.startsWith("Comments are restricted"))return L({error:"Comments are restricted for this report"},{status:403})}throw T}case"deleteComment":try{return await r.deleteComment(N,O,ee,b.commentId,G,z),H(b,ee,{deletedCommentId:b.commentId})}catch(T){if(T instanceof Error){if(T.message==="Unauthorized")return L({error:"Unauthorized"},{status:403});if(T.message==="Not Found")return L({error:"Comment not found"},{status:404})}throw T}}},de=async({request:b,params:O})=>{let{user:N,cookie:L}=await t(b,{failureRedirect:null}),H=(G,P)=>js(G,{...P,setCookie:L}),z=(G,P,k)=>js(Lp(G,P,k),{setCookie:L});if(!N)return H({error:"Unauthorized"},{status:401});let ee=ce();try{if(O.endpoint!==ue.action)return H({error:"Unknown endpoint"},{status:404});let G=B.spend(N.id,"action");if(G!==null)return H({error:G.message},{status:G.status,headers:G.headers});let P=await Ba(b,l);if("refusal"in P){let{refusal:W}=P;return W.status===413&&_(W.measuredBy),H({error:W.error},{status:W.status})}let{command:k}=P;if(k.intent==="clearCache"&&!e.enableDevCacheClear)return H({error:"Invalid intent"},{status:400});let T=await u(b,"initial");if(!T.ok)return H({error:Ir},{status:503,headers:{..._e(503),"Cache-Control":"no-store"}});let U=await r.getUserIdByExternalId(N.id);return U?k.intent==="clearCache"?(await r.clearCache(),H({status:"OK",intent:"clearCache"})):await Y(k,U,T.scope,H,z):H({error:"User not found"},{status:404})}catch(G){if(G instanceof Response)throw G;let P=ce()-ee,k=G instanceof Error?G:new Error(String(G));return c.error(`500 action elapsed=${P}ms name=${k.name} message=${k.message}`,k),H({error:"Internal Server Error"},{status:500})}},ae=qs({authenticate:t,service:r,resolveViewerScope:u,redis:o,sseReader:a,streamKey:i,streamSlots:g,logger:h}),pe=Ui({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:u,logger:p}),De=Xa(y),X=(b,O)=>async N=>{let L=Qa(N.request)?b.frameworkDataRefusal(N):null;if(L!==null)throw L;let H=(0,Ks.crossOriginRefusal)(N.request,b);return H===void 0?O(N):(De(b.route,H,N.request),b.crossSiteRejection())};return{index:{loader:F},api:{loader:X(Pp,$),action:X(kp,de)},sse:{loader:X(Bs,ae)},attachment:{loader:X($i,pe)}}}var ar=require("@aiquants/mssql"),we=require("drizzle-orm");var Wp=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],Yp=["document","comment"],zp=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],Gp=["hubId","ordinal","authorUserId","commentText"],xo=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Zs=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw xn(e,n,r)},el=(e,t,r)=>{if(typeof t!="object"||t===null)throw Z(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw Z(`${e}.${o}`,"a column",n[o])},tl=(e,t)=>{if(!xo(e))throw Z("search","a plain object",e);Zs("search key",e,Wp);let{tables:r}=e;if(!xo(r))throw Z("search.tables","a plain object with document and comment",r);Zs("search.tables key",r,Yp),el("search.tables.document",r.document,zp),el("search.tables.comment",r.comment,Gp);let n=new Map;if(e.externalSourceTexts!==void 0){if(!xo(e.externalSourceTexts))throw Z("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw xn("search.externalSourceTexts key",o,t);if(typeof a!="function")throw Z(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:le("search.concurrency",e.concurrency,1),rateLimitPerMinute:le("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var kt=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},Vt=(e,t)=>{let r=typeof e=="string"?rt(e):typeof e=="number"&&lt(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},qt=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};var V=require("drizzle-orm");var Tt=require("drizzle-orm"),rl=e=>{if(e.length===0)throw new Error("[daily-report] draft rule: draftLabelNames must hold at least one name (a rule without names would show every draft to every viewer)");return Tt.sql.join(e.map(t=>Tt.sql`${t}`),Tt.sql`, `)},mn=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return Tt.sql`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${rl(t)}))`},nl=(e,t)=>{let{hubLabel:r,label:n}=e;return Tt.sql`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${rl(t)}))`},yn=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?Tt.sql`${o.userId} = ${t} OR ${o.userId} IS NULL`:Tt.sql`${o.userId} = ${t}`;return Tt.sql`(${a} OR NOT ${mn(e,r)})`};var Kp=/[[%_]/gu,Jp=e=>e.replace(Kp,t=>`[${t}]`),ol=e=>`%${Jp(e)}%`;var ot=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),jt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),xr=Object.freeze({value:"value"}),Le=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),q=e=>V.sql`${V.sql.identifier(e.name)}`,_r=e=>V.sql.join(e.map(t=>V.sql`${t}`),V.sql`, `),al=(e,t)=>V.sql`SELECT ${q(e.id)} AS ${V.sql.identifier(Le.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${_r(t)}) ORDER BY ${e.id}`,Qp=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>ol(u.text)),l=V.sql.join(i.map(u=>V.sql`${o.searchText} LIKE ${u}`),V.sql` OR `),s=V.sql.join(i.map(u=>V.sql`${a.commentText} LIKE ${u}`),V.sql` OR `),c=Tr(n.sourceType,r.scope.commentable),d=c===void 0?V.sql``:V.sql` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return V.sql`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},il=(e,t,r)=>V.sql`(${V.sql.join(t.words.map(n=>Qp(e,n,r)),V.sql` AND `)})`,Co=(e,t,r,n)=>{let{hub:o}=e,a=[V.sql`${o.deletedAt} IS NULL`,yn(e,t.userId,r,"author")],i=Tr(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(V.sql`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},Xp=(e,t)=>{let{hub:r}=e,{document:n}=e.search,o=[];if(t.sourceTypes!==null){if(t.sourceTypes.size===0)throw new Error("[daily-report] search: a source-type filter must hold at least one source type");o.push(V.sql`LOWER(${r.sourceType}) IN (${_r([...t.sourceTypes])})`)}return t.authors!==null&&o.push(V.sql`${n.authorName} IN (${_r(t.authors)})`),t.customers!==null&&o.push(V.sql`${n.customerName} IN (${_r(t.customers)})`),o},sl=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...Co(e,r,n,o),...Xp(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?V.sql` AND `:V.sql` OR `;s.push(V.sql`(${V.sql.join(l.sets.map(d=>il(e,d,r)),c)})`)}return V.sql`SELECT ${q(a.id)} AS ${V.sql.identifier(ot.reportHubId)}, CONVERT(char(10), ${q(a.businessDate)}, 23) AS ${V.sql.identifier(ot.businessDate)}, ${q(a.sourceType)} AS ${V.sql.identifier(ot.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${V.sql.join(s,V.sql` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},ll=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=V.sql.join(t.sets.map((s,c)=>V.sql`(CASE WHEN ${il(e,s,r)} THEN ${2**c} ELSE 0 END)`),V.sql` + `);return V.sql`SELECT ${q(a.id)} AS ${V.sql.identifier(jt.reportHubId)}, ${l} AS ${V.sql.identifier(jt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${V.sql.join(Co(e,r,n,o),V.sql` AND `)}`},cl=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...Co(e,r,n),V.sql`${i} IS NOT NULL`];return V.sql`SELECT ${i} AS ${V.sql.identifier(xr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${V.sql.join(l,V.sql` AND `)} GROUP BY ${i} ORDER BY ${i}`},ul=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(s=>({[n.hubId.name]:s.hubId,[n.searchText.name]:s.searchText,[n.sourceDigest.name]:s.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:s.authorName,[n.customerName.name]:s.customerName}))),i=JSON.stringify(t.flatMap(s=>s.comments.map(c=>({[o.hubId.name]:s.hubId,[o.ordinal.name]:c.ordinal,[o.authorUserId.name]:c.authorUserId,[o.commentText.name]:c.commentText})))),l=JSON.stringify(t.map(s=>s.hubId));return V.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), ${q(n.authorName)} nvarchar(max), ${q(n.customerName)} nvarchar(max))) AS s ON t.${q(n.hubId)} = s.${q(n.hubId)}
1
+ "use strict";var xn=Object.defineProperty;var Tc=Object.getOwnPropertyDescriptor;var Ac=Object.getOwnPropertyNames;var Ec=Object.prototype.hasOwnProperty;var Xo=e=>{throw TypeError(e)};var wc=(e,t)=>{for(var r in t)xn(e,r,{get:t[r],enumerable:!0})},Ic=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ac(t))!Ec.call(e,o)&&o!==r&&xn(e,o,{get:()=>t[o],enumerable:!(n=Tc(t,o))||n.enumerable});return e};var _c=e=>Ic(xn({},"__esModule",{value:!0}),e);var Zo=(e,t,r)=>t.has(e)||Xo("Cannot "+r);var cr=(e,t,r)=>(Zo(e,t,"read from private field"),r?r.call(e):t.get(e)),Cn=(e,t,r)=>t.has(e)?Xo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Mn=(e,t,r,n)=>(Zo(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var ny={};wc(ny,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>Xr,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>Qr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>Yo,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Nr,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>zo,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>mn,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>ko,DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS:()=>Go,DailyReportSseReader:()=>ar,DailyReportViewerScope:()=>Xe,SqlResultCache:()=>Gt,buildDailyReportRedisKeys:()=>Tn,createDailyReportHandlers:()=>yn,createDailyReportServer:()=>ry,createDailyReportService:()=>In,createDailyReportVisibilityCache:()=>hc,createEpochStore:()=>Or,createSharpThumbnailRenderer:()=>yc,dailyReportSseStreamMessageSchema:()=>Br,defineDailyReportSchema:()=>Xl,defineDailyReportSearchSchema:()=>Zl,encodeIdsStreamRows:()=>Ut,isStreamIdLte:()=>mt,parseClientTempId:()=>Yr,predictSharpThumbnailWorkingSetBytes:()=>mc,readDailyReportSseStreamEntry:()=>rr,transformJsonArray:()=>Ql});module.exports=_c(ny);var Ht=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,Q=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Ht(r)}`),Je=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),kn=(e,t,r)=>Q(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ce=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw Q(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},Oe=(e,t,r,n)=>t===void 0?n:ce(e,t,r),ur=(e,t)=>{if(t===void 0)throw Je(e,"a function");if(typeof t!="function")throw Q(e,"a function",t);return t};var ue=()=>Math.floor(performance.now());var Pn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),rt=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},Or=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{}}}),dr=(e,t)=>t?e.map(r=>structuredClone(r)):e,xc=8,Cc=32,Mc=24,kc=16,Pc=-(2**30),vc=2**30-1,Lc=e=>Number.isInteger(e)&&e>=Pc&&e<=vc&&!Object.is(e,-0),Nc=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=Cc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=xc*a.length;for(let i of a)typeof i=="string"?r+=Mc+2*i.length:typeof i=="number"&&!Lc(i)?r+=kc:typeof i=="object"&&i!==null&&n.push(i)}return r},Gt=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;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-ue())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:c,expireAt:ue()+a,epoch:s}),c})(),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,s=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&s===null)throw new rt(o.signal.aborted?"aborted":"busy");try{for(let d of r)d();let c=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:c,expireAt:ue()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),c}finally{s?.()}})(),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 rt("aborted");return this.dropBucket(r),dr(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ue())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),dr(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),dr(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return dr(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new rt("aborted");return dr(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 rt&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.totalBytes=0,this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.dropBucket(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=Oe("cacheDefaultTtlMs",t.defaultTtlMs,1,Pn.defaultTtlMs),this.maxBuckets=Oe("cacheMaxBuckets",t.maxBuckets,1,Pn.maxBuckets),this.maxBytes=Oe("cacheMaxBytes",t.maxBytes,1,Pn.maxBytes),this.lastSweepAt=ue()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=Nc(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=ue();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};var rl=require("@aiquants/request-isolation");var Oc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var ea=e=>e<10?`0${e}`:`${e}`,Hc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=ea(e.getMonth()+1),n=ea(e.getDate());return`${t}-${r}-${n}`},Kt=e=>{let t=Oc.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 s=new Date(0);return s.setUTCFullYear(a,i-1,l),s.getUTCFullYear()!==a||s.getUTCMonth()!==i-1||s.getUTCDate()!==l?null:`${r}-${n}-${o}`},Hr=e=>Kt(e)===e;var We=e=>e==null?null:e instanceof Date?Hc(e):Kt(e);var ta=require("zod/v3"),ct=e=>Number.isSafeInteger(e)&&e>0,He=ta.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var re=require("zod/v3");var Fr=/^(?:[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 vn=/^[0-9a-f]{64}$/u;var Ft=e=>typeof e=="string"&&vn.test(e);var $t=Symbol("daily-report wire mismatch"),Qe=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),$t),aa=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,xt=(e,t)=>({code:"invalid_type",expected:e,received:aa(t)}),Fc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$c=e=>{let t=0;for(let r in e)t+=1;return t},ra=(e,t,r)=>{let n={};for(let o=0;o<r;o+=1){let a=t[o];a in e&&(n[a]=e[a])}return n},Jt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!Fc(n))return Qe(o,null,xt("object",n));let a=null,i=!1,l=0;for(let s=0;s<t.length;s+=1){let c=t[s],d=n[c];d!==void 0&&(l+=1);let u=r[s](d,o,c);if(u===$t){i=!0;continue}a===null&&u!==d&&(a=ra(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?$t:a!==null?a:$c(n)===l?n:ra(n,t,t.length)}},pr=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},mr=e=>(t,r,n)=>{if(!Array.isArray(t))return Qe(r,n,xt("array",t));r.path.push(n);let o=t,a=!1;for(let i=0;i<t.length;i+=1){let l=t[i],s=e(l,r,i);s===$t?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?$t:o},ye=(e,t,r)=>e==null||typeof e=="string"?e:Qe(t,r,xt("string",e)),na=(e,t,r)=>e===null||typeof e=="string"?e:Qe(t,r,xt("string",e)),oa=(e,t,r)=>typeof e=="string"?e:Qe(t,r,xt("string",e)),Uc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:Qe(t,r,xt("number",e)),yr=(e,t,r)=>typeof e=="boolean"?e:Qe(t,r,xt("boolean",e)),ia=(e,t,r)=>typeof e!="string"?Qe(t,r,xt("string",e)):Ft(e)?e:Qe(t,r,{code:"invalid_string",validation:"regex",message:"a content digest is 64 lowercase hex digits"}),Bc=(e,t,r)=>e===null?null:ia(e,t,r),Ln=(e,t,r)=>{if(typeof e=="number"&&ct(e))return e;for(let{message:n,path:o,...a}of He.safeParse(e).error.issues)Qe(t,r,a);return $t},sa={present:!0,absent:!0,unknown:!0},la=Object.keys(sa),Vc=la.map(e=>`'${e}'`).join(" | "),qc=(e,t,r)=>typeof e!="string"?Qe(t,r,{code:"invalid_type",expected:Vc,received:aa(e)}):Object.hasOwn(sa,e)?e:Qe(t,r,{code:"invalid_enum_value",received:e,options:[...la]}),ca=Jt({name:ye,affiliation:ye}),ua=Jt({name:ye,text:ye,color:ye}),da=Jt({id:Ln,name:ye,color:ye}),pa=Jt({id:Ln,userId:ye,userName:ye,content:ye,createdAt:ye,isMine:yr}),jc=Jt({id:oa,fileName:oa,fileType:na,fileSize:Uc,createdAt:na,state:qc,hasThumbnail:yr}),Wc=Jt({reportHubId:Ln,date:ye,createdAt:ye,author:ye,userId:ye,sourceType:ye,employeeName:ye,updatedBy:ye,updatedAt:ye,category:ye,creationCategory:ye,visitTimeFrom:ye,visitTimeTo:ye,customerName:ye,interviewers:mr(pr(ca)),subject:ye,content:ye,externalComments:mr(pr(ua)),isRead:yr,isStarred:yr,contentDigest:ia,readContentDigest:Bc,isDraft:yr,labels:mr(pr(da)),postedComments:mr(pr(pa)),attachments:mr(pr(jc))}),hr=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===$t?{ok:!1,issues:r.issues}:{ok:!0,value:n}},ma=e=>hr(Wc,e),ya=e=>hr(ca,e),ha=e=>hr(ua,e),fa=e=>hr(da,e),Ra=e=>hr(pa,e);var Sa=15e3,ga="lastEventId",Yc=/^\d{1,15}-\d{1,15}$/,ba=e=>Yc.test(e),Ct="0-0",fr=e=>re.z.unknown().transform((t,r)=>{let n=e(t);if(n.ok)return n.value;for(let o of n.issues)r.addIssue({...o,fatal:!0});return re.z.NEVER}),Dy=fr(ya),Ty=fr(ha),Ay=fr(fa),zc=fr(Ra),Rr=fr(ma),Sr=re.z.string().regex(Fr),Da=re.z.object({type:re.z.literal("connected")}),Ta=re.z.object({type:re.z.literal("status-update"),reportHubId:He,statusType:re.z.enum(["star","read"]),value:re.z.boolean(),readContentDigest:re.z.string().regex(vn).nullable(),clientTempId:Sr}),Nn=re.z.string(),Aa=re.z.object({type:re.z.literal("comment-add"),reportHubId:He,comment:zc,clientTempId:Sr,sourceType:Nn}),Ea=re.z.object({type:re.z.literal("comment-delete"),reportHubId:He,commentId:He,clientTempId:Sr,sourceType:Nn}),$r={recipientRawUserId:He.optional()},On=Ta.extend($r),Hn=Aa.extend($r),Fn=Ea.extend($r),Qt={reportHubId:He,report:Rr,clientTempId:Sr},$n={...$r,actorRawUserId:He},Un={viewerIsActor:re.z.boolean()},Gc=re.z.object({type:re.z.literal("report-create"),...Qt,...Un}),Kc=re.z.object({type:re.z.literal("report-update"),...Qt,...Un}),Jc=re.z.object({type:re.z.literal("report-publish"),...Qt,...Un}),Bn=re.z.object({type:re.z.literal("report-create"),...Qt,...$n}),Vn=re.z.object({type:re.z.literal("report-update"),...Qt,...$n}),qn=re.z.object({type:re.z.literal("report-publish"),...Qt,...$n}),Ur=re.z.object({type:re.z.literal("report-delete"),reportHubId:He,clientTempId:Sr,sourceType:Nn}),Ey=re.z.discriminatedUnion("type",[Da,Ta,Aa,Ea,Gc,Kc,Jc,Ur]),Br=re.z.discriminatedUnion("type",[Da,On,Hn,Fn,Bn,Vn,qn,Ur]);var wa="ids-columns";var Qc=/^[0-9a-f]{1,16}$/,Ia=e=>ct(e.reportHubId)&&(e.businessDate===null||Hr(e.businessDate)),_a=e=>typeof e=="string"&&Qc.test(e),xy=Object.freeze({kind:"absent"}),Cy=Object.freeze({kind:"value",value:null});var Ut=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:h}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let m=h===void 0?null:h,y=s.get(m);y===void 0&&(y=i.length,i.push(m),s.set(m,y)),l.push(y)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},Vr=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+(?=.)/,"")},xa=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Xc=(e,t,r,n)=>xa(e,t,r,n)<0,jn=(e,t)=>xa(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Ca=e=>{for(let t=1;t<e.length;t++)if(!Xc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},Ma=(e,t)=>{let r=e.findIndex(n=>jn({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var de=Object.freeze({businessDate:"business-date",idsStream:wa,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),Ae=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var ka=(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)}}},vy=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),Pa=e=>`[DailyReport${e}]`,Ee=(e,t,r)=>e===void 0?ka(t,Pa(r)):ka(0,Pa(r),e);var Mt=require("zod/v3");var gr=e=>({reportHubId:e,outcome:"not_found"}),Hy=Mt.z.discriminatedUnion("outcome",[Mt.z.object({reportHubId:He,outcome:Mt.z.literal("ok"),report:Rr}).strict(),Mt.z.object({reportHubId:He,outcome:Mt.z.literal("not_found")}).strict(),Mt.z.object({reportHubId:He,outcome:Mt.z.literal("failed")}).strict()]);var Zc="legacy-",Wn=e=>`${Zc}${e}`;var eu=/^[1-9][0-9]*$/,tu=/^(?:0|[1-9][0-9]*)$/,nt=e=>{if(e===null||!eu.test(e))return null;let t=Number(e);return ct(t)?t:null},Yn=e=>{if(e===null||!tu.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},zn=e=>e==="true"?!0:e==="false"?!1:null,br=e=>e===null?!1:zn(e);var va=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),St=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var ru=16777619,Gn=2166136261,Kn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,ru);return o>>>0},La=e=>Kn(Gn,e,0,e.length),nu=String.fromCodePoint(3),ou=String.fromCodePoint(2),au=String.fromCodePoint(1),qr=e=>La(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(nu)).join(ou)).join(au));var Na=e=>e==="intersection"||e==="union",Pe=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Jn=2,jr=2,Bt=Object.freeze({word:0,reading:1});var Qn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var qy=2*(1+Jn);var iu=require("zod/v3");var Oa=e=>e.issues.map(t=>`${t.path.length===0?"(root)":t.path.join(".")}: ${t.code}`).join("; ");var Ce=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",contentDigest:"contentDigest",commentId:"commentId"});var Wr=Math.max(1,Math.floor(10.556701030927835));var ot=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var ve=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(c=>[c,0]))};o.set(i,l),ot(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var gt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var Qy=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),su=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Xn=e=>{let t=e.trim();return t.length===0?null:t.replace(su,"\uFFFD")},lu=e=>{let t=Xn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>gt.maxValueLength?"filter-value-too-long":null},cu=e=>{if(e.length>gt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=lu(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},uu=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Ha=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=cu(t);if(r!==null)return r}return uu(e)>gt.maxTotalValueLength?"filters-too-long":null};var Fa=e=>e.trim().length===0;var Yr=e=>e!==null&&Fr.test(e)?e:null,Zn=e=>Na(e)?e:null,eo=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=nt(n);if(o===null||r.includes(o))return null;r.push(o)}return r},$a=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},Ua=(e,t)=>{let r={authors:e.getAll(Ae.searchAuthor),sourceTypes:e.getAll(Ae.searchSourceType),customers:e.getAll(Ae.searchCustomer)},n=Ha(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:$a(r.authors),customers:$a(r.customers)}}},Ba=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var qa=Object.freeze({status:400,error:"Invalid form"}),ja=e=>({status:413,error:"Form too large",measuredBy:e}),du=(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)}}))},pu=async e=>{let t=Yn(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:ja("declared")};let r=!1,n=e.body===null?null:du(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?ja("counted"):qa}}let l=Ba(i);return l===null?{refusal:qa}:{fields:l}},Ya=(e,t)=>{let r=e.get(t);if(r===null)return{error:`${t} required`};let n=zn(r);return n===null?{error:`Invalid ${t}`}:{value:n}},mu=(e,t)=>{let r=Ya(e,Ce.isStarred);return"error"in r?r:{command:{...t,intent:"toggleStar",value:r.value}}},yu=(e,t)=>{let r=Ya(e,Ce.isRead);if("error"in r)return r;let n=e.get(Ce.contentDigest);return r.value?n===null?{error:`${Ce.contentDigest} required`}:Ft(n)?{command:{...t,intent:"toggleRead",value:!0,contentDigest:n}}:{error:`Invalid ${Ce.contentDigest}`}:n===null?{command:{...t,intent:"toggleRead",value:!1}}:{error:`${Ce.contentDigest} is not allowed when ${Ce.isRead} is false`}},za=Object.freeze({update:(e,t,r)=>{let n=e.get(Ce.title),o=e.get(Ce.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:mu,toggleRead:yu,addComment:(e,t)=>{let r=e.get(Ce.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=nt(e.get(Ce.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),hu=e=>Object.hasOwn(za,e),fu=(e,t)=>{let r=e.get(Ce.intent),n=e.get(Ce.businessDate),o=n===null?null:Kt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Ce.operationTimestamp),i=Yn(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Ce.clientTempId);if(!l)return{error:"clientTempId required"};let s=Yr(l);if(s===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:i}};let c=nt(e.get(Ce.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!hu(r)?{error:"Invalid intent"}:za[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Ga=async(e,t)=>{let r=await pu(e);if("refusal"in r)return r;let n=fu(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Ru=6e4,Su="form_too_large",Wa=["declared","counted"],Ka=e=>{let t=ve({windowMs:Ru,tallies:Wa,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Wa.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(Su,r,n)}};var Vt=Object.freeze({[de.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[de.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[de.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[de.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[de.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[de.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[de.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),Ja=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),to=e=>e!==void 0&&Object.hasOwn(Vt,e);var ro=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Qa=e=>Object.hasOwn(ro,e);var gu="download",bu="thumbnail",Du="1";var no=e=>{let t=e.getAll(bu),r=e.getAll(gu);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Qa(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Du?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var ri=require("@aiquants/request-isolation");var Xa=require("crypto"),oo=e=>`"${(0,Xa.createHash)("sha256").update(e).digest("hex")}"`,Za=e=>oo(JSON.stringify(e));var ut=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),ao=(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},ei=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=oo(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...ut});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&ao(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},io=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...ut});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},so=e=>(t,r,n,o)=>{if(o!==200)return io(r,n,o);if(e===null||n===null)throw new Error(`[daily-report] API route: a 200 JSON answer needs an answer of a JSON 200 and a body; got ${e===null?"a responder without one":"an answer"} and ${n===null?"no body":"a body"}`);return e(t,r,n)},Tu=5e3/1e3,Au=new Map([[503,Tu]]),_e=e=>{let t=Au.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var co="Cross-site request rejected",Eu="Not Found",ti=["api","action","sse","attachment"],ni=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...ut}}),wu=()=>ni(403,co),zr=()=>ni(404,Eu),Dr=Object.freeze({...ri.NO_CROSS_ORIGIN_NAVIGATION,frameworkDataRefusal:()=>null,crossSiteRejection:wu}),oi=e=>new URL(e.url).pathname.endsWith(".data"),Iu=6e4,_u="refusals",xu=32,Cu=/^[a-z-]+$/,lo=e=>{if(e===null)return"-";let t=e.slice(0,xu);return Cu.test(t)&&t===e?e:JSON.stringify(t)},ai=e=>{let t=ve({windowMs:Iu,tallies:ti,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${ti.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n,o)=>{let a=()=>{let{headers:i}=o;e.warn(`cross_site_rejected route=${r} reason=${n} site=${lo(i.get("Sec-Fetch-Site"))} mode=${lo(i.get("Sec-Fetch-Mode"))} dest=${lo(i.get("Sec-Fetch-Dest"))} method=${o.method}`)};t.record(_u,r,a)}};var ii=(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 Mu="same-origin",ku="SAMEORIGIN",Xt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Mu,"X-Frame-Options":ku}),Gr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Xt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},si=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Pu=/^[\x20-\x7E]+$/,vu=/^[\w.+-]+\/[\w.+-]+/,uo=e=>e&&Pu.test(e)&&vu.test(e)?e:null,Lu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,li=e=>encodeURIComponent(e.replace(Lu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),ci=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),Tr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},ui={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Kr=e=>typeof e=="string"&&Object.hasOwn(ui,e),Jr=e=>ui[e],bt="Attachment request failed";var dt=e=>{let t=ce("limit",e.limit,1),r=ce("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ce("queue.max",e.queue.max,0),maxPerOwner:ce("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ce("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(p,f)=>p.get(f)??0,c=(p,f,D)=>{let w=s(p,f)+D;w<=0?p.delete(f):p.set(f,w)},d=p=>s(l,p)<r,u=p=>o<t&&d(p),h=p=>(o+=1,c(l,p,1),R(p)),m=()=>{let p=-1,f=r;for(let[D,w]of a.entries()){let S=s(l,w.owner);if(S<f&&(p=D,f=S,S===0))break}return p},y=()=>{for(;o<t;){let p=m();if(p<0)return;let[f]=a.splice(p,1);c(i,f.owner,-1),f.grant(h(f.owner))}},R=p=>{let f=!1;return()=>{f||(f=!0,o-=1,c(l,p,-1),y())}};return{canAcquire:u,acquire:(p,f)=>{if(f.aborted)return Promise.resolve(null);if(u(p))return Promise.resolve(h(p));if(n===null||a.length>=n.max||s(i,p)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:D}=n,w=S=>{let g=()=>{let H=a.indexOf(C);H<0||(a.splice(H,1),c(i,p,-1),T(),S(null))},M=ot(g,D),T=()=>{clearTimeout(M),f.removeEventListener("abort",g)},C={owner:p,grant:H=>{T(),S(H)}};a.push(C),c(i,p,1),f.addEventListener("abort",g,{once:!0})};return new Promise(w)}}};var Nu=1024,po="Too many requests",Ou=(e,t)=>{ce("limitPerWindow",e,1),ce("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 s=l??{tokens:e,lastRefillMs:i};n(s,i),r.set(a,s);for(let c of r.keys()){if(r.size<=Nu)break;r.delete(c)}return s};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let s=r.get(a);s&&(n(s,i),s.tokens=Math.min(e,s.tokens+l))}}},Dt=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ce("windowMs",r,1e3)%1e3!==0)throw Q("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Ou(e.limitPerWindow,r),i=Object.freeze({status:429,message:po,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=ve({windowMs:r,tallies:[t],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`${t}_suppressed count=${c} since=${d} ${o(s)}`)}});return{spend:(s,c)=>a.consume(s,ue())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,ue(),c)}}};var Fu=256*1024,di=6e4,$u=e=>Math.ceil(e/2),Uu=new Uint8Array(new ArrayBuffer(0)),Bu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Uu,t()},i=l=>{clearTimeout(o),o=ot(()=>{l.error(new Error(`attachment body idle for ${di} ms`)),a()},di)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Fu,r.byteLength);if(s>n&&l.enqueue(r.slice(n,s)),n=s,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},pi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=Dt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=dt({limit:e.concurrency,maxHeldPerOwner:$u(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:h,readAttachment:m,cookie:y,fail:R}=s,p=e.maxBytes,f=i.spend(h,`attachment=${u} viewer=${h}`);if(f)return R(f.status,f.message,f.headers);let D=await n(c,"initial");if(!D.ok)return R(503,Tr[503],_e(503));let w=await t.getAttachmentForUser(D.scope,u,h);if(!w)return o.warn(`404 attachment=${u} viewer=${h} reason=not_visible`),R(404,"Attachment not found");if(w.fileSize!=null&&w.fileSize>p)return o.warn(`413 attachment=${u} viewer=${h} reason=db_size`),R(413,"Attachment too large");let S=uo(w.fileType),g=`filename="${ci(w.fileName)}"; filename*=UTF-8''${li(w.fileName)}`,M=await l.acquire(h,c.signal);if(!M)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${h} reason=aborted`),R(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${h} reason=concurrency`),R(503,"Too many concurrent downloads",_e(503)));let T=!1;try{let C=await m(w.filePath,{maxBytes:p,head:c.method==="HEAD",principal:r(h),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${h} reason=aborted`),R(503,"Attachment request aborted");if(!C.ok){if(!Kr(C.reason))return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=failure_reason`),R(500,bt);let $=Jr(C.reason);return C.reason==="not_found"&&a(u,!1),o.warn(`${$} attachment=${u} viewer=${h} reason=${C.reason} code=${C.code??"-"}`),R($,Tr[$],_e($))}if(C.bytes.byteLength>p)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),R(500,bt);let H=c.method==="HEAD";if(H&&C.size!==void 0&&C.size>p)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),R(500,bt);if(!H&&C.size!==void 0&&C.size!==C.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=size_mismatch`),R(500,bt);let I=S??uo(C.contentType),L=I!==null&&si.has(I),x=L?I:"application/octet-stream",j=L&&d.kind!=="download"?"inline":"attachment",X=H?C.size:C.bytes.byteLength,J=new Headers({"Content-Type":x,"Content-Disposition":`${j}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Xt});return X!==void 0&&J.set("Content-Length",String(X)),y&&J.append("Set-Cookie",y),a(u,!0),o.info(`200 attachment=${u} viewer=${h} type=${x} disposition=${j} bytes=${X??"-"}`),H?new Response(null,{status:200,headers:J}):(T=!0,new Response(Bu(C.bytes,M),{status:200,headers:J}))}finally{T||M()}}};var Ye=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),$h=Ye.queueWaitMs+Ye.readMs+Ye.renderMs+Ye.transferMarginMs;var hi=require("buffer"),fi=new Set([194,198,202,206]),Vu=new Set([192,193,194,195]),Ri=216,qu=217,Si=218,ju=4,Wu=64,Yu=2,mi=8,yi=28,kt=12,mo=8,zu=20,gi=kt+mo+10,Gu=2,Tt=(e,t)=>e[t]<<8|e[t+1],Zt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},pt=(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},bi=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Di=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),Ti=e=>(e.stepsLeft-=1,e.stepsLeft>=0),Ai=e=>e[0]===255&&e[1]===Ri,Ei=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!Ti(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===qu)return"eoi";if(o===0||o===Ri)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=Tt(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")}},Ku=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!Ti(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}},wi=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=Tt(e,r+1),a=Tt(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let s=0;s<i;s+=1){let c=e[r+7+3*s],d=c>>4,u=c&15;if(d<1||d>4||u<1||u>4)return null;l.push({id:e[r+6+3*s],horizontal:d,vertical:u})}return{marker:t,width:a,height:o,components:l}},Ii=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>ju||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},_i=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:fi.has(e.marker)||t<e.components.length}),yo=e=>{if(!Ai(e))return null;let t=Di(e.byteLength),r=null;for(let n=2;;){if(Ei(e,n,t)!=="segment")return null;if(bi(t.marker)){if(r!==null||(r=wi(e,t),r===null))return null}else if(t.marker===Si){if(r===null)return null;let o=Ii(e,t);return o===null?null:_i(r,o.length)}n=t.end}},xi=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*mi)),i=Math.ceil(e.height*o/(r*mi));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},Ci=e=>e.multiScan?xi(e).reduce((r,n)=>r+n,0)*Wu*Yu:0,Ju=896,Mi=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!Ai(e))return null;let n=hi.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=Di(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let h=Ei(e,u,o);if(h===null)return null;if(h==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,bi(o.marker)){if(a!==null||!Vu.has(o.marker)||(a=wi(e,o),a===null))return null;let m=xi(a);l=new Map;for(let[y,R]of a.components.entries()){let p=l.get(R.id);l.set(R.id,p===void 0?m[y]:Math.max(p,m[y]))}s=a.components.length*(fi.has(a.marker)?Ju:1)}else if(o.marker===Si){if(a===null||d===s)return null;let m=Ii(e,o);if(m===null)return null;for(let R of m){let p=l.get(R);if(p===void 0)return null;c+=p}if(d+=1,i===null&&(i=_i(a,m.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let y=Ku(n,o.end,o);if(y===null)return null;u=y}}},ki=e=>{if(e.byteLength<24||Tt(e,8)!==0||Tt(e,10)!==13||!pt(e,12,"IHDR"))return null;let t=Tt(e,16)*65536+Tt(e,18),r=Tt(e,20)*65536+Tt(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Qu=e=>{if(pt(e,kt,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Zt(e,26,2)&16383,r=Zt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(pt(e,kt,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Zt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return pt(e,kt,"VP8X")?e.byteLength<gi?null:{width:Zt(e,24,3)+1,height:Zt(e,27,3)+1}:null},Pi=e=>{if(ki(e)===null||e.byteLength<=yi)return null;switch(e[yi]){case 0:return!1;case 1:return!0;default:return null}},vi=(e,t)=>{if(pt(e,kt,"VP8 "))return"lossy";if(pt(e,kt,"VP8L"))return"lossless";if(!pt(e,kt,"VP8X")||e.byteLength<gi)return null;if((e[zu]&Gu)!==0)return"animated";let r=!1,n=t;for(let o=kt;o+mo<=e.byteLength;){if(n-=1,n<0)return null;if(pt(e,o,"VP8L"))return"lossless";if(pt(e,o,"VP8 "))return r?"lossy-alpha":"lossy";pt(e,o,"ALPH")&&(r=!0);let a=Zt(e,o+4,4);o+=mo+a+a%2}return null},Li={png:ki,jpeg:yo,webp:Qu};var Qr=Object.freeze(["image/webp","image/jpeg","image/png"]),Xr=1024*1024;var Xu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Zu={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},ed=new Set(Qr),td=e=>typeof e=="string"&&ed.has(e),rd=256,Zr=(e,t)=>e.fileType===null||!Xu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,nd=[137,80,78,71,13,10,26,10],od=[255,216,255],ad=[[71,73,70,56,55,97],[71,73,70,56,57,97]],id=[82,73,70,70],sd=[87,69,66,80],Ar=(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},ho=e=>{if(Ar(e,nd,0))return"png";if(Ar(e,od,0))return"jpeg";for(let t of ad)if(Ar(e,t,0))return"gif";return Ar(e,id,0)&&Ar(e,sd,8)?"webp":null},Ni=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:Za([t])}},Oi=(e,t)=>{if(!td(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Xr)return"too_large";let r=Zu[e.contentType];if(ho(e.bytes)!==r)return"signature";let n=Li[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Hi=e=>{ce("maxBytes",e.maxBytes,0),ce("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)+rd;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 s of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(s)}}}};var fo=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ue(),l=new AbortController,s=!1,c,d,u=()=>{a(ue()-i)},h=S=>{c=ot(()=>{s=!0,S({timedOut:!0}),d=ot(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},m=new Promise(h),y=AbortSignal.any([r,l.signal]),R=S=>{S(n(y))},p=new Promise(R),f=S=>(clearTimeout(c),clearTimeout(d),s&&o(ue()-i,S.kind==="error"?{error:S.error}:null),S),D=p.then(S=>f({kind:"value",value:S}),S=>f({kind:"error",error:S}));return{outcome:Promise.race([p.then(S=>({timedOut:!1,value:S})),m]),settled:D}};var At={404:"Attachment not found",500:bt,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Fi=(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=Oi(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},ld=e=>{let t=new AbortController,r=()=>{t.abort()},n=ot(r,Ye.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},$i=()=>{},cd=(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)}),Ui=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(m,y)=>{let R=y.then($i,$i);l.set(m,R);let p=()=>{l.get(m)===R&&l.delete(m)};R.then(p)},c=async(m,y)=>{let R=l.get(m.key);if(R===void 0)return t.acquire(m.owner,y);let p=ld(y);try{if(await cd(R,p.signal),p.signal.aborted)return null;let f=r.get(m.key);return f!==void 0?{...f,identity:"verified"}:await t.acquire(m.owner,p.signal)}finally{p.end()}},d=(m,y)=>{if(m.fileSize===null)return y.kind==="exact"?"verified":"unrecorded";if(y.kind==="exact"?y.bytes===m.fileSize:m.fileSize>y.maxBytes)return"verified";let p=y.kind==="exact"?String(y.bytes):`>${y.maxBytes}`;return i.warn(`size_mismatch expected=${m.fileSize} got=${p} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`),"unverified"},u=(m,y)=>(R,p)=>{let f=p===null?"":` message=${p.error instanceof Error?p.error.message:"unknown"}`;i.warn(`${m}_overrun ms=${R} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail${f}`)},h=(m,y)=>R=>{i.warn(`${m}_stuck ms=${R} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail`)};return async(m,y)=>{let R=await c(m,y);if(R===null)return{kind:"failure",status:503,reason:y.aborted?"aborted":"queue"};if(typeof R!="function")return R;let p=R,f=null;try{if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let D=r.get(m.key);if(D!==void 0)return{...D,identity:"verified"};let w=fo({budgetMs:Ye.readMs,flightSignal:y,call:$=>m.readAttachment(m.filePath,{maxBytes:n,head:!1,principal:o(m.owner),signal:$}),onOverrun:u("read",m),onStuck:h("read",m)}),S=await w.outcome;if(S.timedOut)return f=w.settled,y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=S.value;if(!g.ok&&g.reason!=="too_large")return Kr(g.reason)?(g.reason==="not_found"&&a(m.attachmentId,!1),{kind:"failure",status:Jr(g.reason),reason:g.reason,code:g.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(g.ok&&g.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let M=d(m,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),T=$=>{M==="verified"&&r.set(m.key,$)},C=$=>(T($),{...$,identity:M});if(!g.ok)return C({kind:"unrenderable",reason:"too_large"});let H=ho(g.bytes);if(H===null)return C({kind:"unrenderable",reason:"signature"});let I=fo({budgetMs:Ye.renderMs,flightSignal:y,call:$=>m.renderer.render(g.bytes,{format:H,maxWidth:m.box.maxWidth,maxHeight:m.box.maxHeight,signal:$}),onOverrun:u("render",m),onStuck:h("render",m)}),L=$=>{if($.kind==="error")return;let _=Fi($.value,m.box);"entry"in _&&T(_.entry)},x=null,j=()=>(x===null&&(x=I.settled.then(L),s(m.key,x)),x);y.addEventListener("abort",j,{once:!0});let X=await I.outcome.finally(()=>y.removeEventListener("abort",j));if(X.timedOut||y.aborted)return f=j(),y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let J=Fi(X.value,m.box);return"entry"in J?C(J.entry):J.failure}finally{f===null?p():f.then(p,p)}}};var Bi=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let s=new AbortController,c=()=>{e.get(t)?.controller===s&&e.delete(t)},u={promise:n(s.signal).finally(c),controller:s,waiters:0};return e.set(t,u),u},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 ji=10,ud=1/ji,Vi=1-ud,dd=1024,pd=64,md=8,qi="private, no-cache",yd="no-store",hd=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),fd=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Wi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(S,g)=>Dt({reason:S,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:M=>`viewer=${M} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*ji),h=dt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:pd,maxPerOwner:md,maxWaitMs:Ye.queueWaitMs}}),m=Hi({maxBytes:l.cacheBytes,maxEntries:dd}),y=Bi(),R=Ui({gate:h,cache:m,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),p=(S,g,M,T)=>{let C=`attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail cache=${T}`;if(g.kind==="failure")return o[fd(g)](`${g.status} ${C} reason=${g.reason} code=${g.code??"-"}`),S.fail(g.status,At[g.status],_e(g.status));let H=hd[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${C} reason=${g.reason}${H}`),S.fail(404,At[404]);let I=g.identity==="verified"?{"Cache-Control":qi,ETag:M}:{"Cache-Control":yd},L=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...I,"Content-Security-Policy":"default-src 'none'; sandbox",...Xt});return S.cookie&&L.append("Set-Cookie",S.cookie),o.info(`200 ${C} type=${g.contentType} bytes=${g.bytes.byteLength}${H}`),new Response(g.bytes,{status:200,headers:L})},f=(S,g)=>{let M=S.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return M===null?null:g.fail(M.status,M.message,M.headers)},D=S=>f(d,S),w=(S,g)=>g?f(u,S):D(S);return async(S,g)=>{let{request:M,attachmentId:T,internalUserId:C,readAttachment:H,cookie:I,fail:L}=S,x=ro[g],j=M.headers.get("If-None-Match"),X=j!==null,J=w(S,X);if(J)return J;let $=await n(M,"initial");if(!$.ok)return L(503,At[503],_e(503));let _=await t.getAttachmentForUser($.scope,T,C),Y=_!==null&&Zr(_,i)?Ni({rendererId:s.id,box:x,attachmentId:T,filePath:_.filePath,fileType:_.fileType,fileSize:_.fileSize}):null;if(Y&&ao(j,Y.etag)){let b=new Headers({"Cache-Control":qi,ETag:Y.etag,...Xt});return I&&b.append("Set-Cookie",I),o.info(`304 attachment=${T} viewer=${C} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:b})}if(X){let b=D(S);if(b)return b}if(!_)return o.warn(`404 attachment=${T} viewer=${C} variant=thumbnail reason=not_visible`),L(404,At[404]);if(!Y)return d.refund(C,Vi),o.info(`404 attachment=${T} viewer=${C} variant=thumbnail reason=not_eligible`),L(404,At[404]);let{key:pe,etag:ie}=Y,me=m.get(pe);if(me)return d.refund(C,Vi),p(S,{...me,identity:"verified"},ie,"hit");let De=b=>R({key:pe,attachmentId:T,filePath:_.filePath,fileSize:_.fileSize,box:x,owner:C,readAttachment:H,renderer:s},b),Z;try{Z=await y.join(pe,M.signal,De)}catch(b){return o.error(`500 attachment=${T} viewer=${C} variant=thumbnail cache=miss reason=port_exception message=${b instanceof Error?b.message:"unknown"}`),L(500,At[500])}return p(S,Z,ie,"miss")}};var Rd='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Sd=()=>Gr(403,co,{cookie:null}),Yi=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=no(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Gr(404,Tr[404],{cookie:null}),crossSiteRejection:Sd}),zi=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:ii(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:pi({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Wi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,h=(m,y,R={})=>Gr(m,y,{cookie:u,extraHeaders:R});try{let{user:m,cookie:y}=await t(c,{failureRedirect:null});if(u=y??null,!m)return h(401,"Unauthorized");let R=no(new URL(c.url).searchParams);if(R.kind==="invalid")return h(400,"Invalid attachment request");if(R.kind==="thumbnail"&&c.method!=="GET")return h(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return h(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return h(404,"Attachment not found");if(d.token===void 0)throw new Error(Rd);let p=s.idCodec.decode(d.token);if(p===null||!ct(p))return h(400,"Invalid attachment token");let f=await r.getUserIdByExternalId(m.id);if(!f)return h(403,"Forbidden");let D={request:c,delivery:R,attachmentId:p,internalUserId:f,readAttachment:s.read,cookie:u,fail:h};return R.kind!=="thumbnail"?await s.serveOriginal(D):s.serveThumbnail===null?h(404,At[404]):await s.serveThumbnail(D,R.variant)}catch(m){if(m instanceof Response)throw m;return a.error(`500 attachment=? viewer=? reason=unexpected message=${m instanceof Error?m.message:"unknown"}`),h(500,bt)}}};var gd=32*1024*1024,bd=60,Dd=4,Td=120,Ad=2,Ed=8*1024*1024,en=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wd=e=>{if(e===void 0)throw Je("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!en(e))throw Q("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Je("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw Q("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Q("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Id=e=>{if(e===void 0)return null;if(!en(e))throw Q("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:wd(e.renderer),rateLimitPerMinute:Oe("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Td),concurrency:Oe("attachments.thumbnails.concurrency",e.concurrency,1,Ad),cacheBytes:Oe("attachments.thumbnails.cacheBytes",e.cacheBytes,0,Ed)})},Gi=e=>{let t=e;if(t===void 0)return null;if(!en(t))throw Q("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Je("attachments.idCodec","injected when attachments is given");if(!en(r)||typeof r.encode!="function"||typeof r.decode!="function")throw Q("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Je("attachments.read","injected when attachments is given");if(typeof n!="function")throw Q("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Oe("attachments.maxBytes",t.maxBytes,1,gd),rateLimitPerMinute:Oe("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,bd),concurrency:Oe("attachments.concurrency",t.concurrency,1,Dd),thumbnails:Id(t.thumbnails)})},_d=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"]]),tn=e=>{for(let[t,r]of _d)if(Object.hasOwn(e,t))throw Je(r,`given in place of the flat key ${t}`)};var Ji=8,xd=8*Ji,Cd=128,Md=2,Qi=Md*Cd,kd=4*Qi,Pd=6e4,vd=6e4,Ld="Too many reads",Ki=Object.freeze(Object.keys(Vt).filter(e=>Vt[e].admission.includes("miss-gate"))),Xi=e=>{let t=dt({limit:xd,maxHeldPerOwner:Ji,queue:{max:kd,maxPerOwner:Qi,maxWaitMs:Pd}}),r=ve({windowMs:vd,tallies:Ki,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Ki.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}})}},rn=(e,t,r)=>{let n=e(t,r,{error:{message:Ld}},503);for(let[o,a]of Object.entries(_e(503)))n.headers.set(o,a);return n};var Zi=e=>{let t=e.get(Ae.cursorReportHubId),r=e.get(Ae.cursorBusinessDate),n=e.get(Ae.cursorSnapshot),o=_a(n)?n:null,a=null;if(t!==null){let l=nt(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!Ia(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=br(e.get(Ae.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var nn=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Nd=2,Od=16,Hd=Nd*Od,Fd=6e4,es=()=>{},$d=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},ts=e=>{let t=dt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Hd,queue:null}),r=ve({windowMs:Fd,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 es;if(a.aborted){if(t.canAcquire(n))return es}else{let i=await t.acquire(n,a);if(i!==null)return $d(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var on=30,is=4e3,Ud="stream interrupted by server error",Bd="Too many streams",Vd=15e3,ss=Symbol("ids-stream-heartbeat"),rs=()=>{},ns=e=>e.return(void 0).then(rs,rs),qd=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(ss),Vd)}),stop:()=>clearTimeout(e)}};async function*os(e,t,r,n){let o=t?Ma(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:is),e.length),l=Ut(e,o,i),s=i>o?e[i-1]:void 0;o=i;let c=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:c||s===void 0?null:{businessDate:s.businessDate,reportHubId:s.reportHubId},isLast:c,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,c)return}}var ls=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...ut});return e&&t.append("Set-Cookie",e),t},as=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await ns(t);try{d.close()}catch{}},i=new TextEncoder,l=!1,s=null,c=new ReadableStream({async pull(d){if(l||r.aborted){await a(d,!0);return}let u=qd();try{s===null&&(s=t.next());let h=await Promise.race([s,u.fired]);if(u.stop(),h===ss){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
2
+ `));return}s=null;let{value:m,done:y}=h;if(y){await a(d,!1);return}if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`${JSON.stringify(m)}
3
+ `))}catch(h){if(u.stop(),s=null,o(),l||r.aborted)return;h instanceof rt||n.error(`ids-stream emission failed: ${h instanceof Error?h.message:String(h)}`);try{let m={kind:"error",error:Ud};d.enqueue(i.encode(`${JSON.stringify(m)}
4
+ `)),d.close()}catch{}}},cancel(){l=!0,o(),ns(t)}});return new Response(c,{status:200,headers:ls(e)})},cs=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,s,c,d,u,h,m)=>{let y=!1,R=null,p=null,f=new Promise((S,g)=>{R=S,p=g});f.catch(()=>{});let D=t.getDailyReportIdsByExternalId(c,s.id,{forceRefresh:l.forceRefresh,admission:m,onFetchStart:l.cursor?void 0:()=>{y=!0,t.readSseStreamAnchor().then(S=>t.getDailyReportIdsFirstPageByExternalId(c,s.id,on).then(g=>({items:g,streamAnchor:S}))).then(S=>R?.(S),S=>p?.(S))}});if(D.catch(()=>{}),l.cursor){let{items:S,streamAnchor:g,snapshot:M}=await D,T=l.snapshot!==null&&l.snapshot===M;return as(d,os(S,T?l.cursor:null,on,{snapshot:M,restarted:!T,streamAnchor:g}),u,r,h)}let w=(async function*(){let S=await Promise.race([D.then(T=>({kind:"full",source:T}),T=>({kind:"full-error",error:T})),f.then(T=>({kind:"page",page:T}),()=>({kind:"page-error"}))]),g=null,M=!1;if(S.kind==="full")g=S.source;else if(S.kind==="page"){let{items:T,streamAnchor:C}=S.page;if(T.length<on){yield{kind:"chunk",...Ut(T,0,T.length),nextCursor:null,isLast:!0,total:T.length,streamAnchor:C};return}yield{kind:"chunk",...Ut(T,0,T.length),nextCursor:null,isLast:!1,provisional:!0},M=!0}else if(S.kind==="full-error"&&y){let T=await f.catch(()=>null);T&&T.items.length>0&&(yield{kind:"chunk",...Ut(T.items,0,T.items.length),nextCursor:null,isLast:!1,provisional:!0})}g===null&&(g=await D),yield*os(g.items,null,M?is:on,{snapshot:g.snapshot,streamAnchor:g.streamAnchor})})();return as(d,w,u,r,h)};return async(l,s,c,d,u,h)=>{let m=Zi(l.searchParams);if("refused"in m)return h(c,s,{error:{message:m.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:y}=m;if(y.forceRefresh){let D=a(d,c,s,h);if(D!==null)return D}let R=nn(c),p=await t.getUserIdByExternalId(d.id),f=await n.admit(p,"ids-stream",R);if(f===null){let D=h(c,s,{error:{message:Bd}},503);for(let[w,S]of Object.entries(_e(503)))D.headers.set(w,S);return D}if(R.aborted)return new Response(null,{status:200,headers:ls(s)});try{return await i(y,d,u,s,R,f,p===null?void 0:o.admissionFor(p,de.idsStream,R))}catch(D){if(f(),D instanceof rt)return rn(h,c,s);throw D}}};var qt=require("drizzle-orm");var ze="Internal",us=e=>e.trim().toLowerCase();var jd="",Wd=64,Yd=e=>e.toLowerCase(),ds=e=>{let t=new Set;if(!Array.isArray(e))return t;for(let r of e){if(typeof r!="string")continue;let n=us(r);n.length>0&&t.add(n)}return t};function Me(e,t){return e===null?!0:t==null?!1:e.has(Yd(t))}function $e(e){return e!==null&&e.size===0}var zd=4e3,So=e=>{let t=e.getSQLType();if(!t.startsWith("nvarchar("))throw Q("tables.hub.sourceType","an nvarchar(n) column with a declared length (source types compare as UTF-16 bytes)",t);return ce("tables.hub.sourceType.length",e.length,1,zd)};function wr(e,t){if(t===null)return;let r=So(e),n=[...t].filter(a=>a.length<=r);if(n.length===0)return qt.sql`1 = 0`;let o=qt.sql.raw(`VARBINARY(${2*r})`);return(0,qt.inArray)(qt.sql`CAST(LOWER(${e}) AS ${o})`,n.map(a=>qt.sql`CAST(${a} AS ${o})`))}var er,tr,Er=class Er{constructor(t,r){Cn(this,er);Cn(this,tr);Mn(this,er,t),Mn(this,tr,r)}get visible(){return cr(this,er)===null?null:new Set(cr(this,er))}get commentable(){return cr(this,tr)===null?null:new Set(cr(this,tr))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=ds(r?t.read:t);if(!r||t.comment===void 0)return new Er(n,n);let o=new Set;for(let a of ds(t.comment))n.has(a)&&o.add(a);return new Er(n,o)}static unrestricted(t){return new Er(null,null)}};er=new WeakMap,tr=new WeakMap;var Xe=Er,Ro=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),Gd=new Set(["read","comment"]),ms=e=>{if(Ro(e))return Xe.restrictTo(e);if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=Object.keys(e);if("unrestricted"in e){let o=e.unrestricted;return t.length===1&&typeof o=="string"&&o.trim().length>0?Xe.unrestricted(o):null}let{read:r,comment:n}=e;return t.every(o=>Gd.has(o))&&Ro(r)?n===void 0?Xe.restrictTo({read:r}):Ro(n)?Xe.restrictTo({read:r,comment:n}):null:null};function an(e){let t=ps(e.visible),r=ps(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function ps(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(jd);if(t.length<=Wd)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 ys=(e,t,r,n)=>Me(n.commentable,t)||e.authorUserId===r;var Ms=require("@aiquants/fuzzy-search");var Ss=require("crypto"),go=require("timers/promises"),ge=require("@aiquants/fuzzy-search/normalize");var ln=`
5
+ `,bo=4e3,Kd=1,gs=new Set([8203,8288,65279,173]),Jd=new RegExp(`[${String.fromCodePoint(...gs)}]`,"gu"),bs=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),Ds=/(\s+)/u,Qd=/^\s+$/u,Xd=new RegExp(Ds.source,"gu"),Zd=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,ep=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]),cn=e=>e.replace(Jd,"");var Do=e=>(0,ge.normalizeText)(e,ge.DEFAULT_NORMALIZE_OPTIONS),sn=e=>Do(cn(e)),tp=(0,ge.resolveNormalizeOptions)({...ge.DEFAULT_NORMALIZE_OPTIONS,convertRomaji:!0},"[daily-report] search reading options"),rp=3,np=/^[-ー]+/u,op=/[^\p{L}\p{M}]/gu,ap=/ー{2,}/gu,ip=/\p{Script=Latin}/u,hs=/(?=\p{L})\p{Script=Latin}/u,sp=e=>(0,ge.clusterCountOf)(e.replace(np,"").replace(op,"").replace(ap,"\u30FC")),lp=(e,t)=>{for(let r of t)if(!(0,ge.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})`)},Ts=e=>{if(!hs.test(e))return[];let t=sn(e);if(!hs.test(t))return[];let r=(0,ge.queryNeedles)(t,tp,!1);lp(t,r);let n=[];for(let o of r){if(o.tier===Bt.word)continue;let a=sn(o.text);if(!(a.length===0||a.length>Pe.maxWordLength)&&!(a===t||ip.test(a))&&!(sp(a)<rp||n.includes(a))&&(n.push(a),n.length===Jn))break}return n},To=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},As=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&To(e,t-1)?t-2:t-1;return Zd.test(String.fromCodePoint(r))&&!ep.has(e.codePointAt(n))},cp=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!As(e,i);)i--;i===a&&(i=a+r,To(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}},Ao=(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 s of e.split(Ds)){let c=o;if(o+=s.length,i+s.length<=t){i===0&&(a=c),i+=s.length;continue}if(l(),Qd.test(s))continue;if(s.length<=t){a=c,i=s.length;continue}let d=cp(s,c,t);n+=d.forcedCuts,r.push(d.pieces)}return l(),{chunks:r,forcedCuts:n}},Eo=(e,t)=>{let r=Ao(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>Do(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},up=(e,t)=>{let r=0;for(let n of e.matchAll(bs))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},dp=(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},Es=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],s=[];for(let c of a){let d=e.slice(c.start,c.end),u=dp((0,ge.toMappedFormsInto)(d,ge.DEFAULT_NORMALIZE_OPTIONS,new ge.InteriorPairs(0)),d),[h,m]=(0,ge.trimmedRange)(u.text);i+=u.text.slice(h,m);for(let y=h;y<m;y++)l.push(c.start+u.start[y]),s.push(c.start+u.end[y])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let c=0;c<l.length;c++)n.push(l[c]),o.push(s[c])}}return{text:r,start:n,end:o}},un=(e,t=bo)=>{let r=[],n=0;return up(cn(e),o=>{let a=Eo(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(ln),forcedCuts:n}},ws=e=>e.filter(t=>t.length>0).join(ln),wo=(e,t)=>{let r=null;return{advance:n=>{if(r!==null)return 0;e.units=ce("search text steps: units",n,1);let o=t.next();return o.done===!0&&(r={result:o.value}),n-e.units},done:()=>r!==null,result:()=>{if(r===null)throw new Error("[daily-report] search text: the steps are not done (advance until done() is true)");return r.result}}},fs=4096;function*pp(e,t){let r=[],n=new Uint32Array(e.length),o=0,a=!1;for(let i=0;i<e.length;){for(;t.units===0;)yield;let l=Math.min(e.length,i+t.units);t.units-=l-i;let s=o,c=new Uint16Array(l-i);for(let d=i;d<l;d++){let u=e.charCodeAt(d);gs.has(u)||(c[o-s]=u,n[o++]=d)}if(o-s===l-i)a&&r.push(e.slice(i,l));else{a||r.push(e.slice(0,i)),a=!0;for(let d=s;d<o;d+=fs)r.push(Reflect.apply(String.fromCharCode,null,c.subarray(d-s,Math.min(o,d+fs)-s)))}i=l}return a?{text:r.join(""),rawIndex:n.subarray(0,o)}:{text:e,rawIndex:null}}var Is=e=>{let t={units:0};return wo(t,pp(e,t))};function*mp(e,t,r){let n=0;for(let o=0;o<e.length;){for(;r.units===0;)yield;let a=Math.min(e.length,o+r.units);r.units-=a-o;let i=a;for(let l of e.slice(o,Math.min(e.length,a+1)).matchAll(bs)){let s=o+l.index;if(s>=a)break;t(e.slice(n,s),n),n=s+l[0].length,i=Math.max(i,n)}o=i}t(e.slice(n),n)}var _s=(e,t)=>{let r={units:0};return wo(r,mp(e,t,r))};function*Rs(e,t,r,n,o){let a=[],i=0,l=t;for(;r-l>n;){let s=l+n;for(;s>l;s--){for(;o.units===0;)yield;if(o.units-=1,As(e,s))break}s===l&&(s=l+n,To(e,s)&&s--,i++),a.push({start:l,end:s}),l=s}return a.push({start:l,end:r}),{pieces:a,forcedCuts:i}}function*yp(e,t,r){if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let n=[],o=0,a=0,i=0,l=0,s=0,c=!1,d=(m,y,R)=>{let p=y-m;return i+p<=t?(i===0&&(a=m),i+=p,!1):(i>0&&n.push([{start:a,end:a+i}]),i=0,R?!1:p<=t?(a=m,i=p,!1):!0)},u=m=>{c&&(d(l,s,!0),l=s),c=!1,s=m},h=m=>{let y=-1;return!c&&s>l&&(d(l,s,!1)&&(y=l),l=s),c=!0,s=m,y};for(let m=0;m<e.length;){for(;r.units===0;)yield;let y=Math.min(e.length,m+r.units);r.units-=y-m;let R=m;for(let p of e.slice(m,y).matchAll(Xd)){let f=m+p.index;f>R&&u(f),R=f+p[0].length;let D=h(R);if(D>=0){let w=yield*Rs(e,D,f,t,r);o+=w.forcedCuts,n.push(w.pieces)}}y>R&&u(y),m=y}if(d(l,s,c)){let m=yield*Rs(e,l,s,t,r);o+=m.forcedCuts,n.push(m.pieces)}return i>0&&n.push([{start:a,end:a+i}]),{chunks:n,forcedCuts:o}}var xs=(e,t)=>{let r={units:0};return wo(r,yp(e,t,r))},hp=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
6
+ `)},fp=[`\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`],Rp=["","\u30A2","\u4F50"," "],Sp=()=>JSON.stringify(fp.map(e=>un(e,8))),gp=e=>`dr-search-v${Kd};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var bp=async()=>{let e=(0,Ss.createHash)("sha256");e.update(JSON.stringify(ge.DEFAULT_NORMALIZE_OPTIONS));for(let t of Rp)await(0,go.setImmediate)(),e.update("\0"),e.update(Do(hp(t)));return await(0,go.setImmediate)(),e.update("\0"),e.update(Sp()),gp(e.digest("hex"))},Dp=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},Io=Dp(bp);var Tp=/^-+/u,Ap=/\s+/u,Cs=e=>{let t=Tp.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Ep=(e,t)=>{let r=[...Cs(e).map(n=>({text:n,tier:Bt.word})),...t.flatMap(n=>Cs(n).map(o=>({text:o,tier:Bt.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},wp=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),dn=(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,Ms.parseQuerySets)(cn(e),t).sets){let i=[],l=new Set;for(let c of a.split(Ap)){let d=sn(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>Pe.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=Ep(d,Ts(c)),h=wp(u);l.has(h)||(l.add(h),i.push({alternatives:u}))}if(i.length>Pe.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let s=JSON.stringify([...l].sort());n.has(s)||(n.add(s),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}}},Ir=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var sR=Object.freeze({sourceTypes:null,authors:null,customers:null}),Ip=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,ks=(e,t,r)=>{if(Fa(e)&&Ip(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=dn(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var Ps=6e4,_p=1,xp=3200,vs=2e3,Cp=Object.freeze({search:xp,reports:vs,"search-marks":vs,"search-facets":null}),Mp=(e,t)=>{let r=Cp[e];return r===null?null:{max:t,maxPerOwner:jr,maxWaitMs:r}},_r=e=>{let{concurrency:t,route:r,logger:n}=e,o=Dt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:Ps,logger:n,windowFields:()=>`route=${r}`}),a=dt({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:Mp(r,t)}),i=Object.freeze({status:429,message:po,headers:Object.freeze({"Retry-After":String(_p)})}),l=ve({windowMs:Ps,tallies:["busy"],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`busy_suppressed count=${c} since=${d} route=${r} concurrency=${t}`)}});return{admit:async(s,c)=>{let d=o.spend(s,r);if(d!==null)return{refusal:d};let u=await a.acquire(s,c);return u!==null?{release:u}:(o.refund(s,1),c.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};var zs=require("@aiquants/sse"),vt=require("@aiquants/sse/server");var rr=(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=Br.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});return{entry:Object.freeze({id:e.id,message:a}),json:n}},Ls=new WeakMap,Ns=(e,t,r)=>{let n=Ls.get(e);n===void 0&&(n=new Map,Ls.set(e,n));let o=n.get(t);if(o!==void 0)return o;let a=r();return n.set(t,a),a},_o=e=>e,kp=e=>{switch(e.type){case"connected":case"report-delete":return _o(e);case"status-update":case"comment-add":case"comment-delete":{let{recipientRawUserId:t,...r}=e;return _o(r)}}},Pp=(e,t,r)=>{let{recipientRawUserId:n,actorRawUserId:o,...a}=e,i=r?{...a.report,externalComments:[],postedComments:[]}:a.report;return _o({...a,report:i,viewerIsActor:t})},Os=(e,t,r)=>{let{parsed:n}=e;if(n.type!=="report-create"&&n.type!=="report-update"&&n.type!=="report-publish")return Ns(e,"every-viewer",()=>JSON.stringify(kp(n)));let o=n.actorRawUserId===t;return Ns(e,`${o?"actor":"observer"}${r?"-comments-redacted":""}`,()=>JSON.stringify(Pp(n,o,r)))};var Us=require("@aiquants/sse"),Bs=require("@aiquants/sse/shared-source");var Pt="daily-report:ids:",xo=(e,t)=>`${e}st:${t}`,Co=e=>`${Pt}user:${e}:`,Hs=(e,t)=>xo(Co(e),t),nr=e=>`daily-report:date:${e}:user:`,or=(e,t)=>`${nr(e)}${t}:`,Fs=(e,t,r)=>xo(or(e,t),r),Ze=e=>`daily-report:detail:${e}:user:`,Mo=(e,t)=>`${Ze(e)}${t}:`,$s=(e,t,r)=>xo(Mo(e,t),r);var mt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},vp=5e3,Lp=Wr,ar=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=Ee(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:Ct}_createSource(){return(0,Bs.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Us.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:vp,COUNT:Lp});if(i)for(let l of i)for(let s of l.messages){a=s.id;let{entry:c,json:d}=rr(s,this._logger);this._invalidateCaches(d),r.next(c)}}}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(Pt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ze(n))}};var Np=6e4,xr="Report visibility is unavailable",Vs=["initial","refresh"],qs=Object.freeze({ok:!1}),Op=e=>e===null?"null":Array.isArray(e)?"array":typeof e,js=(e,t)=>{let r=ve({windowMs:Np,tallies:Vs,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{t.error(`visibility_unavailable_suppressed count=${o} since=${a} cause=${n} reasons=${Vs.map(l=>`${l}:${i[l]}`).join(",")}`)}});return async(n,o)=>{let a;try{a=await e(n,{reason:o})}catch(l){return r.record("port_failure",o,()=>t.error(`visibility unavailable cause=port_failure reason=${o}`,l)),qs}let i=ms(a);return i===null?(r.record("port_contract",o,()=>t.error(`visibility unavailable cause=port_contract reason=${o} answer=${Op(a)}`)),qs):{ok:!0,scope:i}}},Ws=(e,t,r)=>{let n=e(t,r,{error:{message:xr}},503);for(let[o,a]of Object.entries(_e(503)))n.headers.set(o,a);return n};var Gs=Object.freeze({...Dr,route:"sse",frameworkDataRefusal:zr}),Ys=864e5,Hp={baseMs:2e3,jitterMs:8e3},ko=6e4,mn=Wr,Ks=JSON.stringify({type:"connected"}),Fp=e=>{let t=e.length,r=e["entries-added"];if(typeof t!="number"||!Number.isSafeInteger(t)||t<0||typeof r!="number"||!Number.isSafeInteger(r)||r<t)throw new Error(`XINFO STREAM must report length and entries-added as safe integers with entries-added >= length >= 0 (Redis 7.0 or later); got length=${String(t)} entries-added=${String(r)}`);return r-t},$p=(e,t,r)=>{if(t===null&&r===null)return!0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Me(t,e.report.sourceType);case"comment-add":case"comment-delete":return Me(r,e.sourceType);case"report-delete":return Me(t,e.sourceType)}},Up=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Me(t,e.report.sourceType),Bp=(e,t)=>{e.writeEvent({event:null,id:t,data:Ks})},Vp=(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||!$p(o,r.visibleSet,r.commentableSet)){Bp(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Os(n,r.internalUserId,Up(o,r.commentableSet))})},Js=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:s}=e,c=async(d,u)=>{let{request:h,internalUserId:m,cursor:y}=u,R=u.initialScope.visible,p=u.initialScope.commentable,f=0,D=setInterval(()=>{let x=++f;n(h,"refresh").then(j=>{if(x===f){if(!j.ok){d.close();return}R=j.scope.visible,p=j.scope.commentable}})},ko);d.onClose(()=>clearInterval(D));let w=y===null?Ct:y,S=y!==null&&o!==void 0,g=[],M=null,T=x=>{mt(x.id,w)||(w=x.id,Vp(d,x,{internalUserId:m,visibleSet:R,commentableSet:p}))},C=async(x,j)=>{let[X]=await x.xRange(i,"-","+",{COUNT:1});return X!==void 0&&!mt(X.id,j)},H=async(x,j)=>{let[X]=await x.xRange(i,"-","+",{COUNT:1});if(X===void 0)return!0;let J;if(j===Ct){if(Fp(await x.xInfoStream(i))>0)return!1;J=X.id}else{if(!mt(X.id,j))return!1;J=j}for(;;){let $=await x.xRange(i,J,"+",{COUNT:mn}),_=$[0];if(_!==void 0&&_.id!==J&&await C(x,J))return!1;for(let Y of $){if(M!==null&&mt(M,Y.id))return!0;mt(Y.id,w)||T(rr(Y,s).entry)}let B=$.at(-1);if($.length<mn||B===void 0||d.isClosed())return!0;J=B.id}},I=a.subscribe(x=>{if(!S){T(x);return}mt(x.id,w)||(M===null&&(M=x.id),g.push(x))},x=>{s.error(`[SSE:${m}] Fan-Out reader error:`,x),d.close()});if(d.onClose(I),y===null){await a.ready();try{let x=await o?.getClient();if(x){let j=await x.xRevRange(i,"+","-",{COUNT:1});j.length>0&&!mt(j[0].id,w)&&(w=j[0].id)}}catch{}}if(d.writeEvent({event:null,id:w===Ct?null:w,data:Ks}),(0,vt.startSseHeartbeat)(d,{intervalMs:Sa,retry:Hp,runtime:zs.systemSseRuntime}),y===null||o===void 0)return;await a.ready();let L=await o.getClient();if(L===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await H(L,y)){d.writeRetry(Ys),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}S=!1;for(let x of g.splice(0))T(x)};return async({request:d,params:u})=>{let h,m=()=>{let R=new Headers;h!==void 0&&R.append("Set-Cookie",h);for(let[p,f]of Object.entries(ut))R.set(p,f);return R},y=R=>(0,vt.terminalStreamResponse)(R,{data:"",retryMs:Ys,headers:m()});try{let R=await t(d,{failureRedirect:null});h=R.cookie;let{user:p}=R;if(!p)return y("auth-required");let f=await r.getUserIdByExternalId(p.id);if(!f)return y("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:m()});let D=(0,vt.readLastEventId)(d,ga);if(D!==null&&!ba(D))return s.warn(`[SSE:${f}] malformed resume cursor; asking the client to resync`),y("resync-required");let w=nn(d),S=await l.admit(f,"sse",w);if(S===null){let M=m();for(let[T,C]of Object.entries(_e(503)))M.set(T,C);return new Response("Too many streams",{status:503,headers:M})}let g=!1;try{let M=await n(d,"initial");if(!M.ok){let C=m();for(let[H,I]of Object.entries(_e(503)))C.set(H,I);return new Response(xr,{status:503,headers:C})}let T=M.scope;return(0,vt.createSseResponse)({requestSignal:w,headers:m(),onError:(C,H)=>s.error(`[SSE:${f}] ${H} failed:`,C),produce:C=>(g=!0,C.onClose(S),c(C,{request:d,internalUserId:f,cursor:D,initialScope:T}))})}finally{g||S()}}catch(R){if(R instanceof Response)throw R;let p=R instanceof Error?R:new Error(String(R));return s.error(`500 sse name=${p.name} message=${p.message}`),new Response("Internal Server Error",{status:500,headers:m()})}}};var Qs=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...ut});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},qp=Object.freeze({...Dr,route:"api",frameworkDataRefusal:({params:e})=>to(e.endpoint)&&Vt[e.endpoint].body==="stream"?zr():null}),jp=Object.freeze({...Dr,route:"action"}),Wp=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),nl=6e4,ol=5,Yp=ol*Math.ceil(nl/500),zp=2,Gp=6,Kp=6e4,Jp=ol*zp*Gp,Qp=2,Xp=10,Zp=2,em=10,Xs=(e,t)=>Math.max(e,jr)*t,al=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},tm=Object.freeze({etag:(e,t,r)=>ei(e,t,r,200),"no-store":(e,t,r)=>io(t,r,200)}),rm=e=>so(e.body==="json"?tm[e.cache]:null),Zs=so(null),el=(e,t,r,n)=>al(e(t,r,{error:{message:n.message}},n.status),n.headers),tl=(e,t,r)=>al(e(t,r,null,503),_e(503));function yn(e){tn(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:ce("service.titleMaxLength",r.titleMaxLength,1)},{loginRedirectPath:s}=e;if(typeof s!="string"||s.trim()==="")throw Q("loginRedirectPath","the non-blank path of the host's sign-in route",s);let c=Ee(e.logger,3,"API"),d=Ee(e.logger,3,"Visibility"),u=js(ur("resolveVisibleSourceTypes",e.resolveVisibleSourceTypes),d),h=Ee(e.logger,1,"SSE"),m=Ee(e.logger,1,"Attachment"),y=Ee(e.logger,2,"Isolation"),R=Ee(e.logger,2,"Action"),p=Ee(e.logger,2,"Search"),f=Ee(e.logger,2,"Refresh"),D=Ee(e.logger,2,"Streams"),w=Ee(e.logger,2,"Reads"),S=Dt({reason:"refresh_rate_limit",limitPerWindow:Jp,windowMs:Kp,logger:f,windowFields:()=>"route=api"}),g=ts(D),M=Xi(w),T=async(b,O,N,v,F,z)=>{let ee=await r.getUserIdByExternalId(O.id);try{return await z(ee===null?void 0:M.admissionFor(ee,b,N.signal))}catch(G){if(G instanceof rt)return rn(F,N,v);throw G}},C=(b,O,N,v,F)=>{let z=S.spend(O.id,`endpoint=${b}`);return z===null?null:el(F,N,v,z)},H=async({request:b})=>{let{user:O,cookie:N}=await t(b,{failureRedirect:s}),v=new Headers;N&&v.append("Set-Cookie",N);let F=await r.getUserIdByExternalId(O.id),z=F?n(F):null;return{data:{user:O,userId:z},headers:v}},I=b=>{let{limiter:O}=b;return async(N,v,F,z,ee,G)=>{if(O===null)return G(F,v,{error:{message:"Unknown endpoint"}},404);let k=b.parse(N);if(!k.ok)return G(F,v,k.invalid,400);let P=await r.getUserIdByExternalId(z.id);if(!P)return G(F,v,b.emptyAnswer(k.parsed),200);let{signal:E}=F,U=await O.admit(P,E);if("refusal"in U)return E.aborted?tl(G,F,v):el(G,F,v,U.refusal);try{E.throwIfAborted();let W=await b.read(k.parsed,{userId:P,user:z,scope:ee},E);return E.throwIfAborted(),G(F,v,W,200)}catch(W){if(E.aborted&&W===E.reason)return tl(G,F,v);throw W}finally{U.release()}}},L=r.searchLimits===null?null:_r({...r.searchLimits,route:de.search,logger:p}),x=r.searchLimits===null?null:_r({concurrency:Xs(r.searchLimits.concurrency,Qp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Xp,route:de.reports,logger:p}),j=r.searchLimits===null?null:_r({concurrency:Xs(r.searchLimits.concurrency,Zp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*em,route:de.searchMarks,logger:p}),X=r.searchLimits===null?null:_r({...r.searchLimits,route:de.searchFacets,logger:p}),J={[de.businessDate]:async(b,O,N,v,F,z)=>{let ee=b.searchParams.get(Ae.businessDate),G=ee===null?null:Kt(ee);if(G===null)return z(N,O,{error:{message:"Invalid business date"}},400);let k=br(b.searchParams.get(Ae.forceRefresh));if(k===null)return z(N,O,{error:{message:"Invalid forceRefresh"}},400);let P=k?C(de.businessDate,v,N,O,z):null;return P!==null?P:T(de.businessDate,v,N,O,z,async E=>{let U=await r.getDailyReportsByBusinessDateByExternalId(F,G,v.id,{forceRefresh:k,admission:E});return z(N,O,{businessDate:G,reports:U},200)})},[de.idsStream]:cs({service:r,logger:c,streamSlots:g,missGate:M,refuseForcedRead:(b,O,N,v)=>C(de.idsStream,b,O,N,v)}),[de.report]:async(b,O,N,v,F,z)=>{let ee=nt(b.searchParams.get(Ae.reportHubId));if(ee===null)return z(N,O,{error:{message:"Invalid reportHubId"}},400);let G=br(b.searchParams.get(Ae.forceRefresh));if(G===null)return z(N,O,{error:{message:"Invalid forceRefresh"}},400);let k=G?C(de.report,v,N,O,z):null;return k!==null?k:T(de.report,v,N,O,z,async P=>{let E=await r.getDailyReportDetailByIdByExternalId(F,ee,v.id,{snapshot:!0,forceRefresh:G,admission:P});return E?z(N,O,{report:E},200):z(N,O,{error:{message:"Report not found"}},404)})},[de.search]:I({limiter:L,parse:b=>{let O=b.searchParams.get(Ae.searchQuery),N=Zn(b.searchParams.get(Ae.searchCombine));if(O===null||N===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let v=Ua(b.searchParams,r.searchFilterSourceTypes);if(!v.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:v.reason}}};let F=ks(O,N,v.filters);if(!F.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:F.reason}}};let{criteria:z}=F;return{ok:!0,parsed:{criteria:z,words:z.plan===null?[]:Ir(z.plan)}}},emptyAnswer:({words:b})=>Qn([],b),read:async({criteria:b,words:O},{userId:N,scope:v})=>Qn(await r.searchDailyReports(v,N,b),O)}),[de.reports]:I({limiter:x,parse:b=>{let O=eo(b.searchParams.get(Ae.reportIds));return O===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:O}},emptyAnswer:b=>({outcomes:b.map(gr)}),read:async(b,{user:O,scope:N},v)=>({outcomes:await r.getDailyReportDetailsByIdsByExternalId(N,b,O.id,{signal:v})})}),[de.searchMarks]:I({limiter:j,parse:b=>{let O=b.searchParams.get(Ae.searchQuery),N=Zn(b.searchParams.get(Ae.searchCombine));if(O===null||N===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let v=dn(O,N);if(!v.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:v.reason}}};let F=eo(b.searchParams.get(Ae.reportIds));return F===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:v.plan,ids:F}}},emptyAnswer:({plan:b})=>({wordsDigest:qr(Ir(b)),reports:[],deferred:[]}),read:({plan:b,ids:O},{userId:N,scope:v},F)=>r.markDailyReportSearchHits(v,N,b,O,{signal:F})}),[de.searchFacets]:I({limiter:X,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(b,{userId:O,scope:N})=>r.listDailyReportSearchFacets(N,O)})},$=async({request:b,params:O})=>{let{user:N,cookie:v}=await t(b,{failureRedirect:null}),F=v??null;if(!N)return Zs(b,F,{error:{message:"Unauthorized"}},401);let z=O.endpoint;if(!to(z))return Zs(b,F,{error:{message:"Unknown endpoint"}},404);let ee=Vt[z],G=rm(ee),k=Ja[ee.body];if(!k.includes(b.method)){let E=G(b,F,{error:{message:"Method not allowed"}},405);return E.headers.set("Allow",k.join(", ")),E}let P=ue();try{let E=new URL(b.url),U=await u(b,"initial"),W=U.ok?await J[z](E,F,b,N,U.scope,G):Ws(G,b,F);return ee.body==="json"&&c.debug(W.headers.has("ETag")?`${W.status} endpoint=${z} etag_match=${W.status===304}`:`${W.status} endpoint=${z}`),W}catch(E){let U=ue()-P,W=E instanceof Error?E:new Error(String(E));return c.error(`500 endpoint=${z} elapsed=${U}ms name=${W.name} code=${"code"in W?W.code:"N/A"} message=${W.message}`,W),G(b,F,{error:{message:"Internal Server Error"}},500)}},_=Ka(R),B=Dt({reason:"rate_limit",limitPerWindow:Yp,windowMs:nl,logger:R,windowFields:()=>"route=action"}),Y=async(b,O,N,v,F)=>{let{clientTempId:z}=b;if(b.intent==="create")try{let E=await r.createDailyReport(N,O,b.businessDate,z);return F(b,E.reportHubId,{report:E})}catch(E){if(E instanceof Error&&E.message==="Forbidden")return v({error:"Creating reports is restricted"},{status:403});throw E}let{reportHubId:ee,businessDate:G}=b,k=async(E,U)=>{try{let W=await U();return F(E,ee,{updatedStatus:{isStarred:W.isStarred,isRead:W.isRead,readContentDigest:W.readContentDigest},operationTimestamp:E.operationTimestamp})}catch(W){if(W instanceof Error&&W.message==="Not Found")return v({error:"Report not found"},{status:404});throw W}},P=E=>E instanceof Error?E.message==="Forbidden"?v({error:"Reports from this source are read-only"},{status:403}):E.message==="Unauthorized"?v({error:"Unauthorized"},{status:403}):E.message==="Not Found"?v({error:"Report not found"},{status:404}):null:null;switch(b.intent){case"update":try{return await r.updateDailyReport(N,ee,O,b.changes,z),F(b,ee,{})}catch(E){let U=P(E);if(U===null)throw E;return U}case"publish":try{let E=await r.publishDailyReport(N,ee,O,z);return F(b,ee,{report:E})}catch(E){let U=P(E);if(U===null)throw E;return U}case"delete":try{return await r.deleteDailyReport(N,ee,O,z),F(b,ee,{})}catch(E){let U=P(E);if(U===null)throw E;return U}case"toggleStar":return await k(b,()=>r.setStarStatus(N,O,ee,G,b.value,z));case"toggleRead":return await k(b,()=>r.setReadStatus(N,O,ee,G,b.value?{isRead:!0,contentDigest:b.contentDigest}:{isRead:!1},z));case"addComment":try{let E=await r.addComment(N,O,ee,b.content,G,z);return F(b,ee,{newComment:E})}catch(E){if(E instanceof Error){if(E.message==="Not Found")return v({error:"Report not found"},{status:404});if(E.message.startsWith("Comments are restricted"))return v({error:"Comments are restricted for this report"},{status:403})}throw E}case"deleteComment":try{return await r.deleteComment(N,O,ee,b.commentId,G,z),F(b,ee,{deletedCommentId:b.commentId})}catch(E){if(E instanceof Error){if(E.message==="Unauthorized")return v({error:"Unauthorized"},{status:403});if(E.message==="Not Found")return v({error:"Comment not found"},{status:404})}throw E}}},pe=async({request:b,params:O})=>{let{user:N,cookie:v}=await t(b,{failureRedirect:null}),F=(G,k)=>Qs(G,{...k,setCookie:v}),z=(G,k,P)=>Qs(Wp(G,k,P),{setCookie:v});if(!N)return F({error:"Unauthorized"},{status:401});let ee=ue();try{if(O.endpoint!==de.action)return F({error:"Unknown endpoint"},{status:404});let G=B.spend(N.id,"action");if(G!==null)return F({error:G.message},{status:G.status,headers:G.headers});let k=await Ga(b,l);if("refusal"in k){let{refusal:W}=k;return W.status===413&&_(W.measuredBy),F({error:W.error},{status:W.status})}let{command:P}=k;if(P.intent==="clearCache"&&!e.enableDevCacheClear)return F({error:"Invalid intent"},{status:400});let E=await u(b,"initial");if(!E.ok)return F({error:xr},{status:503,headers:{..._e(503),"Cache-Control":"no-store"}});let U=await r.getUserIdByExternalId(N.id);return U?P.intent==="clearCache"?(await r.clearCache(),F({status:"OK",intent:"clearCache"})):await Y(P,U,E.scope,F,z):F({error:"User not found"},{status:404})}catch(G){if(G instanceof Response)throw G;let k=ue()-ee,P=G instanceof Error?G:new Error(String(G));return c.error(`500 action elapsed=${k}ms name=${P.name} message=${P.message}`,P),F({error:"Internal Server Error"},{status:500})}},ie=Js({authenticate:t,service:r,resolveViewerScope:u,redis:o,sseReader:a,streamKey:i,streamSlots:g,logger:h}),me=zi({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:u,logger:m}),De=ai(y),Z=(b,O)=>async N=>{let v=oi(N.request)?b.frameworkDataRefusal(N):null;if(v!==null)throw v;let F=(0,rl.crossOriginRefusal)(N.request,b);return F===void 0?O(N):(De(b.route,F,N.request),b.crossSiteRejection())};return{index:{loader:H},api:{loader:Z(qp,$),action:Z(jp,pe)},sse:{loader:Z(Gs,ie)},attachment:{loader:Z(Yi,me)}}}var sr=require("@aiquants/mssql"),we=require("drizzle-orm");var nm=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],om=["document","comment"],am=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],im=["hubId","ordinal","authorUserId","commentText"],Po=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},il=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw kn(e,n,r)},sl=(e,t,r)=>{if(typeof t!="object"||t===null)throw Q(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw Q(`${e}.${o}`,"a column",n[o])},ll=(e,t)=>{if(!Po(e))throw Q("search","a plain object",e);il("search key",e,nm);let{tables:r}=e;if(!Po(r))throw Q("search.tables","a plain object with document and comment",r);il("search.tables key",r,om),sl("search.tables.document",r.document,am),sl("search.tables.comment",r.comment,im);let n=new Map;if(e.externalSourceTexts!==void 0){if(!Po(e.externalSourceTexts))throw Q("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw kn("search.externalSourceTexts key",o,t);if(typeof a!="function")throw Q(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:ce("search.concurrency",e.concurrency,1),rateLimitPerMinute:ce("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var Lt=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},jt=(e,t)=>{let r=typeof e=="string"?nt(e):typeof e=="number"&&ct(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 V=require("drizzle-orm");var Et=require("drizzle-orm"),cl=e=>{if(e.length===0)throw new Error("[daily-report] draft rule: draftLabelNames must hold at least one name (a rule without names would show every draft to every viewer)");return Et.sql.join(e.map(t=>Et.sql`${t}`),Et.sql`, `)},hn=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return Et.sql`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${cl(t)}))`},ul=(e,t)=>{let{hubLabel:r,label:n}=e;return Et.sql`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${cl(t)}))`},fn=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?Et.sql`${o.userId} = ${t} OR ${o.userId} IS NULL`:Et.sql`${o.userId} = ${t}`;return Et.sql`(${a} OR NOT ${hn(e,r)})`};var sm=/[[%_]/gu,lm=e=>e.replace(sm,t=>`[${t}]`),dl=e=>`%${lm(e)}%`;var at=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),Yt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),Mr=Object.freeze({value:"value"}),Le=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),q=e=>V.sql`${V.sql.identifier(e.name)}`,Cr=e=>V.sql.join(e.map(t=>V.sql`${t}`),V.sql`, `),pl=(e,t)=>V.sql`SELECT ${q(e.id)} AS ${V.sql.identifier(Le.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${Cr(t)}) ORDER BY ${e.id}`,cm=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>dl(u.text)),l=V.sql.join(i.map(u=>V.sql`${o.searchText} LIKE ${u}`),V.sql` OR `),s=V.sql.join(i.map(u=>V.sql`${a.commentText} LIKE ${u}`),V.sql` OR `),c=wr(n.sourceType,r.scope.commentable),d=c===void 0?V.sql``:V.sql` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return V.sql`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},ml=(e,t,r)=>V.sql`(${V.sql.join(t.words.map(n=>cm(e,n,r)),V.sql` AND `)})`,vo=(e,t,r,n)=>{let{hub:o}=e,a=[V.sql`${o.deletedAt} IS NULL`,fn(e,t.userId,r,"author")],i=wr(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(V.sql`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},um=(e,t)=>{let{hub:r}=e,{document:n}=e.search,o=[];if(t.sourceTypes!==null){if(t.sourceTypes.size===0)throw new Error("[daily-report] search: a source-type filter must hold at least one source type");o.push(V.sql`LOWER(${r.sourceType}) IN (${Cr([...t.sourceTypes])})`)}return t.authors!==null&&o.push(V.sql`${n.authorName} IN (${Cr(t.authors)})`),t.customers!==null&&o.push(V.sql`${n.customerName} IN (${Cr(t.customers)})`),o},yl=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...vo(e,r,n,o),...um(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?V.sql` AND `:V.sql` OR `;s.push(V.sql`(${V.sql.join(l.sets.map(d=>ml(e,d,r)),c)})`)}return V.sql`SELECT ${q(a.id)} AS ${V.sql.identifier(at.reportHubId)}, CONVERT(char(10), ${q(a.businessDate)}, 23) AS ${V.sql.identifier(at.businessDate)}, ${q(a.sourceType)} AS ${V.sql.identifier(at.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${V.sql.join(s,V.sql` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},hl=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=V.sql.join(t.sets.map((s,c)=>V.sql`(CASE WHEN ${ml(e,s,r)} THEN ${2**c} ELSE 0 END)`),V.sql` + `);return V.sql`SELECT ${q(a.id)} AS ${V.sql.identifier(Yt.reportHubId)}, ${l} AS ${V.sql.identifier(Yt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${V.sql.join(vo(e,r,n,o),V.sql` AND `)}`},fl=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...vo(e,r,n),V.sql`${i} IS NOT NULL`];return V.sql`SELECT ${i} AS ${V.sql.identifier(Mr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${V.sql.join(l,V.sql` AND `)} GROUP BY ${i} ORDER BY ${i}`},Rl=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(s=>({[n.hubId.name]:s.hubId,[n.searchText.name]:s.searchText,[n.sourceDigest.name]:s.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:s.authorName,[n.customerName.name]:s.customerName}))),i=JSON.stringify(t.flatMap(s=>s.comments.map(c=>({[o.hubId.name]:s.hubId,[o.ordinal.name]:c.ordinal,[o.authorUserId.name]:c.authorUserId,[o.commentText.name]:c.commentText})))),l=JSON.stringify(t.map(s=>s.hubId));return V.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), ${q(n.authorName)} nvarchar(max), ${q(n.customerName)} nvarchar(max))) AS s ON t.${q(n.hubId)} = s.${q(n.hubId)}
8
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.authorName)} = s.${q(n.authorName)}, t.${q(n.customerName)} = s.${q(n.customerName)}, t.${q(n.indexedAt)} = SYSUTCDATETIME()
9
9
  WHEN NOT MATCHED THEN INSERT (${q(n.hubId)}, ${q(n.searchText)}, ${q(n.sourceDigest)}, ${q(n.normalizerVersion)}, ${q(n.authorName)}, ${q(n.customerName)}) VALUES (s.${q(n.hubId)}, s.${q(n.searchText)}, CONVERT(binary(32), s.${q(n.sourceDigest)}, 2), s.${q(n.normalizerVersion)}, s.${q(n.authorName)}, s.${q(n.customerName)});
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));`},dl=(e,t)=>V.sql`SELECT ${q(e.hubId)} AS ${V.sql.identifier(Le.hubId)}, LOWER(CONVERT(char(64), ${q(e.sourceDigest)}, 2)) AS ${V.sql.identifier(Le.sourceDigest)}, ${q(e.normalizerVersion)} AS ${V.sql.identifier(Le.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${_r(t)})`,pl=(e,t,r)=>V.sql`SELECT TOP (${r}) ${q(e.id)} AS ${V.sql.identifier(Le.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var ml=e=>({search:async(t,r)=>Fe(r.scope.visible)?[]:kt(await t.execute(sl(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=qt(o[ot.sourceType],ot.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${ot.sourceType} is null`);return{reportHubId:Vt(o[ot.reportHubId],ot.reportHubId),businessDate:qt(o[ot.businessDate],ot.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Fe(r.scope.visible))return new Map;let n=kt(await t.execute(ll(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[jt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${jt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(Vt(i[jt.reportHubId],jt.reportHubId),l)}return a},facetValues:async(t,r)=>Fe(r.scope.visible)?[]:kt(await t.execute(cl(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=qt(o[xr.value],xr.value);if(a===null)throw new Error(`[daily-report] search: column ${xr.value} is null`);return a})});var yt=require("@aiquants/mssql"),ko=require("drizzle-orm");var hl=require("crypto");var Zp=Object.freeze({authorName:"author",customerName:"customer"}),Mo=e=>e===null?null:Gn(e),yl=(e,t,r)=>{let n=Mo(r);if(n!==null&&n.length>St.maxValueLength){let o=St.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${Zp[t]} display value has ${n.length} UTF-16 units after trimming; the host must keep the author and customer display values at most ${o} UTF-16 units`)}return n},Cr=e=>e===null?"n;":`s${e.length}:${e}`,Mr="utf16le",em=e=>{let t=(0,hl.createHash)("sha256");t.update(`F${e.fields.length};`,Mr);for(let[r,n]of e.fields)t.update(Cr(r)+Cr(n),Mr);return t.update(`C${e.comments.length};`,Mr),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${Cr(r.text)}`,Mr)}),t.update(`P;${Cr(Mo(e.filterValues.authorName))}${Cr(Mo(e.filterValues.customerName))}`,Mr),t.digest("hex")},Po=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=ln(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=ln(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:Ss(r),comments:n,sourceDigest:em(e),forcedCuts:t,authorName:yl(e.hubId,"authorName",e.filterValues.authorName),customerName:yl(e.hubId,"customerName",e.filterValues.customerName)}};var fl=e=>{let t=async(s,c)=>{let d=[];for(let u of(0,yt.chunk)(c,yt.MAX_IN_LIST))for(let h of kt(await s.execute(al(e.hub,u))))d.push(Vt(h[Le.hubId],Le.hubId));return d},r=async(s,c)=>{for(let d of(0,yt.chunk)(c,yt.MAX_IN_LIST))await s.execute(ul(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of(0,yt.chunk)(c,yt.MAX_IN_LIST))for(let h of kt(await s.execute(dl(e.tables.document,u))))d.set(Vt(h[Le.hubId],Le.hubId),{sourceDigest:qt(h[Le.sourceDigest],Le.sourceDigest),normalizerVersion:qt(h[Le.normalizerVersion],Le.normalizerVersion)});return d},o=async(s,c,d)=>kt(await s.execute(pl(e.hub,c,d))).map(u=>Vt(u[Le.hubId],Le.hubId)),a=async(s,c)=>{let d=await t(s,[...new Set(c)].sort((h,p)=>h-p));if(d.length===0)return;let u=(await e.loadSources(s,d)).map(Po);u.length>0&&await r(s,u)},i=s=>e.inTransaction(async c=>{await c.execute(ko.sql`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),h=(await e.loadSources(c,d)).map(Po),p=h.filter(y=>{let f=u.get(y.hubId);return f===void 0||f.sourceDigest!==y.sourceDigest||f.normalizerVersion!==e.normalizerVersion});return p.length>0&&await r(c,p),await c.execute(ko.sql`SET DEADLOCK_PRIORITY NORMAL`),{scanned:h.length,written:p.length,forcedCuts:h.reduce((y,f)=>y+f.forcedCuts,0)}});return{writeHubs:a,reconcile:async(s,c)=>{let{batchSize:d,hubIds:u,signal:h,onProgress:p}=c;le("reconcileSearchIndex: batchSize",d,1,yt.MAX_IN_LIST);let y=ce(),f=u===void 0?null:(0,yt.chunk)([...new Set(u)].sort((R,A)=>R-A),d),m={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let R=0;;R++){h?.throwIfAborted();let A=f===null?await o(s,m.lastHubId===null?0:m.lastHubId,d):f[R];if(A===void 0||A.length===0)break;let w=await i(A);m={scanned:m.scanned+w.scanned,written:m.written+w.written,skipped:m.skipped+w.scanned-w.written,forcedCuts:m.forcedCuts+w.forcedCuts,lastHubId:A[A.length-1]},p?.(m)}return{...m,elapsedMs:ce()-y}}}};var gl=require("@aiquants/fuzzy-search/normalize");var Lo=255,hn=Object.values($t).sort((e,t)=>e-t),tm=new Intl.Segmenter("und",{granularity:"grapheme"}),be=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),ht=5e5,fn=Math.floor(ht/be.linear),rm=Math.floor(ht/be.segment),Rl=Math.floor(ht/be.sweep),bl=Math.floor(ht/be.scan),Pr=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),Dl=(e,t)=>{let r=0,n=t(),o=ht,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+ht,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=ht,a=!1}}},gS=Object.freeze({fits:()=>!0,charge:()=>{}}),Al=e=>{let t=null;return{step:()=>{if(t!==null)return!0;let r=e.next();return r.done!==!0?!1:(t={result:r.value},!0)},result:()=>{if(t===null)throw new Error("[daily-report] search marks: the walk is not done (step until it returns true)");return t.result}}};var nm=(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},om=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length;function*am(e,t,r,n){let o=!1;for(let c=t;c<r&&!o;c+=fn){let d=Math.min(r,c+fn),u=(d-c)*be.linear;n.fits(u)||(yield),o=(0,gl.holdsMultiUnitCluster)(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=tm.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(rm,s.value.segment.length);n.fits(c*be.segment)||(yield);let d=0;for(;!s.done&&d+s.value.segment.length<=c;){let{index:u,segment:h}=s.value;a.fill(t+u,u,u+h.length),i.fill(t+u+h.length,u,u+h.length),d+=h.length,s=l.next()}n.charge(d*be.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var im=256,sm=e=>{let t=new Int32Array(e.length),r=0;for(let n=1;n<e.length;n++){for(;r>0&&e.charCodeAt(n)!==e.charCodeAt(r);)r=t[r-1];e.charCodeAt(n)===e.charCodeAt(r)&&r++,t[n]=r}return e.length-t[e.length-1]},lm=e=>{let t=new Map;for(let r of e){if(r.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let n=t.get(r.text);(n===void 0||r.tier<n)&&t.set(r.text,r.tier)}return[...t].map(([r,n])=>{let o=sm(r),a=Math.max(bl-r.length+1,r.length);if(o===r.length)return{text:r,tier:n,periodic:null,windowStarts:a};let i=r.length%o,l=r.slice(i,o)+r.slice(0,i);return{text:r,tier:n,periodic:{period:o,continuation:l.repeat(Math.ceil(im/o))},windowStarts:a}})},Rn=(e,t)=>{let{pieces:r}=e,n=r[e.lastPiece];if(n.plainStart<=t&&t<n.plainStart+n.text.length)return e.lastPiece;let o=0,a=r.length-1;for(;o<a;){let i=o+a+1>>1;r[i].plainStart<=t?o=i:a=i-1}return t>=r[o].plainStart+r[o].text.length?-1:(e.lastPiece=o,o)},Sl=(e,t,r)=>{let n=Rn(e,t);return e.pieces[n>=0?n:Rn(e,r==="start"?t-1:t+1)]},Tl=(e,t)=>{let r=Rn(e,t);if(r<0)return El(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},El=(e,t)=>{let r=Rn(e,t);if(r<0)return Tl(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},cm=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),um=Object.freeze({kind:"done"}),vo=Object.freeze({kind:"slice"}),dm=Object.freeze({kind:"clusters"}),pm=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:s,periodic:c}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(be.run))return vo;let p=Sl(e,n.closedStart,"start"),y=Sl(e,n.closedEnd-1,"end");if(p.mapped===null)return{kind:"map",piece:p};if(y.mapped===null)return{kind:"map",piece:y};if(e.isCut&&e.clusters===void 0)return dm;let f=t(e.offset+Tl(e,n.closedStart)),m=t(e.offset+El(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let R=e.clusters;R==null?a(f,m,s):a(R.clusterStarts[f-R.start],R.clusterEnds[m-1-R.start],s),o.charge(be.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(ht))return vo;let{period:p,continuation:y}=c,f=n.periodicEnd,m=Math.min(i.length,f+Math.max(bl,y.length)),R=f;for(;R+y.length<=m&&i.startsWith(y,R);)R+=y.length;let A=R+y.length>m&&m<i.length;if(!A)for(;R<i.length&&i.charCodeAt(R)===i.charCodeAt(R-p);)R++;if(o.charge((R-f)*be.scan),A){n.periodicEnd=R;continue}n.periodicEnd=-1,n.last+=Math.floor((R-n.last-l.length)/p)*p,n.from=n.last+l.length-p+1;continue}if(n.from<0){if(n.runStart<0)return um;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(ht))return vo;n.from>=n.windowEnd&&(n.windowStart=n.from,n.windowEnd=n.from+r.windowStarts,n.window=i.slice(n.from,n.windowEnd+l.length-1));let d=n.from-n.windowStart,u=n.window.indexOf(l,d);if(u<0){o.charge((n.window.length-d)*be.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*be.scan);let h=n.windowStart+u;(n.runStart<0||h>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=h),n.last=h,c===null?n.from=h+1:n.periodicEnd=h+l.length}};function*No(e,t,r){let n=Math.floor(ht/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*mm(e,t,r,n,o){if(t.length===0)return;let a=yield*No(gs(e),be.strip,n),i=[],l=[];yield*No(bs(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),be.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(be.line)||(yield),n.charge(be.line);let d=i[c],u=a.text.slice(d,l[c]),h=yield*No(Ds(u,r),be.plan,n),p=[],y="";for(let m of h.chunks){let R="",A=[];for(let w of m){let S=(w.end-w.start)*be.normalize;n.fits(S)||(yield);let g=bo(w.start===0&&w.end===u.length?u:u.slice(w.start,w.end),r).text;n.charge(S),g.length>0&&A.push({start:w.start,end:w.end,text:g,chunkStart:R.length}),R+=g}if(R.length!==0){y.length>0&&(y+=" ");for(let w of A)p.push({start:w.start,end:w.end,text:w.text,plainStart:y.length+w.chunkStart,mapped:null});y+=R}}if(y.length===0)continue;let f={offset:d,plain:y,pieces:p,isCut:!om(h,u),lastPiece:0,clusters:void 0};for(let m of t){let R=cm();for(;;){let A=pm(f,s,m,R,n,o);if(A.kind==="done")break;if(A.kind==="slice"){yield;continue}if(A.kind==="clusters"){f.clusters=yield*am(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:w}=A,S=(w.end-w.start)*be.map;n.fits(S)||(yield);let g=u.slice(w.start,w.end);w.mapped=nm(Rs(g,go(g,r)),w.text),n.charge(S)}}}}function*ym(e,t,r,n){let o=new Int32Array(hn.length),a=0,i=Lo;for(let l=0;l<=e;l+=Rl){let s=Math.min(e+1,l+Rl),c=(s-l)*be.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=Lo;for(let h=hn.length-1;h>=0;h--){let p=hn[h];o[p]+=t[p][d],o[p]>0&&(u=p)}if(u!==i){if(i!==Lo&&!n(a,d,i))return!1;a=d,i=u}}r.charge(c)}return!0}function*hm(e,t,r,n,o){let a=null;return yield*mm(e,t,r,n,(l,s,c)=>{a===null&&(a=hn.map(()=>new Int32Array(e.length+1))),a[c][l]++,a[c][s]--}),a===null?!0:yield*ym(e.length,a,n,o)}var fm=(e,t,r,n)=>{let o=lm(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return Al(function*(){return(yield*hm(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var wl=(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)},Il=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of Ia)r(Rt.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(Rt.interviewer(o,"name"),n.name),r(Rt.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(Rt.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(Rt.comment(Bn(o),"author"),n.name),r(Rt.comment(Bn(o),"content"),n.text)});for(let n of e.postedComments)r(Rt.comment(n.id,"author"),n.userName),r(Rt.comment(n.id,"content"),n.content);return t};function*Rm(e,t){let r=jn;for(let n=0;n<e.length;n+=fn){let o=Math.min(e.length,n+fn),a=(o-n)*be.linear;t.fits(a)||(yield),r=Wn(r,e,n,o),t.charge(a)}return r}var _l=async(e,t,r,n)=>{let o=0,a=0,i=async c=>{for(;!c.step();)await r(),n.startSlice();return c.result()},l=async(c,d)=>{if(!d&&a>t.maxRanges)return null;let u={};for(let{key:h,value:p}of c.fields){if(!d&&o+p.length>t.maxUnits)return null;let y=await i(Al(Rm(p,n))),f=await i(fm(p,c.alternatives,{maxLength:fo,maxRanges:t.maxFieldRanges},n));if(o+=p.length,f.dense){u[h]={fingerprint:y,dense:!0};continue}if(u[h]={fingerprint:y,ranges:f.ranges},a+=f.ranges.length/3,!d&&a>t.maxRanges)return null}return u},s=[];for(let c=0;c<e.length;c++){let d=e[c],u=await l(d,s.length===0);if(u===null)return{reports:s,deferred:e.slice(c).map(h=>h.reportHubId)};s.push({reportHubId:d.reportHubId,matchedSets:d.matchedSets,fields:u})}return{reports:s,deferred:[]}};var Ue=require("drizzle-orm");var $e=require("drizzle-orm");var Et=e=>(0,$e.getColumns)(e),Me=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),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"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},xl=e=>{let{db:t,tables:r,encodeUserId:n,settings:o,draftVisibilityTables:a}=e,{hub:i,label:l}=r,{externalSources:s,draftLabelNames:c,canonicalDraftLabelName:d}=o,u=I=>Tr(i.sourceType,I),h=(I,v)=>yn(a,I,c,v),p=$e.sql`CASE WHEN ${mn(a,c)} THEN 1 ELSE 0 END`,y=async I=>{let[v]=await t.select({id:i.id}).top(1).from(i).where((0,$e.and)((0,$e.eq)(i.id,I),mn(a,c)));return v!==void 0},f=I=>I==null||I===""?null:/^\d+$/.test(I)?n(Number(I)):I,m=()=>{let I={};for(let v of s)I[`ext_${v.sourceType}`]=Et(v.table);return I},R=I=>{let v=I;for(let C of s)v=v.leftJoin(C.table,(0,$e.and)((0,$e.eq)(i.sourceType,C.sourceType),(0,$e.eq)(i.sourceIdNum,C.idColumn)));return v},A=I=>{let{hub:v,internal:C}=I,j=v.summary,Q=[],J=null,$=null,_=null,B=null,Y=null,de=null,ae=[],pe=s.find(X=>X.sourceType===v.sourceType),De=pe?I[`ext_${pe.sourceType}`]:void 0;if(pe&&De){let X=pe.mapRow(De);X.content!==void 0&&(j=X.content),X.employeeName!==void 0&&(de=X.employeeName),X.category!==void 0&&(J=X.category),X.creationCategory!==void 0&&($=X.creationCategory),X.visitTimeFrom!==void 0&&(_=X.visitTimeFrom),X.visitTimeTo!==void 0&&(B=X.visitTimeTo),X.customerName!==void 0&&(Y=X.customerName),X.interviewers!==void 0&&(Q=X.interviewers),X.externalComments!==void 0&&(ae=X.externalComments)}else v.sourceType===We&&C&&(j=C.body);return{content:j,author:I.creatorName??f(v.createdBy)??"",employeeName:de??I.creatorName??f(v.createdBy),updatedBy:f(v.updatedBy),category:J,creationCategory:$,visitTimeFrom:_,visitTimeTo:B,customerName:Y,interviewers:Q,externalComments:ae}},w=I=>{if(I===1)return!0;if(I===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${Nt(I)}`)},S=I=>I.creationCategory!==null&&c.includes(I.creationCategory),g=(I,v)=>w(I.hasDraftLabel)?!0:S(v),M=async I=>{let[v]=await I.select({id:l.id}).top(1).from(l).where((0,$e.eq)(l.name,d)).orderBy((0,$e.asc)(l.id));return v===void 0?null:v.id},D=()=>M(t);return{visibleSourceTypeCondition:u,draftVisibleTo:h,draftLabelFlag:p,isDraftReport:y,externalSelections:m,applyExternalJoins:R,resolveHubDisplayFields:A,readCanonicalDraftLabelId:M,getDraftLabelId:D,resolveCreationCategoryDraftLabelId:I=>I.some(S)?D():Promise.resolve(null),mapHubRecord:(I,v,C,j,Q)=>{let{hub:J}=v,$=v.labels.map(Y=>({id:Y.id,name:Y.name,color:Y.color})),_=v.postedCommentRows,B=Ce(I.commentable,J.sourceType);return j!==null&&S(C)&&!$.some(Y=>Y.id===j)&&$.push({id:j,name:d,color:null}),{reportHubId:J.id,date:Me(J.businessDate,"YYYY-MM-DD"),author:C.author,userId:J.userId?n(J.userId):"",sourceType:J.sourceType,createdAt:Me(J.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:Me(J.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:C.updatedBy,employeeName:C.employeeName,category:C.category,creationCategory:C.creationCategory,visitTimeFrom:C.visitTimeFrom,visitTimeTo:C.visitTimeTo,customerName:C.customerName,interviewers:C.interviewers,subject:J.title,content:C.content,externalComments:B?C.externalComments:[],isRead:v.isRead??!1,isStarred:v.isStarred??!1,isDraft:g(v,C),labels:$,postedComments:_.filter(Y=>ss({authorUserId:Y.userId},J.sourceType,Q,I)).map(Y=>({...Y,userId:n(Y.userId),isMine:Q?Y.userId===Q:!1})),attachments:v.attachments}}}};var Cl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r})=>{let{db:n,tables:o,logger:a,settings:i}=e,{hub:l}=o,{attachmentDelivery:s}=i,c=(y,f)=>f!=null?"absent":y!=null?"present":"unknown";return{getAttachmentsByHubIds:async y=>{let f=new Map,m=o.attachment;if(y.length===0||!m||s===null)return f;let R=s.idCodec,A=s.thumbnails!==null,w=await n.select({id:m.id,hubId:m.hubId,fileName:m.fileName,fileType:m.fileType,fileSize:m.fileSize,createdAt:m.createdAt,objectCheckedAt:m.objectCheckedAt,objectMissingAt:m.objectMissingAt}).from(m).where((0,Ue.inArray)(m.hubId,y)).orderBy((0,Ue.asc)(m.createdAt),(0,Ue.asc)(m.id));for(let S of w){let g=S.fileType?String(S.fileType):null,M=S.fileSize!=null?Number(S.fileSize):null,D=c(S.objectCheckedAt,S.objectMissingAt),x={id:R.encode(Number(S.id)),fileName:String(S.fileName),fileType:g,fileSize:M,createdAt:Me(S.createdAt,"YYYY-MM-DD HH:mm:ss"),state:D,hasThumbnail:A&&D!=="absent"&&Qr({fileType:g,fileSize:M},s.maxBytes)},F=f.get(Number(S.hubId));F?F.push(x):f.set(Number(S.hubId),[x])}return f},getAttachmentForUser:async(y,f,m)=>{let R=o.attachment;return!R||Fe(y.visible)?null:(await n.select({fileName:R.fileName,filePath:R.filePath,fileType:R.fileType,fileSize:R.fileSize}).top(1).from(R).innerJoin(l,(0,Ue.eq)(l.id,R.hubId)).where((0,Ue.and)((0,Ue.eq)(R.id,f),(0,Ue.isNull)(l.deletedAt),t(m,"author"),r(y.visible))))[0]??null},markAttachmentMissing:async y=>{let f=o.attachment;if(!f)return;let m=new Date;try{await n.update(f).set({objectCheckedAt:m,objectMissingAt:m,updatedAt:m}).where((0,Ue.eq)(f.id,y))}catch(R){a.error("markAttachmentMissing failed",R)}},markAttachmentPresent:async y=>{let f=o.attachment;if(!f)return;let m=new Date;try{await n.update(f).set({objectCheckedAt:m,objectMissingAt:null,updatedAt:m}).where((0,Ue.eq)(f.id,y))}catch(R){a.error("markAttachmentPresent failed",R)}}}};var Sn=require("drizzle-orm");var Wt=require("drizzle-orm"),or=async(e,t,r,n)=>{if((await e.update(t).set({deletedAt:null}).output().where((0,Wt.and)((0,Wt.eq)(t.id,r),(0,Wt.isNull)(t.deletedAt),n===null?void 0:(0,Wt.eq)(t.userId,n)))).length===0)throw new Error("Not Found")};var Ml=(e,{isDraftReport:t,assertHubMutable:r,incrementRedisEpoch:n})=>{let{db:o,tables:a,users:i,encodeUserId:l,cache:s,inTransaction:c,prepareSearchIndex:d,publishToSseStream:u}=e,{dateEpochPrefix:h,detailEpochPrefix:p}=e.settings.redisKeys,{hub:y,comment:f}=a,m=async(S,g)=>{if(g!==null)return await t(S)?g:void 0},R=async(S,g,M,D,x,F)=>{let I=await r(S,M,g);if(!Ce(S.commentable,I.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(I.sourceType.toLowerCase()!==We.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let v=await m(M,I.userId),C=await d(),j=await c(async _=>{await or(_,y,M,null);let[B]=await _.insert(f).output().values({hubId:M,userId:g,body:D,createdAt:new Date,createdBy:String(g),updatedAt:new Date,updatedBy:String(g)});return C!==null&&await C.writeHubs(_,[M]),B}),[Q]=await o.select({displayName:i.displayName}).top(1).from(i).where((0,Sn.eq)(i.id,g)),J=Q?.displayName??"";if(x){let _=qe(x);_&&(s.invalidatePrefix(tr(_)),await n(`${h}${_}`))}s.invalidatePrefix(Xe(M)),await n(`${p}${M}`);let $={id:j.id,userId:l(j.userId),userName:J,content:j.body,createdAt:Me(j.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(Ln.parse({type:"comment-add",reportHubId:M,comment:$,clientTempId:F,recipientRawUserId:v,sourceType:I.sourceType}),"addComment"),$},A=async(S,g)=>await S.select().top(1).from(f).where((0,Sn.eq)(f.id,g));return{addComment:R,deleteComment:async(S,g,M,D,x,F)=>{let I=await A(o,D);if(I.length===0)throw new Error("Not Found");if(I[0].hubId!==M)throw new Error("Not Found");let v=await r(S,I[0].hubId,g);if(I[0].userId!==g)throw new Error("Unauthorized");let C=await m(M,v.userId),j=await d();if(await c(async Q=>{await or(Q,y,M,null),await Q.delete(f).where((0,Sn.eq)(f.id,D)),j!==null&&await j.writeHubs(Q,[M])}),x){let Q=qe(x);Q&&(s.invalidatePrefix(tr(Q)),await n(`${h}${Q}`))}s.invalidatePrefix(Xe(M)),await n(`${p}${M}`),await u(vn.parse({type:"comment-delete",reportHubId:M,commentId:D,clientTempId:F,recipientRawUserId:C,sourceType:v.sourceType}),"deleteComment")}}};var Ye=require("drizzle-orm");var Pl=e=>e===We;var kl=e=>e===""?null:e,Ll=(e,{readCanonicalDraftLabelId:t,isDraftReport:r,getDailyReportDetailById:n,assertHubMutable:o,incrementRedisEpoch:a})=>{let{db:i,tables:l,cache:s,logger:c,inTransaction:d,prepareSearchIndex:u,publishToSseStream:h,settings:p,draftVisibilityTables:y}=e,{idsEpoch:f,dateEpochPrefix:m,detailEpochPrefix:R}=e.settings.redisKeys,{hub:A,internal:w,hubLabel:S,userStatus:g}=l,{canonicalDraftLabelName:M,draftLabelNames:D}=p,x=async($,_,B,Y)=>{if(!Nr(B))throw Z("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",B);if(!Ce($.visible,We))throw new Error("Forbidden");c.info("createDailyReport called",{userId:_,businessDate:B});let de=await u();try{let ae=await d(async b=>{c.info("Starting transaction");let O=await t(b);if(O===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(M)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let N=`internal-temp-${Date.now()}-${Math.random()}`,[L]=await b.insert(A).output().values({sourceType:We,sourceId:N,businessDate:new Date(`${B}T00:00:00Z`),userId:_,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(_),updatedAt:new Date,updatedBy:String(_)});return await b.update(A).set({sourceId:String(L.id)}).where((0,Ye.eq)(A.id,L.id)),c.info("Hub created",L),await b.insert(w).values({hubId:L.id,body:"",createdAt:new Date,createdBy:String(_),updatedAt:new Date,updatedBy:String(_)}),c.info("Internal created"),await b.insert(S).values({hubId:L.id,labelId:O,createdAt:new Date,createdBy:String(_)}),c.info("Label assigned"),await b.insert(g).values({hubId:L.id,userId:_,isRead:!0,isStarred:!1,createdAt:new Date,createdBy:String(_),updatedAt:new Date,updatedBy:String(_)}),de!==null&&await de.writeHubs(b,[L.id]),L.id});s.invalidatePrefix(rr(B,_)),s.invalidatePrefix(wo(_)),await a(f),await a(`${m}${B}`);let pe=await n(Qe.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),ae,_,{forceRefresh:!0});if(pe===null)throw new Error(`[daily-report] createDailyReport: report ${ae} was committed but its detail read returned nothing`);let De=await r(pe.reportHubId);await h(Hn.parse({type:"report-create",reportHubId:pe.reportHubId,report:pe,clientTempId:Y,recipientRawUserId:De?_:void 0,actorRawUserId:_}),"createDailyReport");let X=await n($,ae,_,{forceRefresh:!0});if(X===null)throw new Error(`[daily-report] createDailyReport: the actor's scope cannot read report ${ae} it just created`);return X}catch(ae){throw c.error("Error in createDailyReport",ae),ae}},F=async($,_)=>await $.select().top(1).from(A).where((0,Ye.eq)(A.id,_)),I=async($,_,B)=>{await o($,_,B);let[Y]=await F(i,_);if(Y===void 0||Y.deletedAt)throw new Error("Not Found");if(!Pl(Y.sourceType))throw new Error("Forbidden");if(Y.userId!==B)throw new Error("Unauthorized");return Y},v=async($,_,B)=>{await $.update(A).set(B).where((0,Ye.eq)(A.id,_))},C=async($,_,B)=>{await $.update(w).set(B).where((0,Ye.eq)(w.hubId,_))};return{createDailyReport:x,updateDailyReport:async($,_,B,Y,de)=>{let ae=await I($,_,B),pe=await u();await d(async b=>{await or(b,A,_,B),Y.title!==void 0&&await v(b,_,{title:kl(Y.title),updatedAt:new Date,updatedBy:String(B)}),Y.content!==void 0&&await C(b,_,{body:kl(Y.content),updatedAt:new Date,updatedBy:String(B)}),pe!==null&&await pe.writeHubs(b,[_])}),s.invalidatePrefix(Xe(_)),await a(`${R}${_}`);let De=qe(Me(ae.businessDate,"YYYY-MM-DD"));De&&(s.invalidatePrefix(tr(De)),await a(`${m}${De}`));let X=await n(Qe.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),_,B,{forceRefresh:!0});if(X){let b=await r(_);await h(Fn.parse({type:"report-update",reportHubId:X.reportHubId,report:X,clientTempId:de,recipientRawUserId:b?B:void 0,actorRawUserId:B}),"updateDailyReport")}},publishDailyReport:async($,_,B,Y)=>{let de=await I($,_,B),ae=await u();if(await d(async b=>{await or(b,A,_,B),await b.delete(S).where((0,Ye.and)((0,Ye.eq)(S.hubId,_),nl(y,D))),ae!==null&&await ae.writeHubs(b,[_])}),s.invalidatePrefix(Xe(_)),s.invalidatePrefix(Mt),await a(f),de.businessDate){let b=qe(Me(de.businessDate,"YYYY-MM-DD"));b&&await a(`${m}${b}`)}let pe=qe(Me(de.businessDate,"YYYY-MM-DD"));pe&&s.invalidatePrefix(rr(pe,B));let De=await n(Qe.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),_,B,{forceRefresh:!0});if(De===null)return null;let X=await r(_);return await h($n.parse({type:"report-publish",reportHubId:De.reportHubId,report:De,clientTempId:Y,recipientRawUserId:X?B:void 0,actorRawUserId:B}),"publishDailyReport"),await n($,_,B,{forceRefresh:!0})},deleteDailyReport:async($,_,B,Y)=>{let de=await I($,_,B);if(await d(async ae=>{if((await ae.update(A).set({deletedAt:new Date,deletedBy:String(B),updatedAt:new Date,updatedBy:String(B)}).output().where((0,Ye.and)((0,Ye.eq)(A.id,_),(0,Ye.eq)(A.userId,B),(0,Ye.isNull)(A.deletedAt)))).length===0)throw new Error("Not Found")}),s.invalidatePrefix(Xe(_)),s.invalidatePrefix(Mt),await a(f),de.businessDate){let ae=qe(Me(de.businessDate,"YYYY-MM-DD"));ae&&await a(`${m}${ae}`)}await h(Fr.parse({type:"report-delete",reportHubId:_,clientTempId:Y,sourceType:de.sourceType}),"deleteDailyReport")}}};var K=require("drizzle-orm");var vl=Ur([]),Sm=6e4,Ho=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw Ke(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw Z(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw Ke(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw Z(`${e}: options.signal`,r,n);return n},Fo=e=>{let t=async()=>{await new Promise(r=>setImmediate(r)),e.throwIfAborted()};return{sliceMs:Pr.sliceMs,now:ce,pause:t}},Oo=e=>{try{return{ok:!0,value:e()}}catch(t){return{ok:!1,cause:t}}},gm=e=>Oo(()=>{let t=hr.safeParse(JSON.parse(JSON.stringify(e)));if(!t.success)throw new Error(`[daily-report] the detail does not match the delivered detail schema (${Ca(t.error)})`);return t.data}),Nl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r,draftLabelFlag:n,externalSelections:o,applyExternalJoins:a,resolveHubDisplayFields:i,resolveCreationCategoryDraftLabelId:l,mapHubRecord:s,getAttachmentsByHubIds:c,readSseStreamAnchor:d,incrementRedisEpoch:u})=>{let{db:h,tables:p,users:y,resolveUserId:f,cache:m,epochs:R,logger:A,settings:w}=e,{idsEpoch:S,dateEpochPrefix:g,detailEpochPrefix:M}=e.settings.redisKeys,{hub:D,internal:x,comment:F,label:I,hubLabel:v,userStatus:C}=p,j=w.idsTtlMs,Q=w.businessDateTtlMs,J=async(P,k)=>(await h.select({reportHubId:D.id,businessDate:D.businessDate,sourceType:D.sourceType}).from(D).where((0,K.and)((0,K.isNull)(D.deletedAt),t(k,"author-or-authorless"),r(P.visible))).orderBy((0,K.desc)(D.businessDate),(0,K.desc)(D.id))).map(U=>({...U,businessDate:Me(U.businessDate,"YYYY-MM-DD")})),$=async(P,k,T)=>{let U=await B(k);return U?Fe(P.visible)?[]:(await h.select({reportHubId:D.id,businessDate:D.businessDate,sourceType:D.sourceType}).top(T).from(D).where((0,K.and)((0,K.isNull)(D.deletedAt),t(U,"author-or-authorless"),r(P.visible))).orderBy((0,K.desc)(D.businessDate),(0,K.desc)(D.id))).map(Se=>({...Se,businessDate:Me(Se.businessDate,"YYYY-MM-DD")})):[]},_=new Map,B=async P=>{if(!w.disableUserIdCache&&_.has(P))return _.get(P)??null;let k=await f(P);return k!==null&&!w.disableUserIdCache&&_.set(P,k),k},Y=async(P,k,{forceRefresh:T=!1,snapshot:U=!1,ttlMsOverride:W,onFetchStart:Se,admission:He}={})=>{let Ie=await B(k);if(!Ie)return{items:[],streamAnchor:null,snapshot:vl};if(Fe(P.visible))return{items:[],streamAnchor:await d(),snapshot:vl};let Re=Ms(Ie,nn(P)),[Ae]=await m.getOrFetch({cacheKey:Re,fetcher:async()=>{let Ge=await d(),at=await J(P,Ie);if(!Aa(at)){A.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=[...at].sort(Un);return[{items:oe,streamAnchor:Ge,snapshot:Ur(oe)}]}return[{items:at,streamAnchor:Ge,snapshot:Ur(at)}]},onFetchStart:Se,forceRefresh:T,snapshot:U,admission:He,ttlMsOverride:W??j,epochKey:S,refreshAheadRatio:.5});if(Ae===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return Ae},de=async(P,k,T)=>{let U=await a(h.select({hub:Et(D),internal:Et(x),isRead:C.isRead,isStarred:C.isStarred,creatorName:y.displayName,hasDraftLabel:n,...o()}).from(D)).leftJoin(x,(0,K.eq)(D.id,x.hubId)).leftJoin(C,(0,K.and)((0,K.eq)(D.id,C.hubId),(0,K.eq)(C.userId,k))).leftJoin(y,(0,K.eq)(D.userId,y.id)).where((0,K.and)(T,(0,K.isNull)(D.deletedAt),t(k,"author"),r(P.visible))).orderBy((0,K.desc)(D.id));if(U.length===0)return[];let W=U.map(oe=>oe.hub.id),Se=await h.select({hubId:v.hubId,id:I.id,name:I.name,color:I.color}).from(v).innerJoin(I,(0,K.eq)(v.labelId,I.id)).where((0,K.inArray)(v.hubId,W)),He=await h.select({hubId:F.hubId,id:F.id,body:F.body,createdAt:F.createdAt,userId:F.userId,userName:y.displayName}).from(F).leftJoin(y,(0,K.eq)(F.userId,y.id)).where((0,K.inArray)(F.hubId,W)).orderBy((0,K.asc)(F.createdAt)),Ie=await c(W),Re=new Map,Ae=new Map;for(let oe of Se){let ve=Re.get(oe.hubId);ve||(ve=[],Re.set(oe.hubId,ve)),ve.push({id:oe.id,name:oe.name,color:oe.color})}for(let oe of He){let ve=Ae.get(oe.hubId);ve||(ve=[],Ae.set(oe.hubId,ve)),ve.push({id:oe.id,content:oe.body,createdAt:Me(oe.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:oe.userId,userName:oe.userName||""})}let Ge=U.map(oe=>Oo(()=>i(oe))),at=await l(Ge.flatMap(oe=>oe.ok?[oe.value]:[]));return U.map((oe,ve)=>{let ft=oe.hub.id,Lt=Ge[ve],wt=Lt.ok?Oo(()=>s(P,{...oe,attachments:Ie.get(ft)??[],labels:Re.get(ft)||[],postedCommentRows:Ae.get(ft)||[]},Lt.value,at,k)):Lt;return wt.ok?{reportHubId:ft,outcome:"ok",report:wt.value}:{reportHubId:ft,outcome:"failed",cause:wt.cause}})},ae=async(P,k,T)=>(await de(P,k,T)).map(U=>{if(U.outcome==="failed")throw U.cause;return U.report}),pe=P=>ke({windowMs:Sm,tallies:["failed"],writeSuppressed:(k,{count:T,since:U})=>{A.warn(`failed_report_suppressed count=${T} since=${U} read=${P} report=${k}`)}}),De={markDailyReportSearchHits:pe("markDailyReportSearchHits"),getDailyReportDetailsByIdsByExternalId:pe("getDailyReportDetailsByIdsByExternalId")},X=(P,k,T)=>{De[P].record(k,"failed",()=>A.error(`${P}: report ${k} passed the visibility predicate but its own assembly failed`,T))},b=(P,k)=>{let T=k.outcome==="ok"?gm(k.report):{ok:!1,cause:k.cause};return T.ok?{reportHubId:k.reportHubId,outcome:"ok",report:T.value}:(X(P,k.reportHubId,T.cause),{reportHubId:k.reportHubId,outcome:"failed"})},O=async(P,k,T,{read:U,signal:W,slicing:Se})=>{let He=await de(P,k,(0,K.inArray)(D.id,[...T]));W.throwIfAborted();let Ie=[],Re=Se.now();for(let Ae of He)Ie.length>0&&Se.now()-Re>=Se.sliceMs&&(await Se.pause(),Re=Se.now()),Ie.push(b(U,Ae));return Ie},N=async(P,k,T,{forceRefresh:U=!1,snapshot:W=!1,ttlMsOverride:Se,admission:He}={})=>{let Ie=await B(T);if(!Ie)return[];let Re=qe(k);if(!Re)return[];if(Fe(P.visible))return[];let Ae=Ps(Re,Ie,nn(P));return m.getOrFetch({cacheKey:Ae,fetcher:()=>ae(P,Ie,(0,K.eq)(D.businessDate,K.sql`${Re}`)),forceRefresh:U,snapshot:W,admission:He,ttlMsOverride:Se??Q,epochKey:`${g}${Re}`})},L=async(P,k,T,{forceRefresh:U=!1,snapshot:W=!1,ttlMsOverride:Se,admission:He}={})=>{if(Fe(P.visible))return null;let Ie=ks(k,T,nn(P));return(await m.getOrFetch({cacheKey:Ie,fetcher:async()=>{let Ae=await a(h.select({hub:Et(D),internal:Et(x),isRead:C.isRead,isStarred:C.isStarred,creatorName:y.displayName,hasDraftLabel:n,...o()}).from(D)).leftJoin(x,(0,K.eq)(D.id,x.hubId)).leftJoin(C,(0,K.and)((0,K.eq)(D.id,C.hubId),(0,K.eq)(C.userId,T))).leftJoin(y,(0,K.eq)(D.userId,y.id)).where((0,K.and)((0,K.eq)(D.id,k),(0,K.isNull)(D.deletedAt),t(T,"author"),r(P.visible)));if(Ae.length===0)return[];let Ge=Ae[0].hub.id,at=await h.select({id:I.id,name:I.name,color:I.color}).from(v).innerJoin(I,(0,K.eq)(v.labelId,I.id)).where((0,K.eq)(v.hubId,Ge)),oe=await h.select({id:F.id,body:F.body,createdAt:F.createdAt,userId:F.userId,userName:y.displayName}).from(F).leftJoin(y,(0,K.eq)(F.userId,y.id)).where((0,K.eq)(F.hubId,Ge)).orderBy((0,K.asc)(F.createdAt)),ve=await c([Ge]),ft=at.map(Ze=>({id:Ze.id,name:Ze.name,color:Ze.color})),Lt=oe.map(Ze=>({id:Ze.id,content:Ze.body,createdAt:Me(Ze.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Ze.userId,userName:Ze.userName||""})),wt=i(Ae[0]),En=await l([wt]);return[s(P,{...Ae[0],attachments:ve.get(Ge)??[],labels:ft,postedCommentRows:Lt},wt,En,T)]},forceRefresh:U,snapshot:W,admission:He,ttlMsOverride:Se??Q,epochKey:`${M}${k}`}))[0]??null};return{getUserIdByExternalId:B,getDailyReportIdsByExternalId:Y,getDailyReportIdsFirstPageByExternalId:$,getDailyReportsByBusinessDateByExternalId:N,getDailyReportDetailById:L,getDailyReportDetailByIdByExternalId:async(P,k,T,U={})=>{let W=await B(T);return W?L(P,k,W,U):null},getDailyReportDetailsByIdsByExternalId:async(P,k,T,U)=>{let W=Ho("getDailyReportDetailsByIdsByExternalId",U);if(k.length>Pe.maxDetailIds)throw Z("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${Pe.maxDetailIds} ids`,k.length);let Se=await B(T);if(!Se||k.length===0||Fe(P.visible))return k.map(Rr);W.throwIfAborted();let He=await O(P,Se,k,{read:"getDailyReportDetailsByIdsByExternalId",signal:W,slicing:Fo(W)}),Ie=new Map(He.map(Re=>[Re.reportHubId,Re]));return k.map(Re=>{let Ae=Ie.get(Re);return Ae===void 0?Rr(Re):Ae})},fetchDeliveredHubOutcomes:O,invalidateHubReadCaches:async(P,k)=>{m.invalidatePrefix(Mt),await u(S);for(let T of new Set(P))m.invalidatePrefix(Xe(T)),await u(`${M}${T}`);for(let T of new Set(k)){let U=qe(T);U&&await u(`${g}${U}`)}},clearCache:async()=>{m.clearAll(),_.clear(),R&&await u(S),A.info("Server-side DB/SQL caches cleared successfully.")}}};var bm="v4",Dm=/^(?!:)[^\s\p{Cc}]+(?<!:)$/u,gn=e=>{if(typeof e!="string"||!Dm.test(e))throw Z("redisKeyPrefix",'a Redis key prefix of one or more characters without whitespace or control characters, neither starting nor ending with ":"',e);return Object.freeze({sseStream:`${e}:sse-stream:${bm}`,idsEpoch:`${e}:ids:epoch`,dateEpochPrefix:`${e}:date-epoch:`,detailEpochPrefix:`${e}:detail-epoch:`})};var bn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,redisKeyPrefix:"daily-report",streamMaxLen:1e4}),Am=e=>{let{length:t}=e;if(t===void 0)throw Z("tables.hub.title","a character column with a declared length",t);return le("tables.hub.title.length",t,1)},Tm=e=>{if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0)||new Set(e).size!==e.length)throw Z("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},Em=e=>{let t=new Map([[We.toLowerCase(),`the internal source type ${JSON.stringify(We)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw Z(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([We,...e.map(r=>r.sourceType)])},Ol=e=>{let t=e.externalSources??[],r=Tm(e.draftLabelNames);if(Zr(e),Object.hasOwn(e,"streamKey"))throw Ke("redisKeyPrefix","given in place of the removed key streamKey");let n=Bi(e.attachments),o=Am(e.tables.hub.title);yo(e.tables.hub.sourceType);let a=Ne("idsTtlMs",e.idsTtlMs,1,bn.idsTtlMs),i=Ne("businessDateTtlMs",e.businessDateTtlMs,1,bn.businessDateTtlMs),l=Ne("streamMaxLen",e.streamMaxLen,1,bn.streamMaxLen),s=gn(e.redisKeyPrefix===void 0?bn.redisKeyPrefix:e.redisKeyPrefix);return Object.freeze({externalSources:t,sourceTypes:Em(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamMaxLen:l,redisKeys:s,disableUserIdCache:!!e.disableUserIdCache})};var Hl=({redis:e,logger:t,epochs:r,streamKey:n,streamMaxLen:o})=>({incrementRedisEpoch:s=>r.incrementEpoch(s),publishToSseStream:async(s,c)=>{let d=await e?.getClient();if(!d){t.warn(`[SSE] Redis client unavailable (${c})`);return}let u=JSON.stringify(s),h=Buffer.byteLength(u);if(h>6356992){t.warn(`[SSE] Event too large (${c}): ${h} bytes > ${6356992}; not published`);return}let p=ce();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let y=ce()-p;y>1e3&&t.warn(`[SSE] Slow publish (${c}): ${y}ms`)}catch(y){t.error(`[SSE] Redis publish failed (${c}):`,y)}},readSseStreamAnchor:async()=>{try{let s=await e?.getClient();if(s===void 0)return null;let[c]=await s.xRevRange(n,"+","-",{COUNT:1});return c===void 0?_t:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});var he=require("drizzle-orm");var Dn=["hubId","userId","isRead","isStarred","createdAt","createdBy","updatedAt","updatedBy"],Im={isRead:{statusType:"read",callerName:"setReadStatus"},isStarred:{statusType:"star",callerName:"setStarStatus"}},ze=e=>he.sql`${he.sql.identifier(e.name)}`,_m=(e,t,{reportHubId:r,userId:n,value:o,at:a})=>{let i=String(n),l=ze(e[t]),s=(p,y)=>he.sql`t.${ze(p)} = CASE WHEN t.${l} = ${o} THEN t.${ze(p)} ELSE ${y} END`,c={hubId:he.sql`s.${ze(e.hubId)}`,userId:he.sql`s.${ze(e.userId)}`,isRead:he.sql`${t==="isRead"?o:!1}`,isStarred:he.sql`${t==="isStarred"?o:!1}`,createdAt:he.sql`${a}`,createdBy:he.sql`${i}`,updatedAt:he.sql`${a}`,updatedBy:he.sql`${i}`},d=he.sql.join(Dn.map(p=>ze(e[p])),he.sql`, `),u=he.sql.join(Dn.map(p=>c[p]),he.sql`, `),h=he.sql.join(Dn.map(p=>he.sql`inserted.${ze(e[p])} AS ${he.sql.identifier(p)}`),he.sql`, `);return he.sql`MERGE ${e} WITH (HOLDLOCK) AS t USING (SELECT ${r} AS ${ze(e.hubId)}, ${n} AS ${ze(e.userId)}) AS s ON t.${ze(e.hubId)} = s.${ze(e.hubId)} AND t.${ze(e.userId)} = s.${ze(e.userId)}
12
- WHEN MATCHED THEN UPDATE SET t.${l} = ${o}, ${s(e.updatedAt,a)}, ${s(e.updatedBy,i)}
13
- WHEN NOT MATCHED THEN INSERT (${d}) VALUES (${u})
14
- OUTPUT ${h};`},Fl=(e,t)=>(typeof e=="number"||typeof e=="string")&&String(e)===String(t),$l=e=>e instanceof Date||typeof e=="string",xm=e=>{if(!Array.isArray(e))return`recordset ${Nt(e)}`;if(e.length!==1)return`${e.length} rows`;let[t]=e;return typeof t!="object"||t===null?`a row of ${Nt(t)}`:Dn.map(r=>`${r}=${Nt(t[r])}`).join(", ")},Cm=(e,{reportHubId:t,userId:r})=>{let n=typeof e=="object"&&e!==null?e.recordset:void 0,o=Array.isArray(n)&&n.length===1?n[0]:void 0,a=typeof o=="object"&&o!==null?o:void 0;if(a===void 0||!Fl(a.hubId,t)||!Fl(a.userId,r)||typeof a.isRead!="boolean"||typeof a.isStarred!="boolean"||!$l(a.createdAt)||!$l(a.updatedAt)||typeof a.createdBy!="string"||typeof a.updatedBy!="string")throw new Error(`[daily-report] user status: the upsert must output the one status row of report ${t} and user ${r}; got ${xm(n)}`);return{hubId:t,userId:r,isRead:a.isRead,isStarred:a.isStarred,createdAt:a.createdAt,createdBy:a.createdBy,updatedAt:a.updatedAt,updatedBy:a.updatedBy}},Ul=(e,{draftVisibleTo:t,incrementRedisEpoch:r})=>{let{db:n,tables:o,cache:a,publishToSseStream:i}=e,{dateEpochPrefix:l,detailEpochPrefix:s}=e.settings.redisKeys,{hub:c,userStatus:d}=o,u=async(m,R)=>{let[A]=await n.select({sourceType:c.sourceType,userId:c.userId,deletedAt:c.deletedAt}).top(1).from(c).where((0,he.and)((0,he.eq)(c.id,m),t(R,"author")));return A??null},h=async(m,R,A)=>{let w=await u(R,A);if(!w||w.deletedAt||!Ce(m.visible,w.sourceType))throw new Error("Not Found");return{sourceType:w.sourceType,userId:w.userId}},p=async(m,R,A,w,S,g,M)=>{await h(R,w,A);let D={reportHubId:w,userId:A,value:g,at:new Date},x=Cm(await n.execute(_m(d,m,D)),D);if(S){let v=qe(S);v&&(a.invalidatePrefix(rr(v,A)),await r(`${l}${v}`))}a.invalidatePrefix(Io(w,A)),await r(`${s}${w}`);let{statusType:F,callerName:I}=Im[m];return await i(kn.parse({type:"status-update",reportHubId:w,recipientRawUserId:A,statusType:F,value:g,clientTempId:M}),I),x};return{assertHubMutable:h,setStarStatus:(m,R,A,w,S,g)=>p("isStarred",m,R,A,w,S,g),setReadStatus:(m,R,A,w,S,g)=>p("isRead",m,R,A,w,S,g)}};var Mm=Object.freeze([]),$o=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},An=(e,t)=>e.get(t)??Mm,Bl=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(an);function Tn(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:s}=e,{hub:c,internal:d,comment:u,label:h,hubLabel:p}=r,y=Ol(e),{externalSources:f,draftLabelNames:m,attachmentDelivery:R,titleMaxLength:A}=y,w=Ee(e.logger,1,"Service"),S=ne=>(0,ar.runWithTransactionRetry)(ye=>t.transaction(te=>ye(()=>ne(te))),e.transactionRetry),g=e.search===void 0?null:tl(e.search,f.map(ne=>ne.sourceType)),M={hub:c,hubLabel:p,label:h},D=g===null?null:ml({tables:{...M,search:g.tables},draftLabelNames:m});g!==null&&Ao();let x=null,F=async()=>{if(g===null)return null;if(x===null){let ne=await Ao(),ye=g.externalSourceTexts;x=fl({hub:c,tables:g.tables,loadSources:(te,ie)=>Ze(te,ie,ye),inTransaction:S,normalizerVersion:ne})}return x},{incrementRedisEpoch:I,publishToSseStream:v,readSseStreamAnchor:C}=Hl({redis:i,logger:w,epochs:s,streamKey:y.redisKeys.sseStream,streamMaxLen:y.streamMaxLen}),j={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:w,settings:y,draftVisibilityTables:M,inTransaction:S,publishToSseStream:v,prepareSearchIndex:F},{visibleSourceTypeCondition:Q,draftVisibleTo:J,draftLabelFlag:$,isDraftReport:_,externalSelections:B,applyExternalJoins:Y,resolveHubDisplayFields:de,readCanonicalDraftLabelId:ae,getDraftLabelId:pe,resolveCreationCategoryDraftLabelId:De,mapHubRecord:X}=xl(j),{getAttachmentsByHubIds:b,getAttachmentForUser:O,markAttachmentMissing:N,markAttachmentPresent:L}=Cl(j,{draftVisibleTo:J,visibleSourceTypeCondition:Q}),{getUserIdByExternalId:H,getDailyReportIdsByExternalId:z,getDailyReportIdsFirstPageByExternalId:ee,getDailyReportsByBusinessDateByExternalId:G,getDailyReportDetailById:P,getDailyReportDetailByIdByExternalId:k,getDailyReportDetailsByIdsByExternalId:T,fetchDeliveredHubOutcomes:U,invalidateHubReadCaches:W,clearCache:Se}=Nl(j,{draftVisibleTo:J,visibleSourceTypeCondition:Q,draftLabelFlag:$,externalSelections:B,applyExternalJoins:Y,resolveHubDisplayFields:de,resolveCreationCategoryDraftLabelId:De,mapHubRecord:X,getAttachmentsByHubIds:b,readSseStreamAnchor:C,incrementRedisEpoch:I}),{assertHubMutable:He,setStarStatus:Ie,setReadStatus:Re}=Ul(j,{draftVisibleTo:J,incrementRedisEpoch:I}),{addComment:Ae,deleteComment:Ge}=Ml(j,{isDraftReport:_,assertHubMutable:He,incrementRedisEpoch:I}),{createDailyReport:at,updateDailyReport:oe,publishDailyReport:ve,deleteDailyReport:ft}=Ll(j,{readCanonicalDraftLabelId:ae,isDraftReport:_,getDailyReportDetailById:P,assertHubMutable:He,incrementRedisEpoch:I}),Lt=async(ne,ye)=>{let te=new Map,ie=r.attachment;if(!ie||R===null)return te;let xe=await ne.select({hubId:ie.hubId,fileName:ie.fileName}).from(ie).where((0,we.inArray)(ie.hubId,[...ye])).orderBy((0,we.asc)(ie.hubId),(0,we.asc)(ie.createdAt),(0,we.asc)(ie.id));for(let se of xe)$o(te,Number(se.hubId),String(se.fileName));return te},wt=async(ne,ye,te)=>{let ie=new Map;for(let[xe,se]of te){let it=new Map;for(let{hub:Be}of ye)Be.sourceType===xe&&Be.sourceIdNum!==null&&it.set(Be.sourceIdNum,Be.id);if(it.size===0)continue;let It=await se(ne,[...it.keys()]);for(let[Be,st]of It){let vt=it.get(Be);if(vt===void 0)throw Z(`search.externalSourceTexts.${xe} answer key`,"a source id that was asked for",Be);if(!(Array.isArray(st)&&st.every(ir=>typeof ir=="string")))throw Z(`search.externalSourceTexts.${xe} answer for ${Be}`,"an array of strings",st);ie.set(vt,st)}}return ie},En=(ne,ye)=>{let te=de(ne),ie=[["subject",ne.hub.title],["content",te.content],["author",te.author],["employeeName",te.employeeName],["updatedBy",te.updatedBy],["category",te.category],["creationCategory",te.creationCategory],["customerName",te.customerName]];for(let se of te.interviewers)ie.push(["interviewerName",se.name??null],["interviewerAffiliation",se.affiliation??null]);for(let se of ye.labelNames)ie.push(["label",se]);for(let se of ye.attachmentNames)ie.push(["attachment",se]);for(let se of ye.extraTexts)ie.push(["extra",se]);let xe=[];for(let se of te.externalComments)xe.push({authorUserId:null,text:Bl(se.name,se.text)});for(let se of ye.postedComments)xe.push({authorUserId:se.userId,text:Bl(se.userName,se.body)});return{hubId:ne.hub.id,fields:ie,comments:xe,filterValues:{authorName:te.employeeName,customerName:te.customerName}}},Ze=async(ne,ye,te)=>{let ie=[];for(let xe of(0,ar.chunk)(ye,ar.MAX_IN_LIST)){let se=await Y(ne.select({hub:Et(c),internal:Et(d),creatorName:n.displayName,...B()}).from(c)).leftJoin(d,(0,we.eq)(c.id,d.hubId)).leftJoin(n,(0,we.eq)(c.userId,n.id)).where((0,we.inArray)(c.id,[...xe])).orderBy((0,we.asc)(c.id)),it=new Map,It=await ne.select({hubId:p.hubId,name:h.name}).from(p).innerJoin(h,(0,we.eq)(p.labelId,h.id)).where((0,we.inArray)(p.hubId,[...xe])).orderBy((0,we.asc)(p.hubId),(0,we.asc)(h.id));for(let et of It)$o(it,et.hubId,et.name);let Be=new Map,st=await ne.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,(0,we.eq)(u.userId,n.id)).where((0,we.inArray)(u.hubId,[...xe])).orderBy((0,we.asc)(u.hubId),(0,we.asc)(u.createdAt),(0,we.asc)(u.id));for(let et of st)$o(Be,et.hubId,et);let vt=await Lt(ne,xe),ir=await wt(ne,se,te);for(let et of se){let Ve=et.hub.id;ie.push(En(et,{labelNames:An(it,Ve),postedComments:An(Be,Ve),attachmentNames:An(vt,Ve),extraTexts:An(ir,Ve)}))}}return ie},sc=(ne,ye,te)=>D===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):D.search(t,{criteria:te,viewerUserId:ye,scope:ne}),qo=y.sourceTypes,lc=async(ne,ye)=>{if(D===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let te=qo.filter(se=>Ce(ne.visible,se)),ie=await D.facetValues(t,{column:"authorName",viewerUserId:ye,scope:ne}),xe=await D.facetValues(t,{column:"customerName",viewerUserId:ye,scope:ne});return{sourceTypes:te,authors:ie,customers:xe}},cc=async(ne,ye,te,ie,xe)=>{let se=Ho("markDailyReportSearchHits",xe);if(D===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(ie.length>Pe.maxDetailIds)throw Z("markDailyReportSearchHits: reportHubIds",`at most ${Pe.maxDetailIds} ids`,ie.length);let it=Br(Er(te));if(ie.length===0||Fe(ne.visible))return{wordsDigest:it,reports:[],deferred:[]};se.throwIfAborted();let It=Fo(se),Be=await U(ne,ye,ie,{read:"markDailyReportSearchHits",signal:se,slicing:It});await It.pause();let st=Be.flatMap(Ve=>Ve.outcome==="ok"?[{reportHubId:Ve.reportHubId,fields:Il(Ve.report)}]:[]),vt=te.combine==="union"&&te.sets.length>=2&&st.length>0?await D.matchedSets(t,{plan:te,viewerUserId:ye,scope:ne,ids:st.map(Ve=>Ve.reportHubId)}):null,ir=st.map(({reportHubId:Ve,fields:dc})=>{let jo=vt===null?null:vt.get(Ve),Wo=jo===void 0?0:jo;return{reportHubId:Ve,matchedSets:Wo,alternatives:wl(te,Wo).flatMap(pc=>pc.alternatives),fields:dc}}),et=await _l(ir,Pr,It.pause,Dl(Pr,It.now));return{wordsDigest:it,reports:et.reports,deferred:et.deferred}},uc=async ne=>{let ye=await F();if(ye===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return ye.reconcile(t,ne)};return{streamKey:y.redisKeys.sseStream,attachmentDelivery:R,titleMaxLength:A,searchLimits:g===null?null:{concurrency:g.concurrency,rateLimitPerMinute:g.rateLimitPerMinute},searchFilterSourceTypes:qo,clearCache:Se,invalidateHubReadCaches:W,getUserIdByExternalId:H,getDailyReportIdsByExternalId:z,getDailyReportIdsFirstPageByExternalId:ee,readSseStreamAnchor:C,getDailyReportsByBusinessDateByExternalId:G,getDailyReportDetailById:P,getDailyReportDetailByIdByExternalId:k,getDailyReportDetailsByIdsByExternalId:T,getDraftLabelId:pe,searchDailyReports:sc,markDailyReportSearchHits:cc,listDailyReportSearchFacets:lc,reconcileSearchIndex:uc,getAttachmentsByHubIds:b,getAttachmentForUser:O,markAttachmentMissing:N,markAttachmentPresent:L,setStarStatus:Ie,setReadStatus:Re,addComment:Ae,deleteComment:Ge,createDailyReport:at,updateDailyReport:oe,publishDailyReport:ve,deleteDailyReport:ft}}var Vl=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(Ee(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return Ee(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};var kr=require("drizzle-orm"),E=require("drizzle-orm/mssql-core");function ql(e,t){let r=(0,E.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,E.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,E.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,E.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,E.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(kr.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,E.date)("business_date"),userId:(0,E.bigint)("user_id",{mode:"number"}),title:(0,E.nvarchar)("title",{length:200}),summary:(0,E.nvarchar)("summary",{length:"max"}),createdAt:(0,E.datetime2)("created_at").notNull(),createdBy:(0,E.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,E.datetime2)("updated_at").notNull(),updatedBy:(0,E.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,E.datetime2)("deleted_at"),deletedBy:(0,E.nvarchar)("deleted_by",{length:50})},u=>[(0,E.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),(0,E.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,E.index)(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),(0,E.index)(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),(0,E.index)(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),(0,E.index)(`${e}_DailyReportHub_user_id_index`).on(u.userId),(0,E.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,kr.desc)(u.businessDate),(0,kr.desc)(u.id)),(0,E.index)(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,E.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,E.nvarchar)("body",{length:"max"}),metadata:(0,E.nvarchar)("metadata",{length:"max"}),createdAt:(0,E.datetime2)("created_at").notNull(),createdBy:(0,E.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,E.datetime2)("updated_at").notNull(),updatedBy:(0,E.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,E.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),(0,E.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:(0,E.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,E.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,E.bigint)("user_id",{mode:"number"}).notNull(),body:(0,E.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,E.datetime2)("created_at").notNull(),createdBy:(0,E.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,E.datetime2)("updated_at").notNull(),updatedBy:(0,E.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,E.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),(0,E.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,E.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,E.index)(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:(0,E.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,E.bigint)("user_id",{mode:"number"}),name:(0,E.nvarchar)("name",{length:50}).notNull(),color:(0,E.nvarchar)("color",{length:20}),sortOrder:(0,E.int)("sort_order"),createdAt:(0,E.datetime2)("created_at").notNull(),createdBy:(0,E.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,E.datetime2)("updated_at").notNull(),updatedBy:(0,E.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,E.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),(0,E.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:(0,E.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,E.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,E.datetime2)("created_at").notNull(),createdBy:(0,E.nvarchar)("created_by",{length:50}).notNull()},u=>[(0,E.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),(0,E.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,E.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:(0,E.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,E.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,E.bit)("is_read").default(!1).notNull(),isStarred:(0,E.bit)("is_starred").default(!1).notNull(),createdAt:(0,E.datetime2)("created_at").notNull(),createdBy:(0,E.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,E.datetime2)("updated_at").notNull(),updatedBy:(0,E.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,E.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),(0,E.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,E.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:(0,E.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,E.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,E.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,E.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,E.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,E.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,E.nvarchar)("file_type",{length:100}),fileSize:(0,E.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,E.datetime2)("object_checked_at"),objectMissingAt:(0,E.datetime2)("object_missing_at"),createdAt:(0,E.datetime2)("created_at").notNull(),createdBy:(0,E.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,E.datetime2)("updated_at").notNull(),updatedBy:(0,E.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,E.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),(0,E.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,E.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),(0,E.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),(0,E.index)(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:d,label:l,hubLabel:s,userStatus:c}}var fe=require("drizzle-orm/mssql-core");function jl(e){let t=(0,fe.mssqlSchema)(e),r=t.table("DailyReportSearchDocument",{hubId:(0,fe.bigint)("hub_id",{mode:"number"}).notNull(),searchText:(0,fe.nvarchar)("search_text",{length:"max"}).notNull(),sourceDigest:(0,fe.binary)("source_digest",{length:32}).notNull(),normalizerVersion:(0,fe.varchar)("normalizer_version",{length:64}).notNull(),indexedAt:(0,fe.datetime2)("indexed_at").notNull(),rowVersion:(0,fe.binary)("row_version",{length:8}).notNull(),authorName:(0,fe.nvarchar)("author_name",{length:St.maxValueLength}),customerName:(0,fe.nvarchar)("customer_name",{length:St.maxValueLength})},o=>[(0,fe.primaryKey)({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:(0,fe.bigint)("hub_id",{mode:"number"}).notNull(),ordinal:(0,fe.int)("ordinal").notNull(),authorUserId:(0,fe.bigint)("author_user_id",{mode:"number"}),commentText:(0,fe.nvarchar)("comment_text",{length:"max"}).notNull()},o=>[(0,fe.primaryKey)({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var Pm=5e7,Uo=2e8,km=1,Bo=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})})}),Wl=125,Yl=4,zl=16,Gl=50,Kl=2,Lr=Object.freeze({renderMs:je.renderMs,nanosecondsPerBlockVisit:Wl,margin:Yl,maxBlockVisits:Math.floor(je.renderMs*1e6/(Wl*Yl)),walkBudgetMs:zl,nanosecondsPerWalkStep:Gl,walkMargin:Kl,maxWalkSteps:Math.floor(zl*1e6/(Gl*Kl))}),Lm=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Jl=75,Ql=4,Xl="#ffffff",vm=1,Nm={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Om=[/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/],Zl=Object.freeze({ok:!1,reason:"failed"}),ec=Object.freeze({ok:!1,reason:"unsupported"}),tc=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Ai(e)}),rc=(e,t)=>{switch(t){case"jpeg":{let r=co(e);return r===null?null:tc(r)}case"png":{let r=wi(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Ii(e,Lr.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},nc=(e,t)=>{let r=Lm.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Bo,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},oc=(e,t,r)=>{let n=rc(e,t);return n===null?null:nc(n,r)},Hm=e=>e!==null&&e<=Uo,Fm=(e,t)=>{if(t!=="jpeg")return rc(e,t);let r=Ti(e,Lr);return r===null||r.blockVisits>Lr.maxBlockVisits?null:tc(r.header)},$m=e=>{let t=e instanceof Error?e.message:"";return Om.some(r=>r.test(t))?"failed":"unsupported"},ac=e=>{e.cache(!1),e.concurrency(km),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Nm)});let t=async(n,o,a,i,l)=>{let s=Fm(n,o);if(s===null)return ec;try{let c=e(n,{limitInputPixels:Pm,animated:!1});if(!Hm(nc(s,await c.metadata())))return ec;if(l.aborted)return Zl;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Xl}).webp({quality:Jl,effort:Ql}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:$m(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?Zl:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Jl}-e${Ql}/flatten-${Xl}/v${vm}`,render:r}};var Vo=6e4,ic=e=>{let t=le("ttlMs",e.ttlMs,1,Vo),r=lr("readViewerKey",e.readViewerKey),n=lr("resolve",e.resolve),o=new Map;return async(a,i)=>{let l=await r(a,i);if(l===null)throw new Error(`[daily-report] createDailyReportVisibilityCache: the request names no viewer for the ${JSON.stringify(i.reason)} resolution (readViewerKey answered null), so no source type may be shown`);let s=ce(),c=o.get(l);if(i.reason==="initial"&&c!==void 0&&s<c.expiresAt)return c.answer;let d=Promise.resolve().then(()=>n(a,i));for(let[h,p]of o)p.expiresAt<=s&&o.delete(h);o.set(l,{expiresAt:s+t,answer:d});let u=()=>{o.get(l)?.answer===d&&o.delete(l)};return d.catch(u),d}};function Um(e){e.redis||Ee(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=vr(e.redis),r=new Yt({defaultTtlMs:e.cacheDefaultTtlMs,maxBuckets:e.cacheMaxBuckets,maxBytes:e.cacheMaxBytes},t),n=Tn({...e,cache:r,epochs:t}),o=new nr({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=pn({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:n.searchFilterSourceTypes,...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,DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,buildDailyReportRedisKeys,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createDailyReportVisibilityCache,createEpochStore,createSharpThumbnailRenderer,dailyReportSseStreamMessageSchema,defineDailyReportSchema,defineDailyReportSearchSchema,encodeIdsStreamRows,isStreamIdLte,parseClientTempId,predictSharpThumbnailWorkingSetBytes,readDailyReportSseStreamEntry,transformJsonArray});
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));`},Sl=(e,t)=>V.sql`SELECT ${q(e.hubId)} AS ${V.sql.identifier(Le.hubId)}, LOWER(CONVERT(char(64), ${q(e.sourceDigest)}, 2)) AS ${V.sql.identifier(Le.sourceDigest)}, ${q(e.normalizerVersion)} AS ${V.sql.identifier(Le.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${Cr(t)})`,gl=(e,t,r)=>V.sql`SELECT TOP (${r}) ${q(e.id)} AS ${V.sql.identifier(Le.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var bl=e=>({search:async(t,r)=>$e(r.scope.visible)?[]:Lt(await t.execute(yl(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Wt(o[at.sourceType],at.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${at.sourceType} is null`);return{reportHubId:jt(o[at.reportHubId],at.reportHubId),businessDate:Wt(o[at.businessDate],at.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if($e(r.scope.visible))return new Map;let n=Lt(await t.execute(hl(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[Yt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${Yt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(jt(i[Yt.reportHubId],Yt.reportHubId),l)}return a},facetValues:async(t,r)=>$e(r.scope.visible)?[]:Lt(await t.execute(fl(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Wt(o[Mr.value],Mr.value);if(a===null)throw new Error(`[daily-report] search: column ${Mr.value} is null`);return a})});var yt=require("@aiquants/mssql"),Oo=require("drizzle-orm");var Tl=require("crypto");var dm=Object.freeze({authorName:"author",customerName:"customer"}),Lo=e=>e===null?null:Xn(e),Dl=(e,t,r)=>{let n=Lo(r);if(n!==null&&n.length>gt.maxValueLength){let o=gt.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${dm[t]} display value has ${n.length} UTF-16 units after trimming; the host must keep the author and customer display values at most ${o} UTF-16 units`)}return n},kr=e=>e===null?"n;":`s${e.length}:${e}`,Pr="utf16le",pm=e=>{let t=(0,Tl.createHash)("sha256");t.update(`F${e.fields.length};`,Pr);for(let[r,n]of e.fields)t.update(kr(r)+kr(n),Pr);return t.update(`C${e.comments.length};`,Pr),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${kr(r.text)}`,Pr)}),t.update(`P;${kr(Lo(e.filterValues.authorName))}${kr(Lo(e.filterValues.customerName))}`,Pr),t.digest("hex")},No=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=un(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=un(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:ws(r),comments:n,sourceDigest:pm(e),forcedCuts:t,authorName:Dl(e.hubId,"authorName",e.filterValues.authorName),customerName:Dl(e.hubId,"customerName",e.filterValues.customerName)}};var Al=e=>{let t=async(s,c)=>{let d=[];for(let u of(0,yt.chunk)(c,yt.MAX_IN_LIST))for(let h of Lt(await s.execute(pl(e.hub,u))))d.push(jt(h[Le.hubId],Le.hubId));return d},r=async(s,c)=>{for(let d of(0,yt.chunk)(c,yt.MAX_IN_LIST))await s.execute(Rl(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of(0,yt.chunk)(c,yt.MAX_IN_LIST))for(let h of Lt(await s.execute(Sl(e.tables.document,u))))d.set(jt(h[Le.hubId],Le.hubId),{sourceDigest:Wt(h[Le.sourceDigest],Le.sourceDigest),normalizerVersion:Wt(h[Le.normalizerVersion],Le.normalizerVersion)});return d},o=async(s,c,d)=>Lt(await s.execute(gl(e.hub,c,d))).map(u=>jt(u[Le.hubId],Le.hubId)),a=async(s,c)=>{let d=await t(s,[...new Set(c)].sort((h,m)=>h-m));if(d.length===0)return;let u=(await e.loadSources(s,d)).map(No);u.length>0&&await r(s,u)},i=s=>e.inTransaction(async c=>{await c.execute(Oo.sql`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),h=(await e.loadSources(c,d)).map(No),m=h.filter(y=>{let R=u.get(y.hubId);return R===void 0||R.sourceDigest!==y.sourceDigest||R.normalizerVersion!==e.normalizerVersion});return m.length>0&&await r(c,m),await c.execute(Oo.sql`SET DEADLOCK_PRIORITY NORMAL`),{scanned:h.length,written:m.length,forcedCuts:h.reduce((y,R)=>y+R.forcedCuts,0)}});return{writeHubs:a,reconcile:async(s,c)=>{let{batchSize:d,hubIds:u,signal:h,onProgress:m}=c;ce("reconcileSearchIndex: batchSize",d,1,yt.MAX_IN_LIST);let y=ue(),R=u===void 0?null:(0,yt.chunk)([...new Set(u)].sort((f,D)=>f-D),d),p={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let f=0;;f++){h?.throwIfAborted();let D=R===null?await o(s,p.lastHubId===null?0:p.lastHubId,d):R[f];if(D===void 0||D.length===0)break;let w=await i(D);p={scanned:p.scanned+w.scanned,written:p.written+w.written,skipped:p.skipped+w.scanned-w.written,forcedCuts:p.forcedCuts+w.forcedCuts,lastHubId:D[D.length-1]},m?.(p)}return{...p,elapsedMs:ue()-y}}}};var Il=require("@aiquants/fuzzy-search/normalize");var Ho=255,Rn=Object.values(Bt).sort((e,t)=>e-t),mm=new Intl.Segmenter("und",{granularity:"grapheme"}),be=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),ht=5e5,Sn=Math.floor(ht/be.linear),ym=Math.floor(ht/be.segment),El=Math.floor(ht/be.sweep),_l=Math.floor(ht/be.scan),vr=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),xl=(e,t)=>{let r=0,n=t(),o=ht,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+ht,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=ht,a=!1}}},$S=Object.freeze({fits:()=>!0,charge:()=>{}}),Cl=e=>{let t=null;return{step:()=>{if(t!==null)return!0;let r=e.next();return r.done!==!0?!1:(t={result:r.value},!0)},result:()=>{if(t===null)throw new Error("[daily-report] search marks: the walk is not done (step until it returns true)");return t.result}}};var hm=(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},fm=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length;function*Rm(e,t,r,n){let o=!1;for(let c=t;c<r&&!o;c+=Sn){let d=Math.min(r,c+Sn),u=(d-c)*be.linear;n.fits(u)||(yield),o=(0,Il.holdsMultiUnitCluster)(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=mm.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(ym,s.value.segment.length);n.fits(c*be.segment)||(yield);let d=0;for(;!s.done&&d+s.value.segment.length<=c;){let{index:u,segment:h}=s.value;a.fill(t+u,u,u+h.length),i.fill(t+u+h.length,u,u+h.length),d+=h.length,s=l.next()}n.charge(d*be.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var Sm=256,gm=e=>{let t=new Int32Array(e.length),r=0;for(let n=1;n<e.length;n++){for(;r>0&&e.charCodeAt(n)!==e.charCodeAt(r);)r=t[r-1];e.charCodeAt(n)===e.charCodeAt(r)&&r++,t[n]=r}return e.length-t[e.length-1]},bm=e=>{let t=new Map;for(let r of e){if(r.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let n=t.get(r.text);(n===void 0||r.tier<n)&&t.set(r.text,r.tier)}return[...t].map(([r,n])=>{let o=gm(r),a=Math.max(_l-r.length+1,r.length);if(o===r.length)return{text:r,tier:n,periodic:null,windowStarts:a};let i=r.length%o,l=r.slice(i,o)+r.slice(0,i);return{text:r,tier:n,periodic:{period:o,continuation:l.repeat(Math.ceil(Sm/o))},windowStarts:a}})},gn=(e,t)=>{let{pieces:r}=e,n=r[e.lastPiece];if(n.plainStart<=t&&t<n.plainStart+n.text.length)return e.lastPiece;let o=0,a=r.length-1;for(;o<a;){let i=o+a+1>>1;r[i].plainStart<=t?o=i:a=i-1}return t>=r[o].plainStart+r[o].text.length?-1:(e.lastPiece=o,o)},wl=(e,t,r)=>{let n=gn(e,t);return e.pieces[n>=0?n:gn(e,r==="start"?t-1:t+1)]},Ml=(e,t)=>{let r=gn(e,t);if(r<0)return kl(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},kl=(e,t)=>{let r=gn(e,t);if(r<0)return Ml(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},Dm=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),Tm=Object.freeze({kind:"done"}),Fo=Object.freeze({kind:"slice"}),Am=Object.freeze({kind:"clusters"}),Em=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:s,periodic:c}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(be.run))return Fo;let m=wl(e,n.closedStart,"start"),y=wl(e,n.closedEnd-1,"end");if(m.mapped===null)return{kind:"map",piece:m};if(y.mapped===null)return{kind:"map",piece:y};if(e.isCut&&e.clusters===void 0)return Am;let R=t(e.offset+Ml(e,n.closedStart)),p=t(e.offset+kl(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let f=e.clusters;f==null?a(R,p,s):a(f.clusterStarts[R-f.start],f.clusterEnds[p-1-f.start],s),o.charge(be.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(ht))return Fo;let{period:m,continuation:y}=c,R=n.periodicEnd,p=Math.min(i.length,R+Math.max(_l,y.length)),f=R;for(;f+y.length<=p&&i.startsWith(y,f);)f+=y.length;let D=f+y.length>p&&p<i.length;if(!D)for(;f<i.length&&i.charCodeAt(f)===i.charCodeAt(f-m);)f++;if(o.charge((f-R)*be.scan),D){n.periodicEnd=f;continue}n.periodicEnd=-1,n.last+=Math.floor((f-n.last-l.length)/m)*m,n.from=n.last+l.length-m+1;continue}if(n.from<0){if(n.runStart<0)return Tm;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(ht))return Fo;n.from>=n.windowEnd&&(n.windowStart=n.from,n.windowEnd=n.from+r.windowStarts,n.window=i.slice(n.from,n.windowEnd+l.length-1));let d=n.from-n.windowStart,u=n.window.indexOf(l,d);if(u<0){o.charge((n.window.length-d)*be.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*be.scan);let h=n.windowStart+u;(n.runStart<0||h>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=h),n.last=h,c===null?n.from=h+1:n.periodicEnd=h+l.length}};function*$o(e,t,r){let n=Math.floor(ht/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*wm(e,t,r,n,o){if(t.length===0)return;let a=yield*$o(Is(e),be.strip,n),i=[],l=[];yield*$o(_s(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),be.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(be.line)||(yield),n.charge(be.line);let d=i[c],u=a.text.slice(d,l[c]),h=yield*$o(xs(u,r),be.plan,n),m=[],y="";for(let p of h.chunks){let f="",D=[];for(let w of p){let S=(w.end-w.start)*be.normalize;n.fits(S)||(yield);let g=Eo(w.start===0&&w.end===u.length?u:u.slice(w.start,w.end),r).text;n.charge(S),g.length>0&&D.push({start:w.start,end:w.end,text:g,chunkStart:f.length}),f+=g}if(f.length!==0){y.length>0&&(y+=" ");for(let w of D)m.push({start:w.start,end:w.end,text:w.text,plainStart:y.length+w.chunkStart,mapped:null});y+=f}}if(y.length===0)continue;let R={offset:d,plain:y,pieces:m,isCut:!fm(h,u),lastPiece:0,clusters:void 0};for(let p of t){let f=Dm();for(;;){let D=Em(R,s,p,f,n,o);if(D.kind==="done")break;if(D.kind==="slice"){yield;continue}if(D.kind==="clusters"){R.clusters=yield*Rm(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:w}=D,S=(w.end-w.start)*be.map;n.fits(S)||(yield);let g=u.slice(w.start,w.end);w.mapped=hm(Es(g,Ao(g,r)),w.text),n.charge(S)}}}}function*Im(e,t,r,n){let o=new Int32Array(Rn.length),a=0,i=Ho;for(let l=0;l<=e;l+=El){let s=Math.min(e+1,l+El),c=(s-l)*be.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=Ho;for(let h=Rn.length-1;h>=0;h--){let m=Rn[h];o[m]+=t[m][d],o[m]>0&&(u=m)}if(u!==i){if(i!==Ho&&!n(a,d,i))return!1;a=d,i=u}}r.charge(c)}return!0}function*_m(e,t,r,n,o){let a=null;return yield*wm(e,t,r,n,(l,s,c)=>{a===null&&(a=Rn.map(()=>new Int32Array(e.length+1))),a[c][l]++,a[c][s]--}),a===null?!0:yield*Im(e.length,a,n,o)}var xm=(e,t,r,n)=>{let o=bm(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return Cl(function*(){return(yield*_m(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var Pl=(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)},vl=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of va)r(St.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(St.interviewer(o,"name"),n.name),r(St.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(St.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(St.comment(Wn(o),"author"),n.name),r(St.comment(Wn(o),"content"),n.text)});for(let n of e.postedComments)r(St.comment(n.id,"author"),n.userName),r(St.comment(n.id,"content"),n.content);return t};function*Cm(e,t){let r=Gn;for(let n=0;n<e.length;n+=Sn){let o=Math.min(e.length,n+Sn),a=(o-n)*be.linear;t.fits(a)||(yield),r=Kn(r,e,n,o),t.charge(a)}return r}var Ll=async(e,t,r,n)=>{let o=0,a=0,i=async c=>{for(;!c.step();)await r(),n.startSlice();return c.result()},l=async(c,d)=>{if(!d&&a>t.maxRanges)return null;let u={};for(let{key:h,value:m}of c.fields){if(!d&&o+m.length>t.maxUnits)return null;let y=await i(Cl(Cm(m,n))),R=await i(xm(m,c.alternatives,{maxLength:bo,maxRanges:t.maxFieldRanges},n));if(o+=m.length,R.dense){u[h]={fingerprint:y,dense:!0};continue}if(u[h]={fingerprint:y,ranges:R.ranges},a+=R.ranges.length/3,!d&&a>t.maxRanges)return null}return u},s=[];for(let c=0;c<e.length;c++){let d=e[c],u=await l(d,s.length===0);if(u===null)return{reports:s,deferred:e.slice(c).map(h=>h.reportHubId)};s.push({reportHubId:d.reportHubId,matchedSets:d.matchedSets,fields:u})}return{reports:s,deferred:[]}};var Be=require("drizzle-orm");var Ue=require("drizzle-orm");var wt=e=>(0,Ue.getColumns)(e),ke=(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"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},Nl=e=>{let{db:t,tables:r,encodeUserId:n,settings:o,draftVisibilityTables:a}=e,{hub:i,label:l}=r,{externalSources:s,draftLabelNames:c,canonicalDraftLabelName:d}=o,u=I=>wr(i.sourceType,I),h=(I,L)=>fn(a,I,c,L),m=Ue.sql`CASE WHEN ${hn(a,c)} THEN 1 ELSE 0 END`,y=async I=>{let[L]=await t.select({id:i.id}).top(1).from(i).where((0,Ue.and)((0,Ue.eq)(i.id,I),hn(a,c)));return L!==void 0},R=I=>I==null||I===""?null:/^\d+$/.test(I)?n(Number(I)):I,p=()=>{let I={};for(let L of s)I[`ext_${L.sourceType}`]=wt(L.table);return I},f=I=>{let L=I;for(let x of s)L=L.leftJoin(x.table,(0,Ue.and)((0,Ue.eq)(i.sourceType,x.sourceType),(0,Ue.eq)(i.sourceIdNum,x.idColumn)));return L},D=I=>{let{hub:L,internal:x}=I,j=L.summary,X=[],J=null,$=null,_=null,B=null,Y=null,pe=null,ie=[],me=s.find(Z=>Z.sourceType===L.sourceType),De=me?I[`ext_${me.sourceType}`]:void 0;if(me&&De){let Z=me.mapRow(De);Z.content!==void 0&&(j=Z.content),Z.employeeName!==void 0&&(pe=Z.employeeName),Z.category!==void 0&&(J=Z.category),Z.creationCategory!==void 0&&($=Z.creationCategory),Z.visitTimeFrom!==void 0&&(_=Z.visitTimeFrom),Z.visitTimeTo!==void 0&&(B=Z.visitTimeTo),Z.customerName!==void 0&&(Y=Z.customerName),Z.interviewers!==void 0&&(X=Z.interviewers),Z.externalComments!==void 0&&(ie=Z.externalComments)}else L.sourceType===ze&&x&&(j=x.body);return{content:j,author:I.creatorName??R(L.createdBy)??"",employeeName:pe??I.creatorName??R(L.createdBy),updatedBy:R(L.updatedBy),category:J,creationCategory:$,visitTimeFrom:_,visitTimeTo:B,customerName:Y,interviewers:X,externalComments:ie}},w=I=>{if(I===1)return!0;if(I===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${Ht(I)}`)},S=I=>I.creationCategory!==null&&c.includes(I.creationCategory),g=(I,L)=>w(I.hasDraftLabel)?!0:S(L),M=async I=>{let[L]=await I.select({id:l.id}).top(1).from(l).where((0,Ue.eq)(l.name,d)).orderBy((0,Ue.asc)(l.id));return L===void 0?null:L.id},T=()=>M(t);return{visibleSourceTypeCondition:u,draftVisibleTo:h,draftLabelFlag:m,isDraftReport:y,externalSelections:p,applyExternalJoins:f,resolveHubDisplayFields:D,readCanonicalDraftLabelId:M,getDraftLabelId:T,resolveCreationCategoryDraftLabelId:I=>I.some(S)?T():Promise.resolve(null),mapHubRecord:(I,L,x,j,X)=>{let{hub:J}=L,$=L.labels.map(Y=>({id:Y.id,name:Y.name,color:Y.color})),_=L.postedCommentRows,B=Me(I.commentable,J.sourceType);return j!==null&&S(x)&&!$.some(Y=>Y.id===j)&&$.push({id:j,name:d,color:null}),{reportHubId:J.id,date:ke(J.businessDate,"YYYY-MM-DD"),author:x.author,userId:J.userId?n(J.userId):"",sourceType:J.sourceType,createdAt:ke(J.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:ke(J.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:x.updatedBy,employeeName:x.employeeName,category:x.category,creationCategory:x.creationCategory,visitTimeFrom:x.visitTimeFrom,visitTimeTo:x.visitTimeTo,customerName:x.customerName,interviewers:x.interviewers,subject:J.title,content:x.content,externalComments:B?x.externalComments:[],isRead:L.isRead??!1,isStarred:L.isStarred??!1,readContentDigest:L.readContentDigest??null,isDraft:g(L,x),labels:$,postedComments:_.filter(Y=>ys({authorUserId:Y.userId},J.sourceType,X,I)).map(Y=>({...Y,userId:n(Y.userId),isMine:X?Y.userId===X:!1})),attachments:L.attachments}}}};var Ol=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r})=>{let{db:n,tables:o,logger:a,settings:i}=e,{hub:l}=o,{attachmentDelivery:s}=i,c=(y,R)=>R!=null?"absent":y!=null?"present":"unknown";return{getAttachmentsByHubIds:async y=>{let R=new Map,p=o.attachment;if(y.length===0||!p||s===null)return R;let f=s.idCodec,D=s.thumbnails!==null,w=await n.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,Be.inArray)(p.hubId,y)).orderBy((0,Be.asc)(p.createdAt),(0,Be.asc)(p.id));for(let S of w){let g=S.fileType?String(S.fileType):null,M=S.fileSize!=null?Number(S.fileSize):null,T=c(S.objectCheckedAt,S.objectMissingAt),C={id:f.encode(Number(S.id)),fileName:String(S.fileName),fileType:g,fileSize:M,createdAt:ke(S.createdAt,"YYYY-MM-DD HH:mm:ss"),state:T,hasThumbnail:D&&T!=="absent"&&Zr({fileType:g,fileSize:M},s.maxBytes)},H=R.get(Number(S.hubId));H?H.push(C):R.set(Number(S.hubId),[C])}return R},getAttachmentForUser:async(y,R,p)=>{let f=o.attachment;return!f||$e(y.visible)?null:(await n.select({fileName:f.fileName,filePath:f.filePath,fileType:f.fileType,fileSize:f.fileSize}).top(1).from(f).innerJoin(l,(0,Be.eq)(l.id,f.hubId)).where((0,Be.and)((0,Be.eq)(f.id,R),(0,Be.isNull)(l.deletedAt),t(p,"author"),r(y.visible))))[0]??null},markAttachmentMissing:async y=>{let R=o.attachment;if(!R)return;let p=new Date;try{await n.update(R).set({objectCheckedAt:p,objectMissingAt:p,updatedAt:p}).where((0,Be.eq)(R.id,y))}catch(f){a.error("markAttachmentMissing failed",f)}},markAttachmentPresent:async y=>{let R=o.attachment;if(!R)return;let p=new Date;try{await n.update(R).set({objectCheckedAt:p,objectMissingAt:null,updatedAt:p}).where((0,Be.eq)(R.id,y))}catch(f){a.error("markAttachmentPresent failed",f)}}}};var bn=require("drizzle-orm");var zt=require("drizzle-orm"),ir=async(e,t,r,n)=>{if((await e.update(t).set({deletedAt:null}).output().where((0,zt.and)((0,zt.eq)(t.id,r),(0,zt.isNull)(t.deletedAt),n===null?void 0:(0,zt.eq)(t.userId,n)))).length===0)throw new Error("Not Found")};var Hl=(e,{isDraftReport:t,assertHubMutable:r,incrementRedisEpoch:n})=>{let{db:o,tables:a,users:i,encodeUserId:l,cache:s,inTransaction:c,prepareSearchIndex:d,publishToSseStream:u}=e,{dateEpochPrefix:h,detailEpochPrefix:m}=e.settings.redisKeys,{hub:y,comment:R}=a,p=async(S,g)=>{if(g!==null)return await t(S)?g:void 0},f=async(S,g,M,T,C,H)=>{let I=await r(S,M,g);if(!Me(S.commentable,I.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(I.sourceType.toLowerCase()!==ze.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let L=await p(M,I.userId),x=await d(),j=await c(async _=>{await ir(_,y,M,null);let[B]=await _.insert(R).output().values({hubId:M,userId:g,body:T,createdAt:new Date,createdBy:String(g),updatedAt:new Date,updatedBy:String(g)});return x!==null&&await x.writeHubs(_,[M]),B}),[X]=await o.select({displayName:i.displayName}).top(1).from(i).where((0,bn.eq)(i.id,g)),J=X?.displayName??"";if(C){let _=We(C);_&&(s.invalidatePrefix(nr(_)),await n(`${h}${_}`))}s.invalidatePrefix(Ze(M)),await n(`${m}${M}`);let $={id:j.id,userId:l(j.userId),userName:J,content:j.body,createdAt:ke(j.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(Hn.parse({type:"comment-add",reportHubId:M,comment:$,clientTempId:H,recipientRawUserId:L,sourceType:I.sourceType}),"addComment"),$},D=async(S,g)=>await S.select().top(1).from(R).where((0,bn.eq)(R.id,g));return{addComment:f,deleteComment:async(S,g,M,T,C,H)=>{let I=await D(o,T);if(I.length===0)throw new Error("Not Found");if(I[0].hubId!==M)throw new Error("Not Found");let L=await r(S,I[0].hubId,g);if(I[0].userId!==g)throw new Error("Unauthorized");let x=await p(M,L.userId),j=await d();if(await c(async X=>{await ir(X,y,M,null),await X.delete(R).where((0,bn.eq)(R.id,T)),j!==null&&await j.writeHubs(X,[M])}),C){let X=We(C);X&&(s.invalidatePrefix(nr(X)),await n(`${h}${X}`))}s.invalidatePrefix(Ze(M)),await n(`${m}${M}`),await u(Fn.parse({type:"comment-delete",reportHubId:M,commentId:T,clientTempId:H,recipientRawUserId:x,sourceType:L.sourceType}),"deleteComment")}}};var Ge=require("drizzle-orm");var Fl=e=>e===ze;var $l=e=>e===""?null:e,Ul=(e,{readCanonicalDraftLabelId:t,isDraftReport:r,getDailyReportDetailById:n,assertHubMutable:o,incrementRedisEpoch:a})=>{let{db:i,tables:l,cache:s,logger:c,inTransaction:d,prepareSearchIndex:u,publishToSseStream:h,settings:m,draftVisibilityTables:y}=e,{idsEpoch:R,dateEpochPrefix:p,detailEpochPrefix:f}=e.settings.redisKeys,{hub:D,internal:w,hubLabel:S,userStatus:g}=l,{canonicalDraftLabelName:M,draftLabelNames:T}=m,C=async($,_,B,Y)=>{if(!Hr(B))throw Q("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",B);if(!Me($.visible,ze))throw new Error("Forbidden");c.info("createDailyReport called",{userId:_,businessDate:B});let pe=await u();try{let ie=await d(async b=>{c.info("Starting transaction");let O=await t(b);if(O===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(M)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let N=`internal-temp-${Date.now()}-${Math.random()}`,[v]=await b.insert(D).output().values({sourceType:ze,sourceId:N,businessDate:new Date(`${B}T00:00:00Z`),userId:_,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(_),updatedAt:new Date,updatedBy:String(_)});return await b.update(D).set({sourceId:String(v.id)}).where((0,Ge.eq)(D.id,v.id)),c.info("Hub created",v),await b.insert(w).values({hubId:v.id,body:"",createdAt:new Date,createdBy:String(_),updatedAt:new Date,updatedBy:String(_)}),c.info("Internal created"),await b.insert(S).values({hubId:v.id,labelId:O,createdAt:new Date,createdBy:String(_)}),c.info("Label assigned"),await b.insert(g).values({hubId:v.id,userId:_,isRead:!0,isStarred:!1,createdAt:new Date,createdBy:String(_),updatedAt:new Date,updatedBy:String(_),readContentDigest:null}),pe!==null&&await pe.writeHubs(b,[v.id]),v.id});s.invalidatePrefix(or(B,_)),s.invalidatePrefix(Co(_)),await a(R),await a(`${p}${B}`);let me=await n(Xe.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),ie,_,{forceRefresh:!0});if(me===null)throw new Error(`[daily-report] createDailyReport: report ${ie} was committed but its detail read returned nothing`);let De=await r(me.reportHubId);await h(Bn.parse({type:"report-create",reportHubId:me.reportHubId,report:me,clientTempId:Y,recipientRawUserId:De?_:void 0,actorRawUserId:_}),"createDailyReport");let Z=await n($,ie,_,{forceRefresh:!0});if(Z===null)throw new Error(`[daily-report] createDailyReport: the actor's scope cannot read report ${ie} it just created`);return Z}catch(ie){throw c.error("Error in createDailyReport",ie),ie}},H=async($,_)=>await $.select().top(1).from(D).where((0,Ge.eq)(D.id,_)),I=async($,_,B)=>{await o($,_,B);let[Y]=await H(i,_);if(Y===void 0||Y.deletedAt)throw new Error("Not Found");if(!Fl(Y.sourceType))throw new Error("Forbidden");if(Y.userId!==B)throw new Error("Unauthorized");return Y},L=async($,_,B)=>{await $.update(D).set(B).where((0,Ge.eq)(D.id,_))},x=async($,_,B)=>{await $.update(w).set(B).where((0,Ge.eq)(w.hubId,_))};return{createDailyReport:C,updateDailyReport:async($,_,B,Y,pe)=>{let ie=await I($,_,B),me=await u();await d(async b=>{await ir(b,D,_,B),Y.title!==void 0&&await L(b,_,{title:$l(Y.title),updatedAt:new Date,updatedBy:String(B)}),Y.content!==void 0&&await x(b,_,{body:$l(Y.content),updatedAt:new Date,updatedBy:String(B)}),me!==null&&await me.writeHubs(b,[_])}),s.invalidatePrefix(Ze(_)),await a(`${f}${_}`);let De=We(ke(ie.businessDate,"YYYY-MM-DD"));De&&(s.invalidatePrefix(nr(De)),await a(`${p}${De}`));let Z=await n(Xe.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),_,B,{forceRefresh:!0});if(Z){let b=await r(_);await h(Vn.parse({type:"report-update",reportHubId:Z.reportHubId,report:Z,clientTempId:pe,recipientRawUserId:b?B:void 0,actorRawUserId:B}),"updateDailyReport")}},publishDailyReport:async($,_,B,Y)=>{let pe=await I($,_,B),ie=await u();if(await d(async b=>{await ir(b,D,_,B),await b.delete(S).where((0,Ge.and)((0,Ge.eq)(S.hubId,_),ul(y,T))),ie!==null&&await ie.writeHubs(b,[_])}),s.invalidatePrefix(Ze(_)),s.invalidatePrefix(Pt),await a(R),pe.businessDate){let b=We(ke(pe.businessDate,"YYYY-MM-DD"));b&&await a(`${p}${b}`)}let me=We(ke(pe.businessDate,"YYYY-MM-DD"));me&&s.invalidatePrefix(or(me,B));let De=await n(Xe.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),_,B,{forceRefresh:!0});if(De===null)return null;let Z=await r(_);return await h(qn.parse({type:"report-publish",reportHubId:De.reportHubId,report:De,clientTempId:Y,recipientRawUserId:Z?B:void 0,actorRawUserId:B}),"publishDailyReport"),await n($,_,B,{forceRefresh:!0})},deleteDailyReport:async($,_,B,Y)=>{let pe=await I($,_,B);if(await d(async ie=>{if((await ie.update(D).set({deletedAt:new Date,deletedBy:String(B),updatedAt:new Date,updatedBy:String(B)}).output().where((0,Ge.and)((0,Ge.eq)(D.id,_),(0,Ge.eq)(D.userId,B),(0,Ge.isNull)(D.deletedAt)))).length===0)throw new Error("Not Found")}),s.invalidatePrefix(Ze(_)),s.invalidatePrefix(Pt),await a(R),pe.businessDate){let ie=We(ke(pe.businessDate,"YYYY-MM-DD"));ie&&await a(`${p}${ie}`)}await h(Ur.parse({type:"report-delete",reportHubId:_,clientTempId:Y,sourceType:pe.sourceType}),"deleteDailyReport")}}};var K=require("drizzle-orm");var Vl=require("crypto"),ft="utf16le",Mm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Dn=(e,t)=>{if(typeof t=="string"){e.update(`s${t.length}:`,ft),e.update(t,ft);return}if(t==null){e.update("n;",ft);return}if(typeof t=="number"){let n=String(t);e.update(`i${n.length}:${n}`,ft);return}if(typeof t=="boolean"){e.update(t?"t;":"f;",ft);return}let r=JSON.stringify(t);e.update(`j${r.length}:${r}`,ft)},Bl=(e,t,r)=>{if(!Array.isArray(t)){e.update("l",ft),Dn(e,t);return}e.update(`a${t.length};`,ft);for(let n of t)if(Mm(n)){e.update("o",ft);for(let o of r)Dn(e,n[o])}else e.update("v",ft),Dn(e,n)},km=["name","affiliation"],Pm=["fileName","fileSize","createdAt"],Uo=e=>{let t=(0,Vl.createHash)("sha256");for(let r of[e.subject,e.content,e.date,e.category,e.creationCategory,e.visitTimeFrom,e.visitTimeTo,e.customerName])Dn(t,r);return Bl(t,e.interviewers,km),Bl(t,e.attachments,Pm),t.digest("hex")},Bo=e=>{let{subject:t,content:r,date:n,category:o,creationCategory:a,visitTimeFrom:i,visitTimeTo:l,customerName:s,interviewers:c,attachments:d}=e,u=JSON.parse(JSON.stringify({subject:t,content:r,date:n,category:o,creationCategory:a,visitTimeFrom:i,visitTimeTo:l,customerName:s,interviewers:c,attachments:d}));return{...e,contentDigest:Uo(u)}};var ql=Vr([]),vm=6e4,qo=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw Je(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw Q(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw Je(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw Q(`${e}: options.signal`,r,n);return n},jo=e=>{let t=async()=>{await new Promise(r=>setImmediate(r)),e.throwIfAborted()};return{sliceMs:vr.sliceMs,now:ue,pause:t}},Vo=e=>{try{return{ok:!0,value:e()}}catch(t){return{ok:!1,cause:t}}},Lm=e=>Vo(()=>{let t=JSON.parse(JSON.stringify(e)),r=Rr.safeParse({...t,contentDigest:Uo(t)});if(!r.success)throw new Error(`[daily-report] the detail does not match the delivered detail schema (${Oa(r.error)})`);return r.data}),jl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r,draftLabelFlag:n,externalSelections:o,applyExternalJoins:a,resolveHubDisplayFields:i,resolveCreationCategoryDraftLabelId:l,mapHubRecord:s,getAttachmentsByHubIds:c,readSseStreamAnchor:d,incrementRedisEpoch:u})=>{let{db:h,tables:m,users:y,resolveUserId:R,cache:p,epochs:f,logger:D,settings:w}=e,{idsEpoch:S,dateEpochPrefix:g,detailEpochPrefix:M}=e.settings.redisKeys,{hub:T,internal:C,comment:H,label:I,hubLabel:L,userStatus:x}=m,j=w.idsTtlMs,X=w.businessDateTtlMs,J=async(k,P)=>(await h.select({reportHubId:T.id,businessDate:T.businessDate,sourceType:T.sourceType}).from(T).where((0,K.and)((0,K.isNull)(T.deletedAt),t(P,"author-or-authorless"),r(k.visible))).orderBy((0,K.desc)(T.businessDate),(0,K.desc)(T.id))).map(U=>({...U,businessDate:ke(U.businessDate,"YYYY-MM-DD")})),$=async(k,P,E)=>{let U=await B(P);return U?$e(k.visible)?[]:(await h.select({reportHubId:T.id,businessDate:T.businessDate,sourceType:T.sourceType}).top(E).from(T).where((0,K.and)((0,K.isNull)(T.deletedAt),t(U,"author-or-authorless"),r(k.visible))).orderBy((0,K.desc)(T.businessDate),(0,K.desc)(T.id))).map(Se=>({...Se,businessDate:ke(Se.businessDate,"YYYY-MM-DD")})):[]},_=new Map,B=async k=>{if(!w.disableUserIdCache&&_.has(k))return _.get(k)??null;let P=await R(k);return P!==null&&!w.disableUserIdCache&&_.set(k,P),P},Y=async(k,P,{forceRefresh:E=!1,snapshot:U=!1,ttlMsOverride:W,onFetchStart:Se,admission:Fe}={})=>{let Ie=await B(P);if(!Ie)return{items:[],streamAnchor:null,snapshot:ql};if($e(k.visible))return{items:[],streamAnchor:await d(),snapshot:ql};let Re=Hs(Ie,an(k)),[Te]=await p.getOrFetch({cacheKey:Re,fetcher:async()=>{let Ke=await d(),it=await J(k,Ie);if(!Ca(it)){D.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=[...it].sort(jn);return[{items:oe,streamAnchor:Ke,snapshot:Vr(oe)}]}return[{items:it,streamAnchor:Ke,snapshot:Vr(it)}]},onFetchStart:Se,forceRefresh:E,snapshot:U,admission:Fe,ttlMsOverride:W??j,epochKey:S,refreshAheadRatio:.5});if(Te===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return Te},pe=async(k,P,E)=>{let U=await a(h.select({hub:wt(T),internal:wt(C),isRead:x.isRead,isStarred:x.isStarred,readContentDigest:x.readContentDigest,creatorName:y.displayName,hasDraftLabel:n,...o()}).from(T)).leftJoin(C,(0,K.eq)(T.id,C.hubId)).leftJoin(x,(0,K.and)((0,K.eq)(T.id,x.hubId),(0,K.eq)(x.userId,P))).leftJoin(y,(0,K.eq)(T.userId,y.id)).where((0,K.and)(E,(0,K.isNull)(T.deletedAt),t(P,"author"),r(k.visible))).orderBy((0,K.desc)(T.id));if(U.length===0)return[];let W=U.map(oe=>oe.hub.id),Se=await h.select({hubId:L.hubId,id:I.id,name:I.name,color:I.color}).from(L).innerJoin(I,(0,K.eq)(L.labelId,I.id)).where((0,K.inArray)(L.hubId,W)),Fe=await h.select({hubId:H.hubId,id:H.id,body:H.body,createdAt:H.createdAt,userId:H.userId,userName:y.displayName}).from(H).leftJoin(y,(0,K.eq)(H.userId,y.id)).where((0,K.inArray)(H.hubId,W)).orderBy((0,K.asc)(H.createdAt)),Ie=await c(W),Re=new Map,Te=new Map;for(let oe of Se){let Ne=Re.get(oe.hubId);Ne||(Ne=[],Re.set(oe.hubId,Ne)),Ne.push({id:oe.id,name:oe.name,color:oe.color})}for(let oe of Fe){let Ne=Te.get(oe.hubId);Ne||(Ne=[],Te.set(oe.hubId,Ne)),Ne.push({id:oe.id,content:oe.body,createdAt:ke(oe.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:oe.userId,userName:oe.userName||""})}let Ke=U.map(oe=>Vo(()=>i(oe))),it=await l(Ke.flatMap(oe=>oe.ok?[oe.value]:[]));return U.map((oe,Ne)=>{let Rt=oe.hub.id,Nt=Ke[Ne],It=Nt.ok?Vo(()=>s(k,{...oe,attachments:Ie.get(Rt)??[],labels:Re.get(Rt)||[],postedCommentRows:Te.get(Rt)||[]},Nt.value,it,P)):Nt;return It.ok?{reportHubId:Rt,outcome:"ok",report:It.value}:{reportHubId:Rt,outcome:"failed",cause:It.cause}})},ie=async(k,P,E)=>(await pe(k,P,E)).map(U=>{if(U.outcome==="failed")throw U.cause;return Bo(U.report)}),me=k=>ve({windowMs:vm,tallies:["failed"],writeSuppressed:(P,{count:E,since:U})=>{D.warn(`failed_report_suppressed count=${E} since=${U} read=${k} report=${P}`)}}),De={markDailyReportSearchHits:me("markDailyReportSearchHits"),getDailyReportDetailsByIdsByExternalId:me("getDailyReportDetailsByIdsByExternalId")},Z=(k,P,E)=>{De[k].record(P,"failed",()=>D.error(`${k}: report ${P} passed the visibility predicate but its own assembly failed`,E))},b=(k,P)=>{let E=P.outcome==="ok"?Lm(P.report):{ok:!1,cause:P.cause};return E.ok?{reportHubId:P.reportHubId,outcome:"ok",report:E.value}:(Z(k,P.reportHubId,E.cause),{reportHubId:P.reportHubId,outcome:"failed"})},O=async(k,P,E,{read:U,signal:W,slicing:Se})=>{let Fe=await pe(k,P,(0,K.inArray)(T.id,[...E]));W.throwIfAborted();let Ie=[],Re=Se.now();for(let Te of Fe)Ie.length>0&&Se.now()-Re>=Se.sliceMs&&(await Se.pause(),Re=Se.now()),Ie.push(b(U,Te));return Ie},N=async(k,P,E,{forceRefresh:U=!1,snapshot:W=!1,ttlMsOverride:Se,admission:Fe}={})=>{let Ie=await B(E);if(!Ie)return[];let Re=We(P);if(!Re)return[];if($e(k.visible))return[];let Te=Fs(Re,Ie,an(k));return p.getOrFetch({cacheKey:Te,fetcher:()=>ie(k,Ie,(0,K.eq)(T.businessDate,K.sql`${Re}`)),forceRefresh:U,snapshot:W,admission:Fe,ttlMsOverride:Se??X,epochKey:`${g}${Re}`})},v=async(k,P,E,{forceRefresh:U=!1,snapshot:W=!1,ttlMsOverride:Se,admission:Fe}={})=>{if($e(k.visible))return null;let Ie=$s(P,E,an(k));return(await p.getOrFetch({cacheKey:Ie,fetcher:async()=>{let Te=await a(h.select({hub:wt(T),internal:wt(C),isRead:x.isRead,isStarred:x.isStarred,readContentDigest:x.readContentDigest,creatorName:y.displayName,hasDraftLabel:n,...o()}).from(T)).leftJoin(C,(0,K.eq)(T.id,C.hubId)).leftJoin(x,(0,K.and)((0,K.eq)(T.id,x.hubId),(0,K.eq)(x.userId,E))).leftJoin(y,(0,K.eq)(T.userId,y.id)).where((0,K.and)((0,K.eq)(T.id,P),(0,K.isNull)(T.deletedAt),t(E,"author"),r(k.visible)));if(Te.length===0)return[];let Ke=Te[0].hub.id,it=await h.select({id:I.id,name:I.name,color:I.color}).from(L).innerJoin(I,(0,K.eq)(L.labelId,I.id)).where((0,K.eq)(L.hubId,Ke)),oe=await h.select({id:H.id,body:H.body,createdAt:H.createdAt,userId:H.userId,userName:y.displayName}).from(H).leftJoin(y,(0,K.eq)(H.userId,y.id)).where((0,K.eq)(H.hubId,Ke)).orderBy((0,K.asc)(H.createdAt)),Ne=await c([Ke]),Rt=it.map(et=>({id:et.id,name:et.name,color:et.color})),Nt=oe.map(et=>({id:et.id,content:et.body,createdAt:ke(et.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:et.userId,userName:et.userName||""})),It=i(Te[0]),_n=await l([It]);return[Bo(s(k,{...Te[0],attachments:Ne.get(Ke)??[],labels:Rt,postedCommentRows:Nt},It,_n,E))]},forceRefresh:U,snapshot:W,admission:Fe,ttlMsOverride:Se??X,epochKey:`${M}${P}`}))[0]??null};return{getUserIdByExternalId:B,getDailyReportIdsByExternalId:Y,getDailyReportIdsFirstPageByExternalId:$,getDailyReportsByBusinessDateByExternalId:N,getDailyReportDetailById:v,getDailyReportDetailByIdByExternalId:async(k,P,E,U={})=>{let W=await B(E);return W?v(k,P,W,U):null},getDailyReportDetailsByIdsByExternalId:async(k,P,E,U)=>{let W=qo("getDailyReportDetailsByIdsByExternalId",U);if(P.length>Pe.maxDetailIds)throw Q("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${Pe.maxDetailIds} ids`,P.length);let Se=await B(E);if(!Se||P.length===0||$e(k.visible))return P.map(gr);W.throwIfAborted();let Fe=await O(k,Se,P,{read:"getDailyReportDetailsByIdsByExternalId",signal:W,slicing:jo(W)}),Ie=new Map(Fe.map(Re=>[Re.reportHubId,Re]));return P.map(Re=>{let Te=Ie.get(Re);return Te===void 0?gr(Re):Te})},fetchDeliveredHubOutcomes:O,invalidateHubReadCaches:async(k,P)=>{p.invalidatePrefix(Pt),await u(S);for(let E of new Set(k))p.invalidatePrefix(Ze(E)),await u(`${M}${E}`);for(let E of new Set(P)){let U=We(E);U&&await u(`${g}${U}`)}},clearCache:async()=>{p.clearAll(),_.clear(),f&&await u(S),D.info("Server-side DB/SQL caches cleared successfully.")}}};var Nm="v5",Om=/^(?!:)[^\s\p{Cc}]+(?<!:)$/u,Tn=e=>{if(typeof e!="string"||!Om.test(e))throw Q("redisKeyPrefix",'a Redis key prefix of one or more characters without whitespace or control characters, neither starting nor ending with ":"',e);return Object.freeze({sseStream:`${e}:sse-stream:${Nm}`,idsEpoch:`${e}:ids:epoch`,dateEpochPrefix:`${e}:date-epoch:`,detailEpochPrefix:`${e}:detail-epoch:`})};var An=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,redisKeyPrefix:"daily-report",streamMaxLen:1e4}),Hm=e=>{let{length:t}=e;if(t===void 0)throw Q("tables.hub.title","a character column with a declared length",t);return ce("tables.hub.title.length",t,1)},Fm=e=>{if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0)||new Set(e).size!==e.length)throw Q("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},$m=e=>{let t=new Map([[ze.toLowerCase(),`the internal source type ${JSON.stringify(ze)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw Q(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([ze,...e.map(r=>r.sourceType)])},Um=e=>{let t=e===void 0?void 0:e.getSQLType();if(t!=="char(64)")throw Q("tables.userStatus.readContentDigest","a char(64) column (the version the viewer marked read, 64 lowercase hex digits)",t)},Wl=e=>{let t=e.externalSources??[],r=Fm(e.draftLabelNames);if(tn(e),Object.hasOwn(e,"streamKey"))throw Je("redisKeyPrefix","given in place of the removed key streamKey");let n=Gi(e.attachments),o=Hm(e.tables.hub.title);So(e.tables.hub.sourceType),Um(e.tables.userStatus.readContentDigest);let a=Oe("idsTtlMs",e.idsTtlMs,1,An.idsTtlMs),i=Oe("businessDateTtlMs",e.businessDateTtlMs,1,An.businessDateTtlMs),l=Oe("streamMaxLen",e.streamMaxLen,1,An.streamMaxLen),s=Tn(e.redisKeyPrefix===void 0?An.redisKeyPrefix:e.redisKeyPrefix);return Object.freeze({externalSources:t,sourceTypes:$m(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamMaxLen:l,redisKeys:s,disableUserIdCache:!!e.disableUserIdCache})};var Yl=({redis:e,logger:t,epochs:r,streamKey:n,streamMaxLen:o})=>({incrementRedisEpoch:s=>r.incrementEpoch(s),publishToSseStream:async(s,c)=>{let d=await e?.getClient();if(!d){t.warn(`[SSE] Redis client unavailable (${c})`);return}let u=JSON.stringify(s),h=Buffer.byteLength(u);if(h>6356992){t.warn(`[SSE] Event too large (${c}): ${h} bytes > ${6356992}; not published`);return}let m=ue();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let y=ue()-m;y>1e3&&t.warn(`[SSE] Slow publish (${c}): ${y}ms`)}catch(y){t.error(`[SSE] Redis publish failed (${c}):`,y)}},readSseStreamAnchor:async()=>{try{let s=await e?.getClient();if(s===void 0)return null;let[c]=await s.xRevRange(n,"+","-",{COUNT:1});return c===void 0?Ct:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});var ae=require("drizzle-orm");var En=["hubId","userId","isRead","isStarred","createdAt","createdBy","updatedAt","updatedBy","readContentDigest"],Vm={isRead:{statusType:"read",callerName:"setReadStatus"},isStarred:{statusType:"star",callerName:"setStarStatus"}},Ve=e=>ae.sql`${ae.sql.identifier(e.name)}`,qm=(e,t)=>{let{reportHubId:r,userId:n,value:o,at:a}=t,i=String(n),l=Ve(e[t.flag]),s=Ve(e.readContentDigest),c=t.flag==="isRead"?t.readContentDigest:null,d=t.flag==="isRead"?ae.sql`t.${l} = ${o} AND (t.${s} = ${c} OR (t.${s} IS NULL AND ${c} IS NULL))`:ae.sql`t.${l} = ${o}`,u=(f,D)=>ae.sql`t.${Ve(f)} = CASE WHEN ${d} THEN t.${Ve(f)} ELSE ${D} END`,h={hubId:ae.sql`s.${Ve(e.hubId)}`,userId:ae.sql`s.${Ve(e.userId)}`,isRead:ae.sql`${t.flag==="isRead"?o:!1}`,isStarred:ae.sql`${t.flag==="isStarred"?o:!1}`,createdAt:ae.sql`${a}`,createdBy:ae.sql`${i}`,updatedAt:ae.sql`${a}`,updatedBy:ae.sql`${i}`,readContentDigest:ae.sql`${c}`},m=ae.sql.join(En.map(f=>Ve(e[f])),ae.sql`, `),y=ae.sql.join(En.map(f=>h[f]),ae.sql`, `),R=ae.sql.join(En.map(f=>ae.sql`inserted.${Ve(e[f])} AS ${ae.sql.identifier(f)}`),ae.sql`, `),p=t.flag==="isRead"?ae.sql`, t.${s} = ${c}`:ae.sql``;return ae.sql`MERGE ${e} WITH (HOLDLOCK) AS t USING (SELECT ${r} AS ${Ve(e.hubId)}, ${n} AS ${Ve(e.userId)}) AS s ON t.${Ve(e.hubId)} = s.${Ve(e.hubId)} AND t.${Ve(e.userId)} = s.${Ve(e.userId)}
12
+ WHEN MATCHED THEN UPDATE SET t.${l} = ${o}${p}, ${u(e.updatedAt,a)}, ${u(e.updatedBy,i)}
13
+ WHEN NOT MATCHED THEN INSERT (${m}) VALUES (${y})
14
+ OUTPUT ${R};`},zl=(e,t)=>(typeof e=="number"||typeof e=="string")&&String(e)===String(t),Gl=e=>e instanceof Date||typeof e=="string",jm=e=>{if(!Array.isArray(e))return`recordset ${Ht(e)}`;if(e.length!==1)return`${e.length} rows`;let[t]=e;return typeof t!="object"||t===null?`a row of ${Ht(t)}`:En.map(r=>`${r}=${Ht(t[r])}`).join(", ")},Wm=(e,{reportHubId:t,userId:r})=>{let n=typeof e=="object"&&e!==null?e.recordset:void 0,o=Array.isArray(n)&&n.length===1?n[0]:void 0,a=typeof o=="object"&&o!==null?o:void 0;if(a===void 0||!zl(a.hubId,t)||!zl(a.userId,r)||typeof a.isRead!="boolean"||typeof a.isStarred!="boolean"||!Gl(a.createdAt)||!Gl(a.updatedAt)||typeof a.createdBy!="string"||typeof a.updatedBy!="string"||!(a.readContentDigest===null||Ft(a.readContentDigest)))throw new Error(`[daily-report] user status: the upsert must output the one status row of report ${t} and user ${r}; got ${jm(n)}`);return{hubId:t,userId:r,isRead:a.isRead,isStarred:a.isStarred,createdAt:a.createdAt,createdBy:a.createdBy,updatedAt:a.updatedAt,updatedBy:a.updatedBy,readContentDigest:a.readContentDigest}},Kl=(e,{draftVisibleTo:t,incrementRedisEpoch:r})=>{let{db:n,tables:o,cache:a,publishToSseStream:i}=e,{dateEpochPrefix:l,detailEpochPrefix:s}=e.settings.redisKeys,{hub:c,userStatus:d}=o,u=async(p,f)=>{let[D]=await n.select({sourceType:c.sourceType,userId:c.userId,deletedAt:c.deletedAt}).top(1).from(c).where((0,ae.and)((0,ae.eq)(c.id,p),t(f,"author")));return D??null},h=async(p,f,D)=>{let w=await u(f,D);if(!w||w.deletedAt||!Me(p.visible,w.sourceType))throw new Error("Not Found");return{sourceType:w.sourceType,userId:w.userId}},m=async(p,f,D,w)=>{let{reportHubId:S,userId:g}=D;await h(p,S,g);let M=Wm(await n.execute(qm(d,D)),D);if(f){let H=We(f);H&&(a.invalidatePrefix(or(H,g)),await r(`${l}${H}`))}a.invalidatePrefix(Mo(S,g)),await r(`${s}${S}`);let{statusType:T,callerName:C}=Vm[D.flag];return await i(On.parse({type:"status-update",reportHubId:S,recipientRawUserId:g,statusType:T,value:D.value,readContentDigest:M.readContentDigest,clientTempId:w}),C),M};return{assertHubMutable:h,setStarStatus:(p,f,D,w,S,g)=>m(p,w,{flag:"isStarred",reportHubId:D,userId:f,value:S,at:new Date},g),setReadStatus:(p,f,D,w,S,g)=>S.isRead&&!Ft(S.contentDigest)?Promise.reject(Q("setReadStatus: contentDigest","64 lowercase hex digits",S.contentDigest)):m(p,w,{flag:"isRead",reportHubId:D,userId:f,value:S.isRead,readContentDigest:S.isRead?S.contentDigest:null,at:new Date},g)}};var Ym=Object.freeze([]),Wo=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},wn=(e,t)=>e.get(t)??Ym,Jl=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(ln);function In(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:s}=e,{hub:c,internal:d,comment:u,label:h,hubLabel:m}=r,y=Wl(e),{externalSources:R,draftLabelNames:p,attachmentDelivery:f,titleMaxLength:D}=y,w=Ee(e.logger,1,"Service"),S=ne=>(0,sr.runWithTransactionRetry)(he=>t.transaction(te=>he(()=>ne(te))),e.transactionRetry),g=e.search===void 0?null:ll(e.search,R.map(ne=>ne.sourceType)),M={hub:c,hubLabel:m,label:h},T=g===null?null:bl({tables:{...M,search:g.tables},draftLabelNames:p});g!==null&&Io();let C=null,H=async()=>{if(g===null)return null;if(C===null){let ne=await Io(),he=g.externalSourceTexts;C=Al({hub:c,tables:g.tables,loadSources:(te,se)=>et(te,se,he),inTransaction:S,normalizerVersion:ne})}return C},{incrementRedisEpoch:I,publishToSseStream:L,readSseStreamAnchor:x}=Yl({redis:i,logger:w,epochs:s,streamKey:y.redisKeys.sseStream,streamMaxLen:y.streamMaxLen}),j={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:w,settings:y,draftVisibilityTables:M,inTransaction:S,publishToSseStream:L,prepareSearchIndex:H},{visibleSourceTypeCondition:X,draftVisibleTo:J,draftLabelFlag:$,isDraftReport:_,externalSelections:B,applyExternalJoins:Y,resolveHubDisplayFields:pe,readCanonicalDraftLabelId:ie,getDraftLabelId:me,resolveCreationCategoryDraftLabelId:De,mapHubRecord:Z}=Nl(j),{getAttachmentsByHubIds:b,getAttachmentForUser:O,markAttachmentMissing:N,markAttachmentPresent:v}=Ol(j,{draftVisibleTo:J,visibleSourceTypeCondition:X}),{getUserIdByExternalId:F,getDailyReportIdsByExternalId:z,getDailyReportIdsFirstPageByExternalId:ee,getDailyReportsByBusinessDateByExternalId:G,getDailyReportDetailById:k,getDailyReportDetailByIdByExternalId:P,getDailyReportDetailsByIdsByExternalId:E,fetchDeliveredHubOutcomes:U,invalidateHubReadCaches:W,clearCache:Se}=jl(j,{draftVisibleTo:J,visibleSourceTypeCondition:X,draftLabelFlag:$,externalSelections:B,applyExternalJoins:Y,resolveHubDisplayFields:pe,resolveCreationCategoryDraftLabelId:De,mapHubRecord:Z,getAttachmentsByHubIds:b,readSseStreamAnchor:x,incrementRedisEpoch:I}),{assertHubMutable:Fe,setStarStatus:Ie,setReadStatus:Re}=Kl(j,{draftVisibleTo:J,incrementRedisEpoch:I}),{addComment:Te,deleteComment:Ke}=Hl(j,{isDraftReport:_,assertHubMutable:Fe,incrementRedisEpoch:I}),{createDailyReport:it,updateDailyReport:oe,publishDailyReport:Ne,deleteDailyReport:Rt}=Ul(j,{readCanonicalDraftLabelId:ie,isDraftReport:_,getDailyReportDetailById:k,assertHubMutable:Fe,incrementRedisEpoch:I}),Nt=async(ne,he)=>{let te=new Map,se=r.attachment;if(!se||f===null)return te;let xe=await ne.select({hubId:se.hubId,fileName:se.fileName}).from(se).where((0,we.inArray)(se.hubId,[...he])).orderBy((0,we.asc)(se.hubId),(0,we.asc)(se.createdAt),(0,we.asc)(se.id));for(let le of xe)Wo(te,Number(le.hubId),String(le.fileName));return te},It=async(ne,he,te)=>{let se=new Map;for(let[xe,le]of te){let st=new Map;for(let{hub:qe}of he)qe.sourceType===xe&&qe.sourceIdNum!==null&&st.set(qe.sourceIdNum,qe.id);if(st.size===0)continue;let _t=await le(ne,[...st.keys()]);for(let[qe,lt]of _t){let Ot=st.get(qe);if(Ot===void 0)throw Q(`search.externalSourceTexts.${xe} answer key`,"a source id that was asked for",qe);if(!(Array.isArray(lt)&&lt.every(lr=>typeof lr=="string")))throw Q(`search.externalSourceTexts.${xe} answer for ${qe}`,"an array of strings",lt);se.set(Ot,lt)}}return se},_n=(ne,he)=>{let te=pe(ne),se=[["subject",ne.hub.title],["content",te.content],["author",te.author],["employeeName",te.employeeName],["updatedBy",te.updatedBy],["category",te.category],["creationCategory",te.creationCategory],["customerName",te.customerName]];for(let le of te.interviewers)se.push(["interviewerName",le.name??null],["interviewerAffiliation",le.affiliation??null]);for(let le of he.labelNames)se.push(["label",le]);for(let le of he.attachmentNames)se.push(["attachment",le]);for(let le of he.extraTexts)se.push(["extra",le]);let xe=[];for(let le of te.externalComments)xe.push({authorUserId:null,text:Jl(le.name,le.text)});for(let le of he.postedComments)xe.push({authorUserId:le.userId,text:Jl(le.userName,le.body)});return{hubId:ne.hub.id,fields:se,comments:xe,filterValues:{authorName:te.employeeName,customerName:te.customerName}}},et=async(ne,he,te)=>{let se=[];for(let xe of(0,sr.chunk)(he,sr.MAX_IN_LIST)){let le=await Y(ne.select({hub:wt(c),internal:wt(d),creatorName:n.displayName,...B()}).from(c)).leftJoin(d,(0,we.eq)(c.id,d.hubId)).leftJoin(n,(0,we.eq)(c.userId,n.id)).where((0,we.inArray)(c.id,[...xe])).orderBy((0,we.asc)(c.id)),st=new Map,_t=await ne.select({hubId:m.hubId,name:h.name}).from(m).innerJoin(h,(0,we.eq)(m.labelId,h.id)).where((0,we.inArray)(m.hubId,[...xe])).orderBy((0,we.asc)(m.hubId),(0,we.asc)(h.id));for(let tt of _t)Wo(st,tt.hubId,tt.name);let qe=new Map,lt=await ne.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,(0,we.eq)(u.userId,n.id)).where((0,we.inArray)(u.hubId,[...xe])).orderBy((0,we.asc)(u.hubId),(0,we.asc)(u.createdAt),(0,we.asc)(u.id));for(let tt of lt)Wo(qe,tt.hubId,tt);let Ot=await Nt(ne,xe),lr=await It(ne,le,te);for(let tt of le){let je=tt.hub.id;se.push(_n(tt,{labelNames:wn(st,je),postedComments:wn(qe,je),attachmentNames:wn(Ot,je),extraTexts:wn(lr,je)}))}}return se},fc=(ne,he,te)=>T===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):T.search(t,{criteria:te,viewerUserId:he,scope:ne}),Ko=y.sourceTypes,Rc=async(ne,he)=>{if(T===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let te=Ko.filter(le=>Me(ne.visible,le)),se=await T.facetValues(t,{column:"authorName",viewerUserId:he,scope:ne}),xe=await T.facetValues(t,{column:"customerName",viewerUserId:he,scope:ne});return{sourceTypes:te,authors:se,customers:xe}},Sc=async(ne,he,te,se,xe)=>{let le=qo("markDailyReportSearchHits",xe);if(T===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(se.length>Pe.maxDetailIds)throw Q("markDailyReportSearchHits: reportHubIds",`at most ${Pe.maxDetailIds} ids`,se.length);let st=qr(Ir(te));if(se.length===0||$e(ne.visible))return{wordsDigest:st,reports:[],deferred:[]};le.throwIfAborted();let _t=jo(le),qe=await U(ne,he,se,{read:"markDailyReportSearchHits",signal:le,slicing:_t});await _t.pause();let lt=qe.flatMap(je=>je.outcome==="ok"?[{reportHubId:je.reportHubId,fields:vl(je.report)}]:[]),Ot=te.combine==="union"&&te.sets.length>=2&&lt.length>0?await T.matchedSets(t,{plan:te,viewerUserId:he,scope:ne,ids:lt.map(je=>je.reportHubId)}):null,lr=lt.map(({reportHubId:je,fields:bc})=>{let Jo=Ot===null?null:Ot.get(je),Qo=Jo===void 0?0:Jo;return{reportHubId:je,matchedSets:Qo,alternatives:Pl(te,Qo).flatMap(Dc=>Dc.alternatives),fields:bc}}),tt=await Ll(lr,vr,_t.pause,xl(vr,_t.now));return{wordsDigest:st,reports:tt.reports,deferred:tt.deferred}},gc=async ne=>{let he=await H();if(he===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return he.reconcile(t,ne)};return{streamKey:y.redisKeys.sseStream,attachmentDelivery:f,titleMaxLength:D,searchLimits:g===null?null:{concurrency:g.concurrency,rateLimitPerMinute:g.rateLimitPerMinute},searchFilterSourceTypes:Ko,clearCache:Se,invalidateHubReadCaches:W,getUserIdByExternalId:F,getDailyReportIdsByExternalId:z,getDailyReportIdsFirstPageByExternalId:ee,readSseStreamAnchor:x,getDailyReportsByBusinessDateByExternalId:G,getDailyReportDetailById:k,getDailyReportDetailByIdByExternalId:P,getDailyReportDetailsByIdsByExternalId:E,getDraftLabelId:me,searchDailyReports:fc,markDailyReportSearchHits:Sc,listDailyReportSearchFacets:Rc,reconcileSearchIndex:gc,getAttachmentsByHubIds:b,getAttachmentForUser:O,markAttachmentMissing:N,markAttachmentPresent:v,setStarStatus:Ie,setReadStatus:Re,addComment:Te,deleteComment:Ke,createDailyReport:it,updateDailyReport:oe,publishDailyReport:Ne,deleteDailyReport:Rt}}var Ql=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(Ee(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return Ee(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};var Lr=require("drizzle-orm"),A=require("drizzle-orm/mssql-core");function Xl(e,t){let r=(0,A.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,A.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,A.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,A.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(Lr.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,A.date)("business_date"),userId:(0,A.bigint)("user_id",{mode:"number"}),title:(0,A.nvarchar)("title",{length:200}),summary:(0,A.nvarchar)("summary",{length:"max"}),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,A.datetime2)("deleted_at"),deletedBy:(0,A.nvarchar)("deleted_by",{length:50})},u=>[(0,A.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,A.index)(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),(0,A.index)(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),(0,A.index)(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),(0,A.index)(`${e}_DailyReportHub_user_id_index`).on(u.userId),(0,A.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,Lr.desc)(u.businessDate),(0,Lr.desc)(u.id)),(0,A.index)(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,A.nvarchar)("body",{length:"max"}),metadata:(0,A.nvarchar)("metadata",{length:"max"}),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),(0,A.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}).notNull(),body:(0,A.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,A.index)(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}),name:(0,A.nvarchar)("name",{length:50}).notNull(),color:(0,A.nvarchar)("color",{length:20}),sortOrder:(0,A.int)("sort_order"),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,A.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,A.bit)("is_read").default(!1).notNull(),isStarred:(0,A.bit)("is_starred").default(!1).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull(),readContentDigest:(0,A.char)("read_content_digest",{length:64})},u=>[(0,A.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),(0,A.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,A.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,A.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,A.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,A.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,A.nvarchar)("file_type",{length:100}),fileSize:(0,A.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,A.datetime2)("object_checked_at"),objectMissingAt:(0,A.datetime2)("object_missing_at"),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),(0,A.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),(0,A.index)(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:d,label:l,hubLabel:s,userStatus:c}}var fe=require("drizzle-orm/mssql-core");function Zl(e){let t=(0,fe.mssqlSchema)(e),r=t.table("DailyReportSearchDocument",{hubId:(0,fe.bigint)("hub_id",{mode:"number"}).notNull(),searchText:(0,fe.nvarchar)("search_text",{length:"max"}).notNull(),sourceDigest:(0,fe.binary)("source_digest",{length:32}).notNull(),normalizerVersion:(0,fe.varchar)("normalizer_version",{length:64}).notNull(),indexedAt:(0,fe.datetime2)("indexed_at").notNull(),rowVersion:(0,fe.binary)("row_version",{length:8}).notNull(),authorName:(0,fe.nvarchar)("author_name",{length:gt.maxValueLength}),customerName:(0,fe.nvarchar)("customer_name",{length:gt.maxValueLength})},o=>[(0,fe.primaryKey)({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:(0,fe.bigint)("hub_id",{mode:"number"}).notNull(),ordinal:(0,fe.int)("ordinal").notNull(),authorUserId:(0,fe.bigint)("author_user_id",{mode:"number"}),commentText:(0,fe.nvarchar)("comment_text",{length:"max"}).notNull()},o=>[(0,fe.primaryKey)({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var zm=5e7,Yo=2e8,Gm=1,zo=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})})}),ec=125,tc=4,rc=16,nc=50,oc=2,Nr=Object.freeze({renderMs:Ye.renderMs,nanosecondsPerBlockVisit:ec,margin:tc,maxBlockVisits:Math.floor(Ye.renderMs*1e6/(ec*tc)),walkBudgetMs:rc,nanosecondsPerWalkStep:nc,walkMargin:oc,maxWalkSteps:Math.floor(rc*1e6/(nc*oc))}),Km=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),ac=75,ic=4,sc="#ffffff",Jm=1,Qm={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Xm=[/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/],lc=Object.freeze({ok:!1,reason:"failed"}),cc=Object.freeze({ok:!1,reason:"unsupported"}),uc=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Ci(e)}),dc=(e,t)=>{switch(t){case"jpeg":{let r=yo(e);return r===null?null:uc(r)}case"png":{let r=Pi(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=vi(e,Nr.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},pc=(e,t)=>{let r=Km.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=zo,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},mc=(e,t,r)=>{let n=dc(e,t);return n===null?null:pc(n,r)},Zm=e=>e!==null&&e<=Yo,ey=(e,t)=>{if(t!=="jpeg")return dc(e,t);let r=Mi(e,Nr);return r===null||r.blockVisits>Nr.maxBlockVisits?null:uc(r.header)},ty=e=>{let t=e instanceof Error?e.message:"";return Xm.some(r=>r.test(t))?"failed":"unsupported"},yc=e=>{e.cache(!1),e.concurrency(Gm),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Qm)});let t=async(n,o,a,i,l)=>{let s=ey(n,o);if(s===null)return cc;try{let c=e(n,{limitInputPixels:zm,animated:!1});if(!Zm(pc(s,await c.metadata())))return cc;if(l.aborted)return lc;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:sc}).webp({quality:ac,effort:ic}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:ty(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?lc:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${ac}-e${ic}/flatten-${sc}/v${Jm}`,render:r}};var Go=6e4,hc=e=>{let t=ce("ttlMs",e.ttlMs,1,Go),r=ur("readViewerKey",e.readViewerKey),n=ur("resolve",e.resolve),o=new Map;return async(a,i)=>{let l=await r(a,i);if(l===null)throw new Error(`[daily-report] createDailyReportVisibilityCache: the request names no viewer for the ${JSON.stringify(i.reason)} resolution (readViewerKey answered null), so no source type may be shown`);let s=ue(),c=o.get(l);if(i.reason==="initial"&&c!==void 0&&s<c.expiresAt)return c.answer;let d=Promise.resolve().then(()=>n(a,i));for(let[h,m]of o)m.expiresAt<=s&&o.delete(h);o.set(l,{expiresAt:s+t,answer:d});let u=()=>{o.get(l)?.answer===d&&o.delete(l)};return d.catch(u),d}};function ry(e){e.redis||Ee(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=Or(e.redis),r=new Gt({defaultTtlMs:e.cacheDefaultTtlMs,maxBuckets:e.cacheMaxBuckets,maxBytes:e.cacheMaxBytes},t),n=In({...e,cache:r,epochs:t}),o=new ar({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=yn({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:n.searchFilterSourceTypes,...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,DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,buildDailyReportRedisKeys,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createDailyReportVisibilityCache,createEpochStore,createSharpThumbnailRenderer,dailyReportSseStreamMessageSchema,defineDailyReportSchema,defineDailyReportSearchSchema,encodeIdsStreamRows,isStreamIdLte,parseClientTempId,predictSharpThumbnailWorkingSetBytes,readDailyReportSseStreamEntry,transformJsonArray});
15
15
  /* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */