@aiquants/daily-report 0.46.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -1,15 +1,15 @@
1
- var Go=e=>{throw TypeError(e)};var Ko=(e,t,r)=>t.has(e)||Go("Cannot "+r);var tr=(e,t,r)=>(Ko(e,t,"read from private field"),r?r.call(e):t.get(e)),An=(e,t,r)=>t.has(e)?Go("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Tn=(e,t,r,n)=>(Ko(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Pt=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 ${Pt(r)}`),je=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),En=(e,t,r)=>Q(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ie=(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)},ve=(e,t,r,n)=>t===void 0?n:ie(e,t,r),rr=(e,t)=>{if(t===void 0)throw je(e,"a function");if(typeof t!="function")throw Q(e,"a function",t);return t};var se=()=>Math.floor(performance.now());var wn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),Ke=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},In=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{}}}),nr=(e,t)=>t?e.map(r=>structuredClone(r)):e,dc=8,pc=32,mc=24,yc=16,hc=-(2**30),fc=2**30-1,Rc=e=>Number.isInteger(e)&&e>=hc&&e<=fc&&!Object.is(e,-0),Sc=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=pc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=dc*a.length;for(let i of a)typeof i=="string"?r+=mc+2*i.length:typeof i=="number"&&!Rc(i)?r+=yc:typeof i=="object"&&i!==null&&n.push(i)}return r},or=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-se())<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:se()+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 Ke(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:se()+(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 Ke("aborted");return this.dropBucket(r),nr(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>se())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),nr(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),nr(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return nr(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new Ke("aborted");return nr(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 Ke&&(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=ve("cacheDefaultTtlMs",t.defaultTtlMs,1,wn.defaultTtlMs),this.maxBuckets=ve("cacheMaxBuckets",t.maxBuckets,1,wn.maxBuckets),this.maxBytes=ve("cacheMaxBytes",t.maxBytes,1,wn.maxBytes),this.lastSweepAt=se()}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=Sc(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=se();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)}};import{crossOriginRefusal as jp}from"@aiquants/request-isolation";var gc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Jo=e=>e<10?`0${e}`:`${e}`,bc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Jo(e.getMonth()+1),n=Jo(e.getDate());return`${t}-${r}-${n}`},Vt=e=>{let t=gc.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}`},Mr=e=>Vt(e)===e;var Ue=e=>e==null?null:e instanceof Date?bc(e):Vt(e);import{z as Dc}from"zod/v3";var at=e=>Number.isSafeInteger(e)&&e>0,Ne=Dc.number().int().positive().max(Number.MAX_SAFE_INTEGER);import{z as te}from"zod/v3";var Pr=/^(?:[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 kt=Symbol("daily-report wire mismatch"),it=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),kt),ea=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,Lt=(e,t)=>({code:"invalid_type",expected:e,received:ea(t)}),Ac=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Tc=e=>{let t=0;for(let r in e)t+=1;return t},Qo=(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},qt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!Ac(n))return it(o,null,Lt("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===kt){i=!0;continue}a===null&&u!==d&&(a=Qo(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?kt:a!==null?a:Tc(n)===l?n:Qo(n,t,t.length)}},ar=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},ir=e=>(t,r,n)=>{if(!Array.isArray(t))return it(r,n,Lt("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===kt?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?kt:o},pe=(e,t,r)=>e==null||typeof e=="string"?e:it(t,r,Lt("string",e)),Xo=(e,t,r)=>e===null||typeof e=="string"?e:it(t,r,Lt("string",e)),Zo=(e,t,r)=>typeof e=="string"?e:it(t,r,Lt("string",e)),Ec=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:it(t,r,Lt("number",e)),sr=(e,t,r)=>typeof e=="boolean"?e:it(t,r,Lt("boolean",e)),_n=(e,t,r)=>{if(typeof e=="number"&&at(e))return e;for(let{message:n,path:o,...a}of Ne.safeParse(e).error.issues)it(t,r,a);return kt},ta={present:!0,absent:!0,unknown:!0},ra=Object.keys(ta),wc=ra.map(e=>`'${e}'`).join(" | "),Ic=(e,t,r)=>typeof e!="string"?it(t,r,{code:"invalid_type",expected:wc,received:ea(e)}):Object.hasOwn(ta,e)?e:it(t,r,{code:"invalid_enum_value",received:e,options:[...ra]}),na=qt({name:pe,affiliation:pe}),oa=qt({name:pe,text:pe,color:pe}),aa=qt({id:_n,name:pe,color:pe}),ia=qt({id:_n,userId:pe,userName:pe,content:pe,createdAt:pe,isMine:sr}),_c=qt({id:Zo,fileName:Zo,fileType:Xo,fileSize:Ec,createdAt:Xo,state:Ic,hasThumbnail:sr}),xc=qt({reportHubId:_n,date:pe,createdAt:pe,author:pe,userId:pe,sourceType:pe,employeeName:pe,updatedBy:pe,updatedAt:pe,category:pe,creationCategory:pe,visitTimeFrom:pe,visitTimeTo:pe,customerName:pe,interviewers:ir(ar(na)),subject:pe,content:pe,externalComments:ir(ar(oa)),isRead:sr,isStarred:sr,isDraft:sr,labels:ir(ar(aa)),postedComments:ir(ar(ia)),attachments:ir(ar(_c))}),lr=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===kt?{ok:!1,issues:r.issues}:{ok:!0,value:n}},sa=e=>lr(xc,e),la=e=>lr(na,e),ca=e=>lr(oa,e),ua=e=>lr(aa,e),da=e=>lr(ia,e);var pa=15e3,ma="lastEventId",Cc=/^\d{1,15}-\d{1,15}$/,ya=e=>Cc.test(e),Tt="0-0",cr=e=>te.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 te.NEVER}),Gy=cr(la),Ky=cr(ca),Jy=cr(ua),Mc=cr(da),ur=cr(sa),dr=te.string().regex(Pr),ha=te.object({type:te.literal("connected")}),fa=te.object({type:te.literal("status-update"),reportHubId:Ne,statusType:te.enum(["star","read"]),value:te.boolean(),clientTempId:dr}),xn=te.string(),Ra=te.object({type:te.literal("comment-add"),reportHubId:Ne,comment:Mc,clientTempId:dr,sourceType:xn}),Sa=te.object({type:te.literal("comment-delete"),reportHubId:Ne,commentId:Ne,clientTempId:dr,sourceType:xn}),kr={recipientRawUserId:Ne.optional()},Cn=fa.extend(kr),Mn=Ra.extend(kr),Pn=Sa.extend(kr),jt={reportHubId:Ne,report:ur,clientTempId:dr},kn={...kr,actorRawUserId:Ne},Ln={viewerIsActor:te.boolean()},Pc=te.object({type:te.literal("report-create"),...jt,...Ln}),kc=te.object({type:te.literal("report-update"),...jt,...Ln}),Lc=te.object({type:te.literal("report-publish"),...jt,...Ln}),vn=te.object({type:te.literal("report-create"),...jt,...kn}),Nn=te.object({type:te.literal("report-update"),...jt,...kn}),On=te.object({type:te.literal("report-publish"),...jt,...kn}),Lr=te.object({type:te.literal("report-delete"),reportHubId:Ne,clientTempId:dr,sourceType:xn}),Qy=te.discriminatedUnion("type",[ha,fa,Ra,Sa,Pc,kc,Lc,Lr]),Hn=te.discriminatedUnion("type",[ha,Cn,Mn,Pn,vn,Nn,On,Lr]);var ga="ids-columns";var vc=/^[0-9a-f]{1,16}$/,ba=e=>at(e.reportHubId)&&(e.businessDate===null||Mr(e.businessDate)),Da=e=>typeof e=="string"&&vc.test(e),th=Object.freeze({kind:"absent"}),rh=Object.freeze({kind:"value",value:null});var Wt=(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}},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+(?=.)/,"")},Aa=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Nc=(e,t,r,n)=>Aa(e,t,r,n)<0,Fn=(e,t)=>Aa(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Ta=e=>{for(let t=1;t<e.length;t++)if(!Nc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},Ea=(e,t)=>{let r=e.findIndex(n=>Fn({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var le=Object.freeze({businessDate:"business-date",idsStream:ga,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),ge=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 wa=(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)}}},ih=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),Ia=e=>`[DailyReport${e}]`,be=(e,t,r)=>e===void 0?wa(t,Ia(r)):wa(0,Ia(r),e);import{z as vt}from"zod/v3";var pr=e=>({reportHubId:e,outcome:"not_found"}),dh=vt.discriminatedUnion("outcome",[vt.object({reportHubId:Ne,outcome:vt.literal("ok"),report:ur}).strict(),vt.object({reportHubId:Ne,outcome:vt.literal("not_found")}).strict(),vt.object({reportHubId:Ne,outcome:vt.literal("failed")}).strict()]);var Oc="legacy-",$n=e=>`${Oc}${e}`;var Hc=/^[1-9][0-9]*$/,Fc=/^(?:0|[1-9][0-9]*)$/,Je=e=>{if(e===null||!Hc.test(e))return null;let t=Number(e);return at(t)?t:null},Un=e=>{if(e===null||!Fc.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Bn=e=>e==="true"?!0:e==="false"?!1:null,mr=e=>e===null?!1:Bn(e);var _a=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),pt=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var $c=16777619,Vn=2166136261,qn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,$c);return o>>>0},xa=e=>qn(Vn,e,0,e.length),Uc=String.fromCodePoint(3),Bc=String.fromCodePoint(2),Vc=String.fromCodePoint(1),Nr=e=>xa(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Uc)).join(Bc)).join(Vc));var Ca=e=>e==="intersection"||e==="union",xe=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),jn=2,Or=2,Nt=Object.freeze({word:0,reading:1});var Wn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var Rh=2*(1+jn);import{z as Dh}from"zod/v3";var Ma=e=>e.issues.map(t=>`${t.path.length===0?"(root)":t.path.join(".")}: ${t.code}`).join("; ");var We=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var Hr=Math.max(1,Math.floor(10.556701030927835));var Qe=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Ce=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),Qe(()=>{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 mt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var _h=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),qc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Yn=e=>{let t=e.trim();return t.length===0?null:t.replace(qc,"\uFFFD")},jc=e=>{let t=Yn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>mt.maxValueLength?"filter-value-too-long":null},Wc=e=>{if(e.length>mt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=jc(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},Yc=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Pa=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Wc(t);if(r!==null)return r}return Yc(e)>mt.maxTotalValueLength?"filters-too-long":null};var ka=e=>e.trim().length===0;var zn=e=>e!==null&&Pr.test(e)?e:null,Gn=e=>Ca(e)?e:null,Kn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>xe.maxDetailIds)return null;let r=[];for(let n of t){let o=Je(n);if(o===null||r.includes(o))return null;r.push(o)}return r},La=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},va=(e,t)=>{let r={authors:e.getAll(ge.searchAuthor),sourceTypes:e.getAll(ge.searchSourceType),customers:e.getAll(ge.searchCustomer)},n=Pa(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:La(r.authors),customers:La(r.customers)}}},Na=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Ha=Object.freeze({status:400,error:"Invalid form"}),Fa=e=>({status:413,error:"Form too large",measuredBy:e}),zc=(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)}}))},Gc=async e=>{let t=Un(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Fa("declared")};let r=!1,n=e.body===null?null:zc(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?Fa("counted"):Ha}}let l=Na(i);return l===null?{refusal:Ha}:{fields:l}},$a=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=Bn(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},Ba=Object.freeze({update:(e,t,r)=>{let n=e.get(We.title),o=e.get(We.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:$a("toggleStar",We.isStarred),toggleRead:$a("toggleRead",We.isRead),addComment:(e,t)=>{let r=e.get(We.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Je(e.get(We.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Kc=e=>Object.hasOwn(Ba,e),Jc=(e,t)=>{let r=e.get(We.intent),n=e.get(We.businessDate),o=n===null?null:Vt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(We.operationTimestamp),i=Un(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(We.clientTempId);if(!l)return{error:"clientTempId required"};let s=zn(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=Je(e.get(We.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!Kc(r)?{error:"Invalid intent"}:Ba[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Va=async(e,t)=>{let r=await Gc(e);if("refusal"in r)return r;let n=Jc(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Qc=6e4,Xc="form_too_large",Ua=["declared","counted"],qa=e=>{let t=Ce({windowMs:Qc,tallies:Ua,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Ua.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(Xc,r,n)}};var Ot=Object.freeze({[le.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[le.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[le.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[le.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[le.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[le.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[le.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),ja=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Jn=e=>e!==void 0&&Object.hasOwn(Ot,e);var Qn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Wa=e=>Object.hasOwn(Qn,e);var Zc="download",eu="thumbnail",tu="1";var Xn=e=>{let t=e.getAll(eu),r=e.getAll(Zc);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Wa(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===tu?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{NO_CROSS_ORIGIN_NAVIGATION as au}from"@aiquants/request-isolation";import{createHash as ru}from"crypto";var Zn=e=>`"${ru("sha256").update(e).digest("hex")}"`,Ya=e=>Zn(JSON.stringify(e));var st=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),eo=(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=Zn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...st});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&eo(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},to=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...st});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},ro=e=>(t,r,n,o)=>{if(o!==200)return to(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)},nu=5e3/1e3,ou=new Map([[503,nu]]),Te=e=>{let t=ou.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var oo="Cross-site request rejected",iu="Not Found",Ga=["api","action","sse","attachment"],Ka=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...st}}),su=()=>Ka(403,oo),Fr=()=>Ka(404,iu),yr=Object.freeze({...au,frameworkDataRefusal:()=>null,crossSiteRejection:su}),Ja=e=>new URL(e.url).pathname.endsWith(".data"),lu=6e4,cu="refusals",uu=32,du=/^[a-z-]+$/,no=e=>{if(e===null)return"-";let t=e.slice(0,uu);return du.test(t)&&t===e?e:JSON.stringify(t)},Qa=e=>{let t=Ce({windowMs:lu,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=${no(i.get("Sec-Fetch-Site"))} mode=${no(i.get("Sec-Fetch-Mode"))} dest=${no(i.get("Sec-Fetch-Dest"))} method=${o.method}`)};t.record(cu,r,a)}};var Xa=(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 pu="same-origin",mu="SAMEORIGIN",Yt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":pu,"X-Frame-Options":mu}),$r=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Yt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Za=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),yu=/^[\x20-\x7E]+$/,hu=/^[\w.+-]+\/[\w.+-]+/,ao=e=>e&&yu.test(e)&&hu.test(e)?e:null,fu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,ei=e=>encodeURIComponent(e.replace(fu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),ti=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),hr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},ri={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Ur=e=>typeof e=="string"&&Object.hasOwn(ri,e),Br=e=>ri[e],yt="Attachment request failed";var lt=e=>{let t=ie("limit",e.limit,1),r=ie("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ie("queue.max",e.queue.max,0),maxPerOwner:ie("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ie("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,T)=>{let E=s(m,R)+T;E<=0?m.delete(R):m.set(R,E)},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[T,E]of a.entries()){let S=s(l,E.owner);if(S<R&&(m=T,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:T}=n,E=S=>{let g=()=>{let H=a.indexOf(_);H<0||(a.splice(H,1),c(i,m,-1),A(),S(null))},C=Qe(g,T),A=()=>{clearTimeout(C),R.removeEventListener("abort",g)},_={owner:m,grant:H=>{A(),S(H)}};a.push(_),c(i,m,1),R.addEventListener("abort",g,{once:!0})};return new Promise(E)}}};var Ru=1024,io="Too many requests",Su=(e,t)=>{ie("limitPerWindow",e,1),ie("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<=Ru)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))}}},ht=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ie("windowMs",r,1e3)%1e3!==0)throw Q("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Su(e.limitPerWindow,r),i=Object.freeze({status:429,message:io,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Ce({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,se())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,se(),c)}}};var bu=256*1024,ni=6e4,Du=e=>Math.ceil(e/2),Au=new Uint8Array(new ArrayBuffer(0)),Tu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Au,t()},i=l=>{clearTimeout(o),o=Qe(()=>{l.error(new Error(`attachment body idle for ${ni} ms`)),a()},ni)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+bu,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})},oi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=ht({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=lt({limit:e.concurrency,maxHeldPerOwner:Du(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 T=await n(c,"initial");if(!T.ok)return f(503,hr[503],Te(503));let E=await t.getAttachmentForUser(T.scope,u,h);if(!E)return o.warn(`404 attachment=${u} viewer=${h} reason=not_visible`),f(404,"Attachment not found");if(E.fileSize!=null&&E.fileSize>m)return o.warn(`413 attachment=${u} viewer=${h} reason=db_size`),f(413,"Attachment too large");let S=ao(E.fileType),g=`filename="${ti(E.fileName)}"; filename*=UTF-8''${ei(E.fileName)}`,C=await l.acquire(h,c.signal);if(!C)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",Te(503)));let A=!1;try{let _=await p(E.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(!_.ok){if(!Ur(_.reason))return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=failure_reason`),f(500,yt);let F=Br(_.reason);return _.reason==="not_found"&&a(u,!1),o.warn(`${F} attachment=${u} viewer=${h} reason=${_.reason} code=${_.code??"-"}`),f(F,hr[F],Te(F))}if(_.bytes.byteLength>m)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),f(500,yt);let H=c.method==="HEAD";if(H&&_.size!==void 0&&_.size>m)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),f(500,yt);if(!H&&_.size!==void 0&&_.size!==_.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=size_mismatch`),f(500,yt);let w=S??ao(_.contentType),k=w!==null&&Za.has(w),x=k?w:"application/octet-stream",q=k&&d.kind!=="download"?"inline":"attachment",K=H?_.size:_.bytes.byteLength,z=new Headers({"Content-Type":x,"Content-Disposition":`${q}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Yt});return K!==void 0&&z.set("Content-Length",String(K)),y&&z.append("Set-Cookie",y),a(u,!0),o.info(`200 attachment=${u} viewer=${h} type=${x} disposition=${q} bytes=${K??"-"}`),H?new Response(null,{status:200,headers:z}):(A=!0,new Response(Tu(_.bytes,C),{status:200,headers:z}))}finally{A||C()}}};var Be=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Rf=Be.queueWaitMs+Be.readMs+Be.renderMs+Be.transferMarginMs;import{Buffer as Eu}from"buffer";var si=new Set([194,198,202,206]),wu=new Set([192,193,194,195]),li=216,Iu=217,ci=218,_u=4,xu=64,Cu=2,ai=8,ii=28,Et=12,so=8,Mu=20,ui=Et+so+10,Pu=2,ft=(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},ct=(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},di=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,pi=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),mi=e=>(e.stepsLeft-=1,e.stepsLeft>=0),yi=e=>e[0]===255&&e[1]===li,hi=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!mi(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===Iu)return"eoi";if(o===0||o===li)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=ft(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(!mi(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}},fi=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=ft(e,r+1),a=ft(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}},Ri=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>_u||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},Si=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:si.has(e.marker)||t<e.components.length}),lo=e=>{if(!yi(e))return null;let t=pi(e.byteLength),r=null;for(let n=2;;){if(hi(e,n,t)!=="segment")return null;if(di(t.marker)){if(r!==null||(r=fi(e,t),r===null))return null}else if(t.marker===ci){if(r===null)return null;let o=Ri(e,t);return o===null?null:Si(r,o.length)}n=t.end}},gi=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*ai)),i=Math.ceil(e.height*o/(r*ai));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},bi=e=>e.multiScan?gi(e).reduce((r,n)=>r+n,0)*xu*Cu:0,Lu=896,Di=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!yi(e))return null;let n=Eu.from(e.buffer,e.byteOffset,e.byteLength),o=pi(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let h=hi(e,u,o);if(h===null)return null;if(h==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,di(o.marker)){if(a!==null||!wu.has(o.marker)||(a=fi(e,o),a===null))return null;let p=gi(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*(si.has(a.marker)?Lu:1)}else if(o.marker===ci){if(a===null||d===s)return null;let p=Ri(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=Si(a,p.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let y=ku(n,o.end,o);if(y===null)return null;u=y}}},Ai=e=>{if(e.byteLength<24||ft(e,8)!==0||ft(e,10)!==13||!ct(e,12,"IHDR"))return null;let t=ft(e,16)*65536+ft(e,18),r=ft(e,20)*65536+ft(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},vu=e=>{if(ct(e,Et,"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(ct(e,Et,"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 ct(e,Et,"VP8X")?e.byteLength<ui?null:{width:zt(e,24,3)+1,height:zt(e,27,3)+1}:null},Ti=e=>{if(Ai(e)===null||e.byteLength<=ii)return null;switch(e[ii]){case 0:return!1;case 1:return!0;default:return null}},Ei=(e,t)=>{if(ct(e,Et,"VP8 "))return"lossy";if(ct(e,Et,"VP8L"))return"lossless";if(!ct(e,Et,"VP8X")||e.byteLength<ui)return null;if((e[Mu]&Pu)!==0)return"animated";let r=!1,n=t;for(let o=Et;o+so<=e.byteLength;){if(n-=1,n<0)return null;if(ct(e,o,"VP8L"))return"lossless";if(ct(e,o,"VP8 "))return r?"lossy-alpha":"lossy";ct(e,o,"ALPH")&&(r=!0);let a=zt(e,o+4,4);o+=so+a+a%2}return null},wi={png:Ai,jpeg:lo,webp:vu};var co=Object.freeze(["image/webp","image/jpeg","image/png"]),uo=1024*1024;var Nu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Ou={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Hu=new Set(co),Fu=e=>typeof e=="string"&&Hu.has(e),$u=256,Vr=(e,t)=>e.fileType===null||!Nu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Uu=[137,80,78,71,13,10,26,10],Bu=[255,216,255],Vu=[[71,73,70,56,55,97],[71,73,70,56,57,97]],qu=[82,73,70,70],ju=[87,69,66,80],fr=(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},po=e=>{if(fr(e,Uu,0))return"png";if(fr(e,Bu,0))return"jpeg";for(let t of Vu)if(fr(e,t,0))return"gif";return fr(e,qu,0)&&fr(e,ju,8)?"webp":null},Ii=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])}},_i=(e,t)=>{if(!Fu(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>uo)return"too_large";let r=Ou[e.contentType];if(po(e.bytes)!==r)return"signature";let n=wi[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},xi=e=>{ie("maxBytes",e.maxBytes,0),ie("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)+$u;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 mo=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=se(),l=new AbortController,s=!1,c,d,u=()=>{a(se()-i)},h=S=>{c=Qe(()=>{s=!0,S({timedOut:!0}),d=Qe(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(se()-i,S.kind==="error"?{error:S.error}:null),S),T=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:T}};var Rt={404:"Attachment not found",500:yt,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Ci=(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=_i(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Wu=e=>{let t=new AbortController,r=()=>{t.abort()},n=Qe(r,Be.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Mi=()=>{},Yu=(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)}),Pi=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(Mi,Mi);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=Wu(y);try{if(await Yu(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 T=r.get(p.key);if(T!==void 0)return{...T,identity:"verified"};let E=mo({budgetMs:Be.readMs,flightSignal:y,call:F=>p.readAttachment(p.filePath,{maxBytes:n,head:!1,principal:o(p.owner),signal:F}),onOverrun:u("read",p),onStuck:h("read",p)}),S=await E.outcome;if(S.timedOut)return R=E.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 Ur(g.reason)?(g.reason==="not_found"&&a(p.attachmentId,!1),{kind:"failure",status:Br(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 C=d(p,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),A=F=>{C==="verified"&&r.set(p.key,F)},_=F=>(A(F),{...F,identity:C});if(!g.ok)return _({kind:"unrenderable",reason:"too_large"});let H=po(g.bytes);if(H===null)return _({kind:"unrenderable",reason:"signature"});let w=mo({budgetMs:Be.renderMs,flightSignal:y,call:F=>p.renderer.render(g.bytes,{format:H,maxWidth:p.box.maxWidth,maxHeight:p.box.maxHeight,signal:F}),onOverrun:u("render",p),onStuck:h("render",p)}),k=F=>{if(F.kind==="error")return;let I=Ci(F.value,p.box);"entry"in I&&A(I.entry)},x=null,q=()=>(x===null&&(x=w.settled.then(k),s(p.key,x)),x);y.addEventListener("abort",q,{once:!0});let K=await w.outcome.finally(()=>y.removeEventListener("abort",q));if(K.timedOut||y.aborted)return R=q(),y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let z=Ci(K.value,p.box);return"entry"in z?_(z.entry):z.failure}finally{R===null?m():R.then(m,m)}}};var ki=()=>{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 Ni=10,zu=1/Ni,Li=1-zu,Gu=1024,Ku=64,Ju=8,vi="private, no-cache",Qu="no-store",Xu=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Zu=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Oi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(S,g)=>ht({reason:S,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:C=>`viewer=${C} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*Ni),h=lt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Ku,maxPerOwner:Ju,maxWaitMs:Be.queueWaitMs}}),p=xi({maxBytes:l.cacheBytes,maxEntries:Gu}),y=ki(),f=Pi({gate:h,cache:p,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),m=(S,g,C,A)=>{let _=`attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail cache=${A}`;if(g.kind==="failure")return o[Zu(g)](`${g.status} ${_} reason=${g.reason} code=${g.code??"-"}`),S.fail(g.status,Rt[g.status],Te(g.status));let H=Xu[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${_} reason=${g.reason}${H}`),S.fail(404,Rt[404]);let w=g.identity==="verified"?{"Cache-Control":vi,ETag:C}:{"Cache-Control":Qu},k=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...w,"Content-Security-Policy":"default-src 'none'; sandbox",...Yt});return S.cookie&&k.append("Set-Cookie",S.cookie),o.info(`200 ${_} type=${g.contentType} bytes=${g.bytes.byteLength}${H}`),new Response(g.bytes,{status:200,headers:k})},R=(S,g)=>{let C=S.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return C===null?null:g.fail(C.status,C.message,C.headers)},T=S=>R(d,S),E=(S,g)=>g?R(u,S):T(S);return async(S,g)=>{let{request:C,attachmentId:A,internalUserId:_,readAttachment:H,cookie:w,fail:k}=S,x=Qn[g],q=C.headers.get("If-None-Match"),K=q!==null,z=E(S,K);if(z)return z;let F=await n(C,"initial");if(!F.ok)return k(503,Rt[503],Te(503));let I=await t.getAttachmentForUser(F.scope,A,_),j=I!==null&&Vr(I,i)?Ii({rendererId:s.id,box:x,attachmentId:A,filePath:I.filePath,fileType:I.fileType,fileSize:I.fileSize}):null;if(j&&eo(q,j.etag)){let b=new Headers({"Cache-Control":vi,ETag:j.etag,...Yt});return w&&b.append("Set-Cookie",w),o.info(`304 attachment=${A} viewer=${_} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:b})}if(K){let b=T(S);if(b)return b}if(!I)return o.warn(`404 attachment=${A} viewer=${_} variant=thumbnail reason=not_visible`),k(404,Rt[404]);if(!j)return d.refund(_,Li),o.info(`404 attachment=${A} viewer=${_} variant=thumbnail reason=not_eligible`),k(404,Rt[404]);let{key:ce,etag:ne}=j,de=p.get(ce);if(de)return d.refund(_,Li),m(S,{...de,identity:"verified"},ne,"hit");let Re=b=>f({key:ce,attachmentId:A,filePath:I.filePath,fileSize:I.fileSize,box:x,owner:_,readAttachment:H,renderer:s},b),J;try{J=await y.join(ce,C.signal,Re)}catch(b){return o.error(`500 attachment=${A} viewer=${_} variant=thumbnail cache=miss reason=port_exception message=${b instanceof Error?b.message:"unknown"}`),k(500,Rt[500])}return m(S,J,ne,"miss")}};var ed='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',td=()=>$r(403,oo,{cookie:null}),Hi=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Xn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>$r(404,hr[404],{cookie:null}),crossSiteRejection:td}),Fi=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:Xa(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:oi({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Oi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,h=(p,y,f={})=>$r(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=Xn(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(ed);let m=s.idCodec.decode(d.token);if(m===null||!at(m))return h(400,"Invalid attachment token");let R=await r.getUserIdByExternalId(p.id);if(!R)return h(403,"Forbidden");let T={request:c,delivery:f,attachmentId:m,internalUserId:R,readAttachment:s.read,cookie:u,fail:h};return f.kind!=="thumbnail"?await s.serveOriginal(T):s.serveThumbnail===null?h(404,Rt[404]):await s.serveThumbnail(T,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,yt)}}};var rd=32*1024*1024,nd=60,od=4,ad=120,id=2,sd=8*1024*1024,qr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ld=e=>{if(e===void 0)throw je("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!qr(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},cd=e=>{if(e===void 0)return null;if(!qr(e))throw Q("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:ld(e.renderer),rateLimitPerMinute:ve("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,ad),concurrency:ve("attachments.thumbnails.concurrency",e.concurrency,1,id),cacheBytes:ve("attachments.thumbnails.cacheBytes",e.cacheBytes,0,sd)})},$i=e=>{let t=e;if(t===void 0)return null;if(!qr(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(!qr(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:ve("attachments.maxBytes",t.maxBytes,1,rd),rateLimitPerMinute:ve("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,nd),concurrency:ve("attachments.concurrency",t.concurrency,1,od),thumbnails:cd(t.thumbnails)})},ud=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"]]),jr=e=>{for(let[t,r]of ud)if(Object.hasOwn(e,t))throw je(r,`given in place of the flat key ${t}`)};var Bi=8,dd=8*Bi,pd=128,md=2,Vi=md*pd,yd=4*Vi,hd=6e4,fd=6e4,Rd="Too many reads",Ui=Object.freeze(Object.keys(Ot).filter(e=>Ot[e].admission.includes("miss-gate"))),qi=e=>{let t=lt({limit:dd,maxHeldPerOwner:Bi,queue:{max:yd,maxPerOwner:Vi,maxWaitMs:hd}}),r=Ce({windowMs:fd,tallies:Ui,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Ui.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}})}},Wr=(e,t,r)=>{let n=e(t,r,{error:{message:Rd}},503);for(let[o,a]of Object.entries(Te(503)))n.headers.set(o,a);return n};var ji=e=>{let t=e.get(ge.cursorReportHubId),r=e.get(ge.cursorBusinessDate),n=e.get(ge.cursorSnapshot),o=Da(n)?n:null,a=null;if(t!==null){let l=Je(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!ba(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=mr(e.get(ge.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var Yr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Sd=2,gd=16,bd=Sd*gd,Dd=6e4,Wi=()=>{},Ad=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Yi=e=>{let t=lt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:bd,queue:null}),r=Ce({windowMs:Dd,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 Wi;if(a.aborted){if(t.canAcquire(n))return Wi}else{let i=await t.acquire(n,a);if(i!==null)return Ad(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var zr=30,Qi=4e3,Td="stream interrupted by server error",Ed="Too many streams",wd=15e3,Xi=Symbol("ids-stream-heartbeat"),zi=()=>{},Gi=e=>e.return(void 0).then(zi,zi),Id=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Xi),wd)}),stop:()=>clearTimeout(e)}};async function*Ki(e,t,r,n){let o=t?Ea(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Qi),e.length),l=Wt(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 Zi=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...st});return e&&t.append("Set-Cookie",e),t},Ji=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await Gi(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=Id();try{s===null&&(s=t.next());let h=await Promise.race([s,u.fired]);if(u.stop(),h===Xi){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 Ke||n.error(`ids-stream emission failed: ${h instanceof Error?h.message:String(h)}`);try{let p={kind:"error",error:Td};d.enqueue(i.encode(`${JSON.stringify(p)}
4
- `)),d.close()}catch{}}},cancel(){l=!0,o(),Gi(t)}});return new Response(c,{status:200,headers:Zi(e)})},es=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 T=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,zr).then(g=>({items:g,streamAnchor:S}))).then(S=>f?.(S),S=>m?.(S))}});if(T.catch(()=>{}),l.cursor){let{items:S,streamAnchor:g,snapshot:C}=await T,A=l.snapshot!==null&&l.snapshot===C;return Ji(d,Ki(S,A?l.cursor:null,zr,{snapshot:C,restarted:!A,streamAnchor:g}),u,r,h)}let E=(async function*(){let S=await Promise.race([T.then(A=>({kind:"full",source:A}),A=>({kind:"full-error",error:A})),R.then(A=>({kind:"page",page:A}),()=>({kind:"page-error"}))]),g=null,C=!1;if(S.kind==="full")g=S.source;else if(S.kind==="page"){let{items:A,streamAnchor:_}=S.page;if(A.length<zr){yield{kind:"chunk",...Wt(A,0,A.length),nextCursor:null,isLast:!0,total:A.length,streamAnchor:_};return}yield{kind:"chunk",...Wt(A,0,A.length),nextCursor:null,isLast:!1,provisional:!0},C=!0}else if(S.kind==="full-error"&&y){let A=await R.catch(()=>null);A&&A.items.length>0&&(yield{kind:"chunk",...Wt(A.items,0,A.items.length),nextCursor:null,isLast:!1,provisional:!0})}g===null&&(g=await T),yield*Ki(g.items,null,C?Qi:zr,{snapshot:g.snapshot,streamAnchor:g.streamAnchor})})();return Ji(d,E,u,r,h)};return async(l,s,c,d,u,h)=>{let p=ji(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 T=a(d,c,s,h);if(T!==null)return T}let f=Yr(c),m=await t.getUserIdByExternalId(d.id),R=await n.admit(m,"ids-stream",f);if(R===null){let T=h(c,s,{error:{message:Ed}},503);for(let[E,S]of Object.entries(Te(503)))T.headers.set(E,S);return T}if(f.aborted)return new Response(null,{status:200,headers:Zi(s)});try{return await i(y,d,u,s,f,R,m===null?void 0:o.admissionFor(m,le.idsStream,f))}catch(T){if(R(),T instanceof Ke)return Wr(h,c,s);throw T}}};import{inArray as _d,sql as Gr}from"drizzle-orm";var Xe="Internal",ts=e=>e.trim().toLowerCase();var xd="",Cd=64,Md=e=>e.toLowerCase(),rs=e=>{let t=new Set;if(!Array.isArray(e))return t;for(let r of e){if(typeof r!="string")continue;let n=ts(r);n.length>0&&t.add(n)}return t};function we(e,t){return e===null?!0:t==null?!1:e.has(Md(t))}function He(e){return e!==null&&e.size===0}var Pd=4e3,ho=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 ie("tables.hub.sourceType.length",e.length,1,Pd)};function Sr(e,t){if(t===null)return;let r=ho(e),n=[...t].filter(a=>a.length<=r);if(n.length===0)return Gr`1 = 0`;let o=Gr.raw(`VARBINARY(${2*r})`);return _d(Gr`CAST(LOWER(${e}) AS ${o})`,n.map(a=>Gr`CAST(${a} AS ${o})`))}var Gt,Kt,Rr=class Rr{constructor(t,r){An(this,Gt);An(this,Kt);Tn(this,Gt,t),Tn(this,Kt,r)}get visible(){return tr(this,Gt)===null?null:new Set(tr(this,Gt))}get commentable(){return tr(this,Kt)===null?null:new Set(tr(this,Kt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=rs(r?t.read:t);if(!r||t.comment===void 0)return new Rr(n,n);let o=new Set;for(let a of rs(t.comment))n.has(a)&&o.add(a);return new Rr(n,o)}static unrestricted(t){return new Rr(null,null)}};Gt=new WeakMap,Kt=new WeakMap;var Ze=Rr,yo=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),kd=new Set(["read","comment"]),os=e=>{if(yo(e))return Ze.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?Ze.unrestricted(o):null}let{read:r,comment:n}=e;return t.every(o=>kd.has(o))&&yo(r)?n===void 0?Ze.restrictTo({read:r}):yo(n)?Ze.restrictTo({read:r,comment:n}):null:null};function Kr(e){let t=ns(e.visible),r=ns(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function ns(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(xd);if(t.length<=Cd)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 as=(e,t,r,n)=>we(n.commentable,t)||e.authorUserId===r;import{parseQuerySets as hp}from"@aiquants/fuzzy-search";import{createHash as Ld}from"crypto";import{setImmediate as is}from"timers/promises";import{clusterCountOf as vd,DEFAULT_NORMALIZE_OPTIONS as Qr,InteriorPairs as Nd,isAnswerTier as Od,normalizeText as Hd,queryNeedles as Fd,resolveNormalizeOptions as $d,toMappedFormsInto as Ud,trimmedRange as Bd}from"@aiquants/fuzzy-search/normalize";var Xr=`
5
- `,fo=4e3,Vd=1,us=new Set([8203,8288,65279,173]),qd=new RegExp(`[${String.fromCodePoint(...us)}]`,"gu"),ds=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),ps=/(\s+)/u,jd=/^\s+$/u,Wd=new RegExp(ps.source,"gu"),Yd=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,zd=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]),Zr=e=>e.replace(qd,"");var Ro=e=>Hd(e,Qr),Jr=e=>Ro(Zr(e)),Gd=$d({...Qr,convertRomaji:!0},"[daily-report] search reading options"),Kd=3,Jd=/^[-ー]+/u,Qd=/[^\p{L}\p{M}]/gu,Xd=/ー{2,}/gu,Zd=/\p{Script=Latin}/u,ss=/(?=\p{L})\p{Script=Latin}/u,ep=e=>vd(e.replace(Jd,"").replace(Qd,"").replace(Xd,"\u30FC")),tp=(e,t)=>{for(let r of t)if(!Od(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})`)},ms=e=>{if(!ss.test(e))return[];let t=Jr(e);if(!ss.test(t))return[];let r=Fd(t,Gd,!1);tp(t,r);let n=[];for(let o of r){if(o.tier===Nt.word)continue;let a=Jr(o.text);if(!(a.length===0||a.length>xe.maxWordLength)&&!(a===t||Zd.test(a))&&!(ep(a)<Kd||n.includes(a))&&(n.push(a),n.length===jn))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},ys=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&So(e,t-1)?t-2:t-1;return Yd.test(String.fromCodePoint(r))&&!zd.has(e.codePointAt(n))},rp=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!ys(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(ps)){let c=o;if(o+=s.length,i+s.length<=t){i===0&&(a=c),i+=s.length;continue}if(l(),jd.test(s))continue;if(s.length<=t){a=c,i=s.length;continue}let d=rp(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}},np=(e,t)=>{let r=0;for(let n of e.matchAll(ds))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},op=(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},hs=(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=op(Ud(d,Qr,new Nd(0)),d),[h,p]=Bd(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}},en=(e,t=fo)=>{let r=[],n=0;return np(Zr(e),o=>{let a=bo(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(Xr),forcedCuts:n}},fs=e=>e.filter(t=>t.length>0).join(Xr),Do=(e,t)=>{let r=null;return{advance:n=>{if(r!==null)return 0;e.units=ie("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}}},ls=4096;function*ap(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);us.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+=ls)r.push(Reflect.apply(String.fromCharCode,null,c.subarray(d-s,Math.min(o,d+ls)-s)))}i=l}return a?{text:r.join(""),rawIndex:n.subarray(0,o)}:{text:e,rawIndex:null}}var Rs=e=>{let t={units:0};return Do(t,ap(e,t))};function*ip(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(ds)){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 Ss=(e,t)=>{let r={units:0};return Do(r,ip(e,t,r))};function*cs(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,ys(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*sp(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(Wd)){let R=p+m.index;R>f&&u(R),f=R+m[0].length;let T=h(f);if(T>=0){let E=yield*cs(e,T,R,t,r);o+=E.forcedCuts,n.push(E.pieces)}}y>f&&u(y),p=y}if(d(l,s,c)){let p=yield*cs(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 gs=(e,t)=>{let r={units:0};return Do(r,sp(e,t,r))},lp=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
6
- `)},cp=[`\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`],up=["","\u30A2","\u4F50"," "],dp=()=>JSON.stringify(cp.map(e=>en(e,8))),pp=e=>`dr-search-v${Vd};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var mp=async()=>{let e=Ld("sha256");e.update(JSON.stringify(Qr));for(let t of up)await is(),e.update("\0"),e.update(Ro(lp(t)));return await is(),e.update("\0"),e.update(dp()),pp(e.digest("hex"))},yp=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},Ao=yp(mp);var fp=/^-+/u,Rp=/\s+/u,bs=e=>{let t=fp.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Sp=(e,t)=>{let r=[...bs(e).map(n=>({text:n,tier:Nt.word})),...t.flatMap(n=>bs(n).map(o=>({text:o,tier:Nt.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},gp=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),tn=(e,t)=>{if(e.length>xe.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of hp(Zr(e),t).sets){let i=[],l=new Set;for(let c of a.split(Rp)){let d=Jr(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>xe.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=Sp(d,ms(c)),h=gp(u);l.has(h)||(l.add(h),i.push({alternatives:u}))}if(i.length>xe.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>xe.maxSets?{ok:!1,reason:"too-many-sets"}:o>xe.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},gr=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var jR=Object.freeze({sourceTypes:null,authors:null,customers:null}),bp=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,Ds=(e,t,r)=>{if(ka(e)&&bp(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=tn(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var As=6e4,Dp=1,Ap=3200,Ts=2e3,Tp=Object.freeze({search:Ap,reports:Ts,"search-marks":Ts,"search-facets":null}),Ep=(e,t)=>{let r=Tp[e];return r===null?null:{max:t,maxPerOwner:Or,maxWaitMs:r}},br=e=>{let{concurrency:t,route:r,logger:n}=e,o=ht({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:As,logger:n,windowFields:()=>`route=${r}`}),a=lt({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:Ep(r,t)}),i=Object.freeze({status:429,message:io,headers:Object.freeze({"Retry-After":String(Dp)})}),l=Ce({windowMs:As,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})}}};import{systemSseRuntime as Lp}from"@aiquants/sse";import{createSseResponse as vp,readLastEventId as Np,startSseHeartbeat as Op,terminalStreamResponse as Hp}from"@aiquants/sse/server";var Dr=(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=Hn.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}},Es=new WeakMap,ws=(e,t,r)=>{let n=Es.get(e);n===void 0&&(n=new Map,Es.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,wp=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)}}},Ip=(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})},Is=(e,t,r)=>{let{parsed:n}=e;if(n.type!=="report-create"&&n.type!=="report-update"&&n.type!=="report-publish")return ws(e,"every-viewer",()=>JSON.stringify(wp(n)));let o=n.actorRawUserId===t;return ws(e,`${o?"actor":"observer"}${r?"-comments-redacted":""}`,()=>JSON.stringify(Ip(n,o,r)))};import{systemSseRuntime as _p}from"@aiquants/sse";import{createSharedSource as xp}from"@aiquants/sse/shared-source";var wt="daily-report:ids:",Eo=(e,t)=>`${e}st:${t}`,wo=e=>`${wt}user:${e}:`,_s=(e,t)=>Eo(wo(e),t),Jt=e=>`daily-report:date:${e}:user:`,Qt=(e,t)=>`${Jt(e)}${t}:`,xs=(e,t,r)=>Eo(Qt(e,t),r),Ye=e=>`daily-report:detail:${e}:user:`,Io=(e,t)=>`${Ye(e)}${t}:`,Cs=(e,t,r)=>Eo(Io(e,t),r);var St=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},Cp=5e3,Mp=Hr,Ar=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=be(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:Tt}_createSource(){return xp({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:_p,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:Cp,COUNT:Mp});if(i)for(let l of i)for(let s of l.messages){a=s.id;let{entry:c,json:d}=Dr(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(wt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ye(n))}};var Pp=6e4,Tr="Report visibility is unavailable",Ms=["initial","refresh"],Ps=Object.freeze({ok:!1}),kp=e=>e===null?"null":Array.isArray(e)?"array":typeof e,ks=(e,t)=>{let r=Ce({windowMs:Pp,tallies:Ms,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{t.error(`visibility_unavailable_suppressed count=${o} since=${a} cause=${n} reasons=${Ms.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)),Ps}let i=os(a);return i===null?(r.record("port_contract",o,()=>t.error(`visibility unavailable cause=port_contract reason=${o} answer=${kp(a)}`)),Ps):{ok:!0,scope:i}}},Ls=(e,t,r)=>{let n=e(t,r,{error:{message:Tr}},503);for(let[o,a]of Object.entries(Te(503)))n.headers.set(o,a);return n};var Ns=Object.freeze({...yr,route:"sse",frameworkDataRefusal:Fr}),vs=864e5,Fp={baseMs:2e3,jitterMs:8e3},Os=6e4,_o=Hr,Hs=JSON.stringify({type:"connected"}),$p=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},Up=(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 we(t,e.report.sourceType);case"comment-add":case"comment-delete":return we(r,e.sourceType);case"report-delete":return we(t,e.sourceType)}},Bp=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!we(t,e.report.sourceType),Vp=(e,t)=>{e.writeEvent({event:null,id:t,data:Hs})},qp=(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||!Up(o,r.visibleSet,r.commentableSet)){Vp(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Is(n,r.internalUserId,Bp(o,r.commentableSet))})},Fs=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,T=setInterval(()=>{let x=++R;n(h,"refresh").then(q=>{if(x===R){if(!q.ok){d.close();return}f=q.scope.visible,m=q.scope.commentable}})},Os);d.onClose(()=>clearInterval(T));let E=y===null?Tt:y,S=y!==null&&o!==void 0,g=[],C=null,A=x=>{St(x.id,E)||(E=x.id,qp(d,x,{internalUserId:p,visibleSet:f,commentableSet:m}))},_=async(x,q)=>{let[K]=await x.xRange(i,"-","+",{COUNT:1});return K!==void 0&&!St(K.id,q)},H=async(x,q)=>{let[K]=await x.xRange(i,"-","+",{COUNT:1});if(K===void 0)return!0;let z;if(q===Tt){if($p(await x.xInfoStream(i))>0)return!1;z=K.id}else{if(!St(K.id,q))return!1;z=q}for(;;){let F=await x.xRange(i,z,"+",{COUNT:_o}),I=F[0];if(I!==void 0&&I.id!==z&&await _(x,z))return!1;for(let j of F){if(C!==null&&St(C,j.id))return!0;St(j.id,E)||A(Dr(j,s).entry)}let $=F.at(-1);if(F.length<_o||$===void 0||d.isClosed())return!0;z=$.id}},w=a.subscribe(x=>{if(!S){A(x);return}St(x.id,E)||(C===null&&(C=x.id),g.push(x))},x=>{s.error(`[SSE:${p}] Fan-Out reader error:`,x),d.close()});if(d.onClose(w),y===null){await a.ready();try{let x=await o?.getClient();if(x){let q=await x.xRevRange(i,"+","-",{COUNT:1});q.length>0&&!St(q[0].id,E)&&(E=q[0].id)}}catch{}}if(d.writeEvent({event:null,id:E===Tt?null:E,data:Hs}),Op(d,{intervalMs:pa,retry:Fp,runtime:Lp}),y===null||o===void 0)return;await a.ready();let k=await o.getClient();if(k===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await H(k,y)){d.writeRetry(vs),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}S=!1;for(let x of g.splice(0))A(x)};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(st))f.set(m,R);return f},y=f=>Hp(f,{data:"",retryMs:vs,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 T=Np(d,ma);if(T!==null&&!ya(T))return s.warn(`[SSE:${R}] malformed resume cursor; asking the client to resync`),y("resync-required");let E=Yr(d),S=await l.admit(R,"sse",E);if(S===null){let C=p();for(let[A,_]of Object.entries(Te(503)))C.set(A,_);return new Response("Too many streams",{status:503,headers:C})}let g=!1;try{let C=await n(d,"initial");if(!C.ok){let _=p();for(let[H,w]of Object.entries(Te(503)))_.set(H,w);return new Response(Tr,{status:503,headers:_})}let A=C.scope;return vp({requestSignal:E,headers:p(),onError:(_,H)=>s.error(`[SSE:${R}] ${H} failed:`,_),produce:_=>(g=!0,_.onClose(S),c(_,{request:d,internalUserId:R,cursor:T,initialScope:A}))})}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 $s=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...st});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Wp=Object.freeze({...yr,route:"api",frameworkDataRefusal:({params:e})=>Jn(e.endpoint)&&Ot[e.endpoint].body==="stream"?Fr():null}),Yp=Object.freeze({...yr,route:"action"}),zp=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),js=6e4,Ws=5,Gp=Ws*Math.ceil(js/500),Kp=2,Jp=6,Qp=6e4,Xp=Ws*Kp*Jp,Zp=2,em=10,tm=2,rm=10,Us=(e,t)=>Math.max(e,Or)*t,Ys=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},nm=Object.freeze({etag:(e,t,r)=>za(e,t,r,200),"no-store":(e,t,r)=>to(t,r,200)}),om=e=>ro(e.body==="json"?nm[e.cache]:null),Bs=ro(null),Vs=(e,t,r,n)=>Ys(e(t,r,{error:{message:n.message}},n.status),n.headers),qs=(e,t,r)=>Ys(e(t,r,null,503),Te(503));function xo(e){jr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:ie("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=be(e.logger,3,"API"),d=be(e.logger,3,"Visibility"),u=ks(rr("resolveVisibleSourceTypes",e.resolveVisibleSourceTypes),d),h=be(e.logger,1,"SSE"),p=be(e.logger,1,"Attachment"),y=be(e.logger,2,"Isolation"),f=be(e.logger,2,"Action"),m=be(e.logger,2,"Search"),R=be(e.logger,2,"Refresh"),T=be(e.logger,2,"Streams"),E=be(e.logger,2,"Reads"),S=ht({reason:"refresh_rate_limit",limitPerWindow:Xp,windowMs:Qp,logger:R,windowFields:()=>"route=api"}),g=Yi(T),C=qi(E),A=async(b,v,L,P,O,W)=>{let X=await r.getUserIdByExternalId(v.id);try{return await W(X===null?void 0:C.admissionFor(X,b,L.signal))}catch(Y){if(Y instanceof Ke)return Wr(O,L,P);throw Y}},_=(b,v,L,P,O)=>{let W=S.spend(v.id,`endpoint=${b}`);return W===null?null:Vs(O,L,P,W)},H=async({request:b})=>{let{user:v,cookie:L}=await t(b,{failureRedirect:s}),P=new Headers;L&&P.append("Set-Cookie",L);let O=await r.getUserIdByExternalId(v.id),W=O?n(O):null;return{data:{user:v,userId:W},headers:P}},w=b=>{let{limiter:v}=b;return async(L,P,O,W,X,Y)=>{if(v===null)return Y(O,P,{error:{message:"Unknown endpoint"}},404);let M=b.parse(L);if(!M.ok)return Y(O,P,M.invalid,400);let D=await r.getUserIdByExternalId(W.id);if(!D)return Y(O,P,b.emptyAnswer(M.parsed),200);let{signal:N}=O,U=await v.admit(D,N);if("refusal"in U)return N.aborted?qs(Y,O,P):Vs(Y,O,P,U.refusal);try{N.throwIfAborted();let G=await b.read(M.parsed,{userId:D,user:W,scope:X},N);return N.throwIfAborted(),Y(O,P,G,200)}catch(G){if(N.aborted&&G===N.reason)return qs(Y,O,P);throw G}finally{U.release()}}},k=r.searchLimits===null?null:br({...r.searchLimits,route:le.search,logger:m}),x=r.searchLimits===null?null:br({concurrency:Us(r.searchLimits.concurrency,Zp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*em,route:le.reports,logger:m}),q=r.searchLimits===null?null:br({concurrency:Us(r.searchLimits.concurrency,tm),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*rm,route:le.searchMarks,logger:m}),K=r.searchLimits===null?null:br({...r.searchLimits,route:le.searchFacets,logger:m}),z={[le.businessDate]:async(b,v,L,P,O,W)=>{let X=b.searchParams.get(ge.businessDate),Y=X===null?null:Vt(X);if(Y===null)return W(L,v,{error:{message:"Invalid business date"}},400);let M=mr(b.searchParams.get(ge.forceRefresh));if(M===null)return W(L,v,{error:{message:"Invalid forceRefresh"}},400);let D=M?_(le.businessDate,P,L,v,W):null;return D!==null?D:A(le.businessDate,P,L,v,W,async N=>{let U=await r.getDailyReportsByBusinessDateByExternalId(O,Y,P.id,{forceRefresh:M,admission:N});return W(L,v,{businessDate:Y,reports:U},200)})},[le.idsStream]:es({service:r,logger:c,streamSlots:g,missGate:C,refuseForcedRead:(b,v,L,P)=>_(le.idsStream,b,v,L,P)}),[le.report]:async(b,v,L,P,O,W)=>{let X=Je(b.searchParams.get(ge.reportHubId));if(X===null)return W(L,v,{error:{message:"Invalid reportHubId"}},400);let Y=mr(b.searchParams.get(ge.forceRefresh));if(Y===null)return W(L,v,{error:{message:"Invalid forceRefresh"}},400);let M=Y?_(le.report,P,L,v,W):null;return M!==null?M:A(le.report,P,L,v,W,async D=>{let N=await r.getDailyReportDetailByIdByExternalId(O,X,P.id,{snapshot:!0,forceRefresh:Y,admission:D});return N?W(L,v,{report:N},200):W(L,v,{error:{message:"Report not found"}},404)})},[le.search]:w({limiter:k,parse:b=>{let v=b.searchParams.get(ge.searchQuery),L=Gn(b.searchParams.get(ge.searchCombine));if(v===null||L===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let P=va(b.searchParams,r.searchFilterSourceTypes);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:P.reason}}};let O=Ds(v,L,P.filters);if(!O.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:O.reason}}};let{criteria:W}=O;return{ok:!0,parsed:{criteria:W,words:W.plan===null?[]:gr(W.plan)}}},emptyAnswer:({words:b})=>Wn([],b),read:async({criteria:b,words:v},{userId:L,scope:P})=>Wn(await r.searchDailyReports(P,L,b),v)}),[le.reports]:w({limiter:x,parse:b=>{let v=Kn(b.searchParams.get(ge.reportIds));return v===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:v}},emptyAnswer:b=>({outcomes:b.map(pr)}),read:async(b,{user:v,scope:L},P)=>({outcomes:await r.getDailyReportDetailsByIdsByExternalId(L,b,v.id,{signal:P})})}),[le.searchMarks]:w({limiter:q,parse:b=>{let v=b.searchParams.get(ge.searchQuery),L=Gn(b.searchParams.get(ge.searchCombine));if(v===null||L===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let P=tn(v,L);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:P.reason}}};let O=Kn(b.searchParams.get(ge.reportIds));return O===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:P.plan,ids:O}}},emptyAnswer:({plan:b})=>({wordsDigest:Nr(gr(b)),reports:[],deferred:[]}),read:({plan:b,ids:v},{userId:L,scope:P},O)=>r.markDailyReportSearchHits(P,L,b,v,{signal:O})}),[le.searchFacets]:w({limiter:K,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(b,{userId:v,scope:L})=>r.listDailyReportSearchFacets(L,v)})},F=async({request:b,params:v})=>{let{user:L,cookie:P}=await t(b,{failureRedirect:null}),O=P??null;if(!L)return Bs(b,O,{error:{message:"Unauthorized"}},401);let W=v.endpoint;if(!Jn(W))return Bs(b,O,{error:{message:"Unknown endpoint"}},404);let X=Ot[W],Y=om(X),M=ja[X.body];if(!M.includes(b.method)){let N=Y(b,O,{error:{message:"Method not allowed"}},405);return N.headers.set("Allow",M.join(", ")),N}let D=se();try{let N=new URL(b.url),U=await u(b,"initial"),G=U.ok?await z[W](N,O,b,L,U.scope,Y):Ls(Y,b,O);return X.body==="json"&&c.debug(G.headers.has("ETag")?`${G.status} endpoint=${W} etag_match=${G.status===304}`:`${G.status} endpoint=${W}`),G}catch(N){let U=se()-D,G=N instanceof Error?N:new Error(String(N));return c.error(`500 endpoint=${W} elapsed=${U}ms name=${G.name} code=${"code"in G?G.code:"N/A"} message=${G.message}`,G),Y(b,O,{error:{message:"Internal Server Error"}},500)}},I=qa(f),$=ht({reason:"rate_limit",limitPerWindow:Gp,windowMs:js,logger:f,windowFields:()=>"route=action"}),j=async(b,v,L,P,O)=>{let{clientTempId:W}=b;if(b.intent==="create")try{let D=await r.createDailyReport(L,v,b.businessDate,W);return O(b,D.reportHubId,{report:D})}catch(D){if(D instanceof Error&&D.message==="Forbidden")return P({error:"Creating reports is restricted"},{status:403});throw D}let{reportHubId:X,businessDate:Y}=b,M=async(D,N)=>{try{let U=await N(D.value);return O(D,X,{updatedStatus:{isStarred:U.isStarred,isRead:U.isRead},operationTimestamp:D.operationTimestamp})}catch(U){if(U instanceof Error&&U.message==="Not Found")return P({error:"Report not found"},{status:404});throw U}};switch(b.intent){case"update":try{return await r.updateDailyReport(L,X,v,b.changes,W),O(b,X,{})}catch(D){if(D instanceof Error){if(D.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(D.message==="Not Found")return P({error:"Report not found"},{status:404})}throw D}case"publish":try{let D=await r.publishDailyReport(L,X,v,W);return O(b,X,{report:D})}catch(D){if(D instanceof Error){if(D.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(D.message==="Not Found")return P({error:"Report not found"},{status:404})}throw D}case"delete":try{return await r.deleteDailyReport(L,X,v,W),O(b,X,{})}catch(D){if(D instanceof Error){if(D.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(D.message==="Not Found")return P({error:"Report not found"},{status:404})}throw D}case"toggleStar":return await M(b,D=>r.setStarStatus(L,v,X,Y,D,W));case"toggleRead":return await M(b,D=>r.setReadStatus(L,v,X,Y,D,W));case"addComment":try{let D=await r.addComment(L,v,X,b.content,Y,W);return O(b,X,{newComment:D})}catch(D){if(D instanceof Error){if(D.message==="Not Found")return P({error:"Report not found"},{status:404});if(D.message.startsWith("Comments are restricted"))return P({error:"Comments are restricted for this report"},{status:403})}throw D}case"deleteComment":try{return await r.deleteComment(L,v,X,b.commentId,Y,W),O(b,X,{deletedCommentId:b.commentId})}catch(D){if(D instanceof Error){if(D.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(D.message==="Not Found")return P({error:"Comment not found"},{status:404})}throw D}}},ce=async({request:b,params:v})=>{let{user:L,cookie:P}=await t(b,{failureRedirect:null}),O=(Y,M)=>$s(Y,{...M,setCookie:P}),W=(Y,M,D)=>$s(zp(Y,M,D),{setCookie:P});if(!L)return O({error:"Unauthorized"},{status:401});let X=se();try{if(v.endpoint!==le.action)return O({error:"Unknown endpoint"},{status:404});let Y=$.spend(L.id,"action");if(Y!==null)return O({error:Y.message},{status:Y.status,headers:Y.headers});let M=await Va(b,l);if("refusal"in M){let{refusal:G}=M;return G.status===413&&I(G.measuredBy),O({error:G.error},{status:G.status})}let{command:D}=M;if(D.intent==="clearCache"&&!e.enableDevCacheClear)return O({error:"Invalid intent"},{status:400});let N=await u(b,"initial");if(!N.ok)return O({error:Tr},{status:503,headers:{...Te(503),"Cache-Control":"no-store"}});let U=await r.getUserIdByExternalId(L.id);return U?D.intent==="clearCache"?(await r.clearCache(),O({status:"OK",intent:"clearCache"})):await j(D,U,N.scope,O,W):O({error:"User not found"},{status:404})}catch(Y){if(Y instanceof Response)throw Y;let M=se()-X,D=Y instanceof Error?Y:new Error(String(Y));return c.error(`500 action elapsed=${M}ms name=${D.name} message=${D.message}`,D),O({error:"Internal Server Error"},{status:500})}},ne=Fs({authenticate:t,service:r,resolveViewerScope:u,redis:o,sseReader:a,streamKey:i,streamSlots:g,logger:h}),de=Fi({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:u,logger:p}),Re=Qa(y),J=(b,v)=>async L=>{let P=Ja(L.request)?b.frameworkDataRefusal(L):null;if(P!==null)throw P;let O=jp(L.request,b);return O===void 0?v(L):(Re(b.route,O,L.request),b.crossSiteRejection())};return{index:{loader:H},api:{loader:J(Wp,F),action:J(Yp,ce)},sse:{loader:J(Ns,ne)},attachment:{loader:J(Hi,de)}}}import{chunk as oy,MAX_IN_LIST as ay,runWithTransactionRetry as iy}from"@aiquants/mssql";import{asc as bt,eq as fn,inArray as Rn}from"drizzle-orm";var am=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],im=["document","comment"],sm=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],lm=["hubId","ordinal","authorUserId","commentText"],Co=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 En(e,n,r)},Gs=(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])},Ks=(e,t)=>{if(!Co(e))throw Q("search","a plain object",e);zs("search key",e,am);let{tables:r}=e;if(!Co(r))throw Q("search.tables","a plain object with document and comment",r);zs("search.tables key",r,im),Gs("search.tables.document",r.document,sm),Gs("search.tables.comment",r.comment,lm);let n=new Map;if(e.externalSourceTexts!==void 0){if(!Co(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 En("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:ie("search.concurrency",e.concurrency,1),rateLimitPerMinute:ie("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var It=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},Ht=(e,t)=>{let r=typeof e=="string"?Je(e):typeof e=="number"&&at(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},Ft=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};import{sql as B}from"drizzle-orm";import{sql as _t}from"drizzle-orm";var Js=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 _t.join(e.map(t=>_t`${t}`),_t`, `)},nn=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return _t`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${Js(t)}))`},Qs=(e,t)=>{let{hubLabel:r,label:n}=e;return _t`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${Js(t)}))`},on=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?_t`${o.userId} = ${t} OR ${o.userId} IS NULL`:_t`${o.userId} = ${t}`;return _t`(${a} OR NOT ${nn(e,r)})`};var cm=/[[%_]/gu,um=e=>e.replace(cm,t=>`[${t}]`),Xs=e=>`%${um(e)}%`;var et=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),$t=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),wr=Object.freeze({value:"value"}),Me=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),V=e=>B`${B.identifier(e.name)}`,Er=e=>B.join(e.map(t=>B`${t}`),B`, `),Zs=(e,t)=>B`SELECT ${V(e.id)} AS ${B.identifier(Me.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${Er(t)}) ORDER BY ${e.id}`,dm=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>Xs(u.text)),l=B.join(i.map(u=>B`${o.searchText} LIKE ${u}`),B` OR `),s=B.join(i.map(u=>B`${a.commentText} LIKE ${u}`),B` OR `),c=Sr(n.sourceType,r.scope.commentable),d=c===void 0?B``:B` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return B`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},el=(e,t,r)=>B`(${B.join(t.words.map(n=>dm(e,n,r)),B` AND `)})`,Mo=(e,t,r,n)=>{let{hub:o}=e,a=[B`${o.deletedAt} IS NULL`,on(e,t.userId,r,"author")],i=Sr(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(B`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},pm=(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(B`LOWER(${r.sourceType}) IN (${Er([...t.sourceTypes])})`)}return t.authors!==null&&o.push(B`${n.authorName} IN (${Er(t.authors)})`),t.customers!==null&&o.push(B`${n.customerName} IN (${Er(t.customers)})`),o},tl=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...Mo(e,r,n,o),...pm(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?B` AND `:B` OR `;s.push(B`(${B.join(l.sets.map(d=>el(e,d,r)),c)})`)}return B`SELECT ${V(a.id)} AS ${B.identifier(et.reportHubId)}, CONVERT(char(10), ${V(a.businessDate)}, 23) AS ${B.identifier(et.businessDate)}, ${V(a.sourceType)} AS ${B.identifier(et.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(s,B` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},rl=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=B.join(t.sets.map((s,c)=>B`(CASE WHEN ${el(e,s,r)} THEN ${2**c} ELSE 0 END)`),B` + `);return B`SELECT ${V(a.id)} AS ${B.identifier($t.reportHubId)}, ${l} AS ${B.identifier($t.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(Mo(e,r,n,o),B` AND `)}`},nl=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...Mo(e,r,n),B`${i} IS NOT NULL`];return B`SELECT ${i} AS ${B.identifier(wr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${B.join(l,B` AND `)} GROUP BY ${i} ORDER BY ${i}`},ol=(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 B`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${V(n.hubId)} bigint, ${V(n.searchText)} nvarchar(max), ${V(n.sourceDigest)} char(64), ${V(n.normalizerVersion)} varchar(64), ${V(n.authorName)} nvarchar(max), ${V(n.customerName)} nvarchar(max))) AS s ON t.${V(n.hubId)} = s.${V(n.hubId)}
1
+ var ea=e=>{throw TypeError(e)};var ta=(e,t,r)=>t.has(e)||ea("Cannot "+r);var nr=(e,t,r)=>(ta(e,t,"read from private field"),r?r.call(e):t.get(e)),wn=(e,t,r)=>t.has(e)?ea("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),In=(e,t,r,n)=>(ta(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var vt=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,K=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${vt(r)}`),Ye=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),_n=(e,t,r)=>K(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ie=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw K(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},Ne=(e,t,r,n)=>t===void 0?n:ie(e,t,r),or=(e,t)=>{if(t===void 0)throw Ye(e,"a function");if(typeof t!="function")throw K(e,"a function",t);return t};var se=()=>Math.floor(performance.now());var xn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),Qe=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},Cn=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{}}}),ar=(e,t)=>t?e.map(r=>structuredClone(r)):e,bc=8,Dc=32,Tc=24,Ac=16,Ec=-(2**30),wc=2**30-1,Ic=e=>Number.isInteger(e)&&e>=Ec&&e<=wc&&!Object.is(e,-0),_c=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=Dc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=bc*a.length;for(let i of a)typeof i=="string"?r+=Tc+2*i.length:typeof i=="number"&&!Ic(i)?r+=Ac:typeof i=="object"&&i!==null&&n.push(i)}return r},ir=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-se())<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:se()+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 Qe(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:se()+(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 Qe("aborted");return this.dropBucket(r),ar(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>se())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),ar(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),ar(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return ar(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new Qe("aborted");return ar(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 Qe&&(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,xn.defaultTtlMs),this.maxBuckets=Ne("cacheMaxBuckets",t.maxBuckets,1,xn.maxBuckets),this.maxBytes=Ne("cacheMaxBytes",t.maxBytes,1,xn.maxBytes),this.lastSweepAt=se()}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=_c(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=se();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)}};import{crossOriginRefusal as rm}from"@aiquants/request-isolation";var xc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var ra=e=>e<10?`0${e}`:`${e}`,Cc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=ra(e.getMonth()+1),n=ra(e.getDate());return`${t}-${r}-${n}`},jt=e=>{let t=xc.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}`},Pr=e=>jt(e)===e;var Ve=e=>e==null?null:e instanceof Date?Cc(e):jt(e);import{z as Mc}from"zod/v3";var it=e=>Number.isSafeInteger(e)&&e>0,Oe=Mc.number().int().positive().max(Number.MAX_SAFE_INTEGER);import{z as ee}from"zod/v3";var vr=/^(?:[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 Mn=/^[0-9a-f]{64}$/u;var Lt=e=>typeof e=="string"&&Mn.test(e);var Nt=Symbol("daily-report wire mismatch"),ze=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),Nt),ia=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,Et=(e,t)=>({code:"invalid_type",expected:e,received:ia(t)}),kc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pc=e=>{let t=0;for(let r in e)t+=1;return t},na=(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},Wt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!kc(n))return ze(o,null,Et("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===Nt){i=!0;continue}a===null&&u!==d&&(a=na(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?Nt:a!==null?a:Pc(n)===l?n:na(n,t,t.length)}},sr=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},lr=e=>(t,r,n)=>{if(!Array.isArray(t))return ze(r,n,Et("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===Nt?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?Nt:o},pe=(e,t,r)=>e==null||typeof e=="string"?e:ze(t,r,Et("string",e)),oa=(e,t,r)=>e===null||typeof e=="string"?e:ze(t,r,Et("string",e)),aa=(e,t,r)=>typeof e=="string"?e:ze(t,r,Et("string",e)),vc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:ze(t,r,Et("number",e)),cr=(e,t,r)=>typeof e=="boolean"?e:ze(t,r,Et("boolean",e)),sa=(e,t,r)=>typeof e!="string"?ze(t,r,Et("string",e)):Lt(e)?e:ze(t,r,{code:"invalid_string",validation:"regex",message:"a content digest is 64 lowercase hex digits"}),Lc=(e,t,r)=>e===null?null:sa(e,t,r),kn=(e,t,r)=>{if(typeof e=="number"&&it(e))return e;for(let{message:n,path:o,...a}of Oe.safeParse(e).error.issues)ze(t,r,a);return Nt},la={present:!0,absent:!0,unknown:!0},ca=Object.keys(la),Nc=ca.map(e=>`'${e}'`).join(" | "),Oc=(e,t,r)=>typeof e!="string"?ze(t,r,{code:"invalid_type",expected:Nc,received:ia(e)}):Object.hasOwn(la,e)?e:ze(t,r,{code:"invalid_enum_value",received:e,options:[...ca]}),ua=Wt({name:pe,affiliation:pe}),da=Wt({name:pe,text:pe,color:pe}),pa=Wt({id:kn,name:pe,color:pe}),ma=Wt({id:kn,userId:pe,userName:pe,content:pe,createdAt:pe,isMine:cr}),Hc=Wt({id:aa,fileName:aa,fileType:oa,fileSize:vc,createdAt:oa,state:Oc,hasThumbnail:cr}),Fc=Wt({reportHubId:kn,date:pe,createdAt:pe,author:pe,userId:pe,sourceType:pe,employeeName:pe,updatedBy:pe,updatedAt:pe,category:pe,creationCategory:pe,visitTimeFrom:pe,visitTimeTo:pe,customerName:pe,interviewers:lr(sr(ua)),subject:pe,content:pe,externalComments:lr(sr(da)),isRead:cr,isStarred:cr,contentDigest:sa,readContentDigest:Lc,isDraft:cr,labels:lr(sr(pa)),postedComments:lr(sr(ma)),attachments:lr(sr(Hc))}),ur=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===Nt?{ok:!1,issues:r.issues}:{ok:!0,value:n}},ya=e=>ur(Fc,e),ha=e=>ur(ua,e),fa=e=>ur(da,e),Ra=e=>ur(pa,e),Sa=e=>ur(ma,e);var ga=15e3,ba="lastEventId",$c=/^\d{1,15}-\d{1,15}$/,Da=e=>$c.test(e),wt="0-0",dr=e=>ee.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 ee.NEVER}),hh=dr(ha),fh=dr(fa),Rh=dr(Ra),Uc=dr(Sa),pr=dr(ya),mr=ee.string().regex(vr),Ta=ee.object({type:ee.literal("connected")}),Aa=ee.object({type:ee.literal("status-update"),reportHubId:Oe,statusType:ee.enum(["star","read"]),value:ee.boolean(),readContentDigest:ee.string().regex(Mn).nullable(),clientTempId:mr}),Pn=ee.string(),Ea=ee.object({type:ee.literal("comment-add"),reportHubId:Oe,comment:Uc,clientTempId:mr,sourceType:Pn}),wa=ee.object({type:ee.literal("comment-delete"),reportHubId:Oe,commentId:Oe,clientTempId:mr,sourceType:Pn}),Lr={recipientRawUserId:Oe.optional()},vn=Aa.extend(Lr),Ln=Ea.extend(Lr),Nn=wa.extend(Lr),Yt={reportHubId:Oe,report:pr,clientTempId:mr},On={...Lr,actorRawUserId:Oe},Hn={viewerIsActor:ee.boolean()},Bc=ee.object({type:ee.literal("report-create"),...Yt,...Hn}),Vc=ee.object({type:ee.literal("report-update"),...Yt,...Hn}),qc=ee.object({type:ee.literal("report-publish"),...Yt,...Hn}),Fn=ee.object({type:ee.literal("report-create"),...Yt,...On}),$n=ee.object({type:ee.literal("report-update"),...Yt,...On}),Un=ee.object({type:ee.literal("report-publish"),...Yt,...On}),Nr=ee.object({type:ee.literal("report-delete"),reportHubId:Oe,clientTempId:mr,sourceType:Pn}),Sh=ee.discriminatedUnion("type",[Ta,Aa,Ea,wa,Bc,Vc,qc,Nr]),Bn=ee.discriminatedUnion("type",[Ta,vn,Ln,Nn,Fn,$n,Un,Nr]);var Ia="ids-columns";var jc=/^[0-9a-f]{1,16}$/,_a=e=>it(e.reportHubId)&&(e.businessDate===null||Pr(e.businessDate)),xa=e=>typeof e=="string"&&jc.test(e),Th=Object.freeze({kind:"absent"}),Ah=Object.freeze({kind:"value",value:null});var zt=(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}},Or=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+(?=.)/,"")},Ca=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Wc=(e,t,r,n)=>Ca(e,t,r,n)<0,Vn=(e,t)=>Ca(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Ma=e=>{for(let t=1;t<e.length;t++)if(!Wc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},ka=(e,t)=>{let r=e.findIndex(n=>Vn({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var le=Object.freeze({businessDate:"business-date",idsStream:Ia,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),be=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 Pa=(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)}}},_h=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),va=e=>`[DailyReport${e}]`,De=(e,t,r)=>e===void 0?Pa(t,va(r)):Pa(0,va(r),e);import{z as Ot}from"zod/v3";var yr=e=>({reportHubId:e,outcome:"not_found"}),Ph=Ot.discriminatedUnion("outcome",[Ot.object({reportHubId:Oe,outcome:Ot.literal("ok"),report:pr}).strict(),Ot.object({reportHubId:Oe,outcome:Ot.literal("not_found")}).strict(),Ot.object({reportHubId:Oe,outcome:Ot.literal("failed")}).strict()]);var Yc="legacy-",qn=e=>`${Yc}${e}`;var zc=/^[1-9][0-9]*$/,Gc=/^(?:0|[1-9][0-9]*)$/,Xe=e=>{if(e===null||!zc.test(e))return null;let t=Number(e);return it(t)?t:null},jn=e=>{if(e===null||!Gc.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Wn=e=>e==="true"?!0:e==="false"?!1:null,hr=e=>e===null?!1:Wn(e);var La=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),mt=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var Kc=16777619,Yn=2166136261,zn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,Kc);return o>>>0},Na=e=>zn(Yn,e,0,e.length),Jc=String.fromCodePoint(3),Qc=String.fromCodePoint(2),Xc=String.fromCodePoint(1),Hr=e=>Na(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Jc)).join(Qc)).join(Xc));var Oa=e=>e==="intersection"||e==="union",Ce=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Gn=2,Fr=2,Ht=Object.freeze({word:0,reading:1});var Kn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var Fh=2*(1+Gn);import{z as Vh}from"zod/v3";var Ha=e=>e.issues.map(t=>`${t.path.length===0?"(root)":t.path.join(".")}: ${t.code}`).join("; ");var we=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 $r=Math.max(1,Math.floor(10.556701030927835));var Ze=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Me=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),Ze(()=>{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 yt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var Gh=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),Zc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Jn=e=>{let t=e.trim();return t.length===0?null:t.replace(Zc,"\uFFFD")},eu=e=>{let t=Jn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>yt.maxValueLength?"filter-value-too-long":null},tu=e=>{if(e.length>yt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=eu(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},ru=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Fa=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=tu(t);if(r!==null)return r}return ru(e)>yt.maxTotalValueLength?"filters-too-long":null};var $a=e=>e.trim().length===0;var Qn=e=>e!==null&&vr.test(e)?e:null,Xn=e=>Oa(e)?e:null,Zn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Ce.maxDetailIds)return null;let r=[];for(let n of t){let o=Xe(n);if(o===null||r.includes(o))return null;r.push(o)}return r},Ua=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},Ba=(e,t)=>{let r={authors:e.getAll(be.searchAuthor),sourceTypes:e.getAll(be.searchSourceType),customers:e.getAll(be.searchCustomer)},n=Fa(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:Ua(r.authors),customers:Ua(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 ja=Object.freeze({status:400,error:"Invalid form"}),Wa=e=>({status:413,error:"Form too large",measuredBy:e}),nu=(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)}}))},ou=async e=>{let t=jn(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Wa("declared")};let r=!1,n=e.body===null?null:nu(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?Wa("counted"):ja}}let l=Va(i);return l===null?{refusal:ja}:{fields:l}},za=(e,t)=>{let r=e.get(t);if(r===null)return{error:`${t} required`};let n=Wn(r);return n===null?{error:`Invalid ${t}`}:{value:n}},au=(e,t)=>{let r=za(e,we.isStarred);return"error"in r?r:{command:{...t,intent:"toggleStar",value:r.value}}},iu=(e,t)=>{let r=za(e,we.isRead);if("error"in r)return r;let n=e.get(we.contentDigest);return r.value?n===null?{error:`${we.contentDigest} required`}:Lt(n)?{command:{...t,intent:"toggleRead",value:!0,contentDigest:n}}:{error:`Invalid ${we.contentDigest}`}:n===null?{command:{...t,intent:"toggleRead",value:!1}}:{error:`${we.contentDigest} is not allowed when ${we.isRead} is false`}},Ga=Object.freeze({update:(e,t,r)=>{let n=e.get(we.title),o=e.get(we.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:au,toggleRead:iu,addComment:(e,t)=>{let r=e.get(we.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Xe(e.get(we.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),su=e=>Object.hasOwn(Ga,e),lu=(e,t)=>{let r=e.get(we.intent),n=e.get(we.businessDate),o=n===null?null:jt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(we.operationTimestamp),i=jn(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(we.clientTempId);if(!l)return{error:"clientTempId required"};let s=Qn(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=Xe(e.get(we.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!su(r)?{error:"Invalid intent"}:Ga[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Ka=async(e,t)=>{let r=await ou(e);if("refusal"in r)return r;let n=lu(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},cu=6e4,uu="form_too_large",Ya=["declared","counted"],Ja=e=>{let t=Me({windowMs:cu,tallies:Ya,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Ya.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(uu,r,n)}};var Ft=Object.freeze({[le.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[le.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[le.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[le.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[le.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[le.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[le.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),Qa=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),eo=e=>e!==void 0&&Object.hasOwn(Ft,e);var to=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Xa=e=>Object.hasOwn(to,e);var du="download",pu="thumbnail",mu="1";var ro=e=>{let t=e.getAll(pu),r=e.getAll(du);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Xa(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===mu?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{NO_CROSS_ORIGIN_NAVIGATION as Ru}from"@aiquants/request-isolation";import{createHash as yu}from"crypto";var no=e=>`"${yu("sha256").update(e).digest("hex")}"`,Za=e=>no(JSON.stringify(e));var st=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),oo=(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=no(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...st});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&oo(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},ao=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...st});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},io=e=>(t,r,n,o)=>{if(o!==200)return ao(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)},hu=5e3/1e3,fu=new Map([[503,hu]]),Ae=e=>{let t=fu.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var lo="Cross-site request rejected",Su="Not Found",ti=["api","action","sse","attachment"],ri=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...st}}),gu=()=>ri(403,lo),Ur=()=>ri(404,Su),fr=Object.freeze({...Ru,frameworkDataRefusal:()=>null,crossSiteRejection:gu}),ni=e=>new URL(e.url).pathname.endsWith(".data"),bu=6e4,Du="refusals",Tu=32,Au=/^[a-z-]+$/,so=e=>{if(e===null)return"-";let t=e.slice(0,Tu);return Au.test(t)&&t===e?e:JSON.stringify(t)},oi=e=>{let t=Me({windowMs:bu,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=${so(i.get("Sec-Fetch-Site"))} mode=${so(i.get("Sec-Fetch-Mode"))} dest=${so(i.get("Sec-Fetch-Dest"))} method=${o.method}`)};t.record(Du,r,a)}};var ai=(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 Eu="same-origin",wu="SAMEORIGIN",Gt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Eu,"X-Frame-Options":wu}),Br=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Gt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},ii=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Iu=/^[\x20-\x7E]+$/,_u=/^[\w.+-]+\/[\w.+-]+/,co=e=>e&&Iu.test(e)&&_u.test(e)?e:null,xu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,si=e=>encodeURIComponent(e.replace(xu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),li=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),Rr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},ci={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Vr=e=>typeof e=="string"&&Object.hasOwn(ci,e),qr=e=>ci[e],ht="Attachment request failed";var lt=e=>{let t=ie("limit",e.limit,1),r=ie("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ie("queue.max",e.queue.max,0),maxPerOwner:ie("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ie("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 E=s(p,f)+D;E<=0?p.delete(f):p.set(f,E)},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,E]of a.entries()){let S=s(l,E.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,E=S=>{let g=()=>{let O=a.indexOf(x);O<0||(a.splice(O,1),c(i,p,-1),T(),S(null))},C=Ze(g,D),T=()=>{clearTimeout(C),f.removeEventListener("abort",g)},x={owner:p,grant:O=>{T(),S(O)}};a.push(x),c(i,p,1),f.addEventListener("abort",g,{once:!0})};return new Promise(E)}}};var Cu=1024,uo="Too many requests",Mu=(e,t)=>{ie("limitPerWindow",e,1),ie("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<=Cu)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))}}},ft=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ie("windowMs",r,1e3)%1e3!==0)throw K("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Mu(e.limitPerWindow,r),i=Object.freeze({status:429,message:uo,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Me({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,se())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,se(),c)}}};var Pu=256*1024,ui=6e4,vu=e=>Math.ceil(e/2),Lu=new Uint8Array(new ArrayBuffer(0)),Nu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Lu,t()},i=l=>{clearTimeout(o),o=Ze(()=>{l.error(new Error(`attachment body idle for ${ui} ms`)),a()},ui)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Pu,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})},di=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=ft({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=lt({limit:e.concurrency,maxHeldPerOwner:vu(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,Rr[503],Ae(503));let E=await t.getAttachmentForUser(D.scope,u,h);if(!E)return o.warn(`404 attachment=${u} viewer=${h} reason=not_visible`),R(404,"Attachment not found");if(E.fileSize!=null&&E.fileSize>p)return o.warn(`413 attachment=${u} viewer=${h} reason=db_size`),R(413,"Attachment too large");let S=co(E.fileType),g=`filename="${li(E.fileName)}"; filename*=UTF-8''${si(E.fileName)}`,C=await l.acquire(h,c.signal);if(!C)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",Ae(503)));let T=!1;try{let x=await m(E.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(!x.ok){if(!Vr(x.reason))return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=failure_reason`),R(500,ht);let F=qr(x.reason);return x.reason==="not_found"&&a(u,!1),o.warn(`${F} attachment=${u} viewer=${h} reason=${x.reason} code=${x.code??"-"}`),R(F,Rr[F],Ae(F))}if(x.bytes.byteLength>p)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),R(500,ht);let O=c.method==="HEAD";if(O&&x.size!==void 0&&x.size>p)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),R(500,ht);if(!O&&x.size!==void 0&&x.size!==x.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=size_mismatch`),R(500,ht);let w=S??co(x.contentType),v=w!==null&&ii.has(w),_=v?w:"application/octet-stream",q=v&&d.kind!=="download"?"inline":"attachment",J=O?x.size:x.bytes.byteLength,G=new Headers({"Content-Type":_,"Content-Disposition":`${q}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Gt});return J!==void 0&&G.set("Content-Length",String(J)),y&&G.append("Set-Cookie",y),a(u,!0),o.info(`200 attachment=${u} viewer=${h} type=${_} disposition=${q} bytes=${J??"-"}`),O?new Response(null,{status:200,headers:G}):(T=!0,new Response(Nu(x.bytes,C),{status:200,headers:G}))}finally{T||C()}}};var qe=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),$f=qe.queueWaitMs+qe.readMs+qe.renderMs+qe.transferMarginMs;import{Buffer as Ou}from"buffer";var yi=new Set([194,198,202,206]),Hu=new Set([192,193,194,195]),hi=216,Fu=217,fi=218,$u=4,Uu=64,Bu=2,pi=8,mi=28,It=12,po=8,Vu=20,Ri=It+po+10,qu=2,Rt=(e,t)=>e[t]<<8|e[t+1],Kt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},ct=(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},Si=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,gi=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),bi=e=>(e.stepsLeft-=1,e.stepsLeft>=0),Di=e=>e[0]===255&&e[1]===hi,Ti=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!bi(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===Fu)return"eoi";if(o===0||o===hi)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=Rt(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")}},ju=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!bi(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}},Ai=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=Rt(e,r+1),a=Rt(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}},Ei=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>$u||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},wi=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:yi.has(e.marker)||t<e.components.length}),mo=e=>{if(!Di(e))return null;let t=gi(e.byteLength),r=null;for(let n=2;;){if(Ti(e,n,t)!=="segment")return null;if(Si(t.marker)){if(r!==null||(r=Ai(e,t),r===null))return null}else if(t.marker===fi){if(r===null)return null;let o=Ei(e,t);return o===null?null:wi(r,o.length)}n=t.end}},Ii=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*pi)),i=Math.ceil(e.height*o/(r*pi));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},_i=e=>e.multiScan?Ii(e).reduce((r,n)=>r+n,0)*Uu*Bu:0,Wu=896,xi=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!Di(e))return null;let n=Ou.from(e.buffer,e.byteOffset,e.byteLength),o=gi(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let h=Ti(e,u,o);if(h===null)return null;if(h==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,Si(o.marker)){if(a!==null||!Hu.has(o.marker)||(a=Ai(e,o),a===null))return null;let m=Ii(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*(yi.has(a.marker)?Wu:1)}else if(o.marker===fi){if(a===null||d===s)return null;let m=Ei(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=wi(a,m.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let y=ju(n,o.end,o);if(y===null)return null;u=y}}},Ci=e=>{if(e.byteLength<24||Rt(e,8)!==0||Rt(e,10)!==13||!ct(e,12,"IHDR"))return null;let t=Rt(e,16)*65536+Rt(e,18),r=Rt(e,20)*65536+Rt(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Yu=e=>{if(ct(e,It,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Kt(e,26,2)&16383,r=Kt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(ct(e,It,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Kt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return ct(e,It,"VP8X")?e.byteLength<Ri?null:{width:Kt(e,24,3)+1,height:Kt(e,27,3)+1}:null},Mi=e=>{if(Ci(e)===null||e.byteLength<=mi)return null;switch(e[mi]){case 0:return!1;case 1:return!0;default:return null}},ki=(e,t)=>{if(ct(e,It,"VP8 "))return"lossy";if(ct(e,It,"VP8L"))return"lossless";if(!ct(e,It,"VP8X")||e.byteLength<Ri)return null;if((e[Vu]&qu)!==0)return"animated";let r=!1,n=t;for(let o=It;o+po<=e.byteLength;){if(n-=1,n<0)return null;if(ct(e,o,"VP8L"))return"lossless";if(ct(e,o,"VP8 "))return r?"lossy-alpha":"lossy";ct(e,o,"ALPH")&&(r=!0);let a=Kt(e,o+4,4);o+=po+a+a%2}return null},Pi={png:Ci,jpeg:mo,webp:Yu};var yo=Object.freeze(["image/webp","image/jpeg","image/png"]),ho=1024*1024;var zu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Gu={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Ku=new Set(yo),Ju=e=>typeof e=="string"&&Ku.has(e),Qu=256,jr=(e,t)=>e.fileType===null||!zu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Xu=[137,80,78,71,13,10,26,10],Zu=[255,216,255],ed=[[71,73,70,56,55,97],[71,73,70,56,57,97]],td=[82,73,70,70],rd=[87,69,66,80],Sr=(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},fo=e=>{if(Sr(e,Xu,0))return"png";if(Sr(e,Zu,0))return"jpeg";for(let t of ed)if(Sr(e,t,0))return"gif";return Sr(e,td,0)&&Sr(e,rd,8)?"webp":null},vi=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])}},Li=(e,t)=>{if(!Ju(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>ho)return"too_large";let r=Gu[e.contentType];if(fo(e.bytes)!==r)return"signature";let n=Pi[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Ni=e=>{ie("maxBytes",e.maxBytes,0),ie("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)+Qu;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 Ro=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=se(),l=new AbortController,s=!1,c,d,u=()=>{a(se()-i)},h=S=>{c=Ze(()=>{s=!0,S({timedOut:!0}),d=Ze(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(se()-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 St={404:"Attachment not found",500:ht,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Oi=(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=Li(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},nd=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ze(r,qe.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Hi=()=>{},od=(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)}),Fi=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(Hi,Hi);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=nd(y);try{if(await od(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 E=Ro({budgetMs:qe.readMs,flightSignal:y,call:F=>m.readAttachment(m.filePath,{maxBytes:n,head:!1,principal:o(m.owner),signal:F}),onOverrun:u("read",m),onStuck:h("read",m)}),S=await E.outcome;if(S.timedOut)return f=E.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 Vr(g.reason)?(g.reason==="not_found"&&a(m.attachmentId,!1),{kind:"failure",status:qr(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 C=d(m,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),T=F=>{C==="verified"&&r.set(m.key,F)},x=F=>(T(F),{...F,identity:C});if(!g.ok)return x({kind:"unrenderable",reason:"too_large"});let O=fo(g.bytes);if(O===null)return x({kind:"unrenderable",reason:"signature"});let w=Ro({budgetMs:qe.renderMs,flightSignal:y,call:F=>m.renderer.render(g.bytes,{format:O,maxWidth:m.box.maxWidth,maxHeight:m.box.maxHeight,signal:F}),onOverrun:u("render",m),onStuck:h("render",m)}),v=F=>{if(F.kind==="error")return;let I=Oi(F.value,m.box);"entry"in I&&T(I.entry)},_=null,q=()=>(_===null&&(_=w.settled.then(v),s(m.key,_)),_);y.addEventListener("abort",q,{once:!0});let J=await w.outcome.finally(()=>y.removeEventListener("abort",q));if(J.timedOut||y.aborted)return f=q(),y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let G=Oi(J.value,m.box);return"entry"in G?x(G.entry):G.failure}finally{f===null?p():f.then(p,p)}}};var $i=()=>{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 Vi=10,ad=1/Vi,Ui=1-ad,id=1024,sd=64,ld=8,Bi="private, no-cache",cd="no-store",ud=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),dd=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},qi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(S,g)=>ft({reason:S,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:C=>`viewer=${C} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*Vi),h=lt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:sd,maxPerOwner:ld,maxWaitMs:qe.queueWaitMs}}),m=Ni({maxBytes:l.cacheBytes,maxEntries:id}),y=$i(),R=Fi({gate:h,cache:m,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),p=(S,g,C,T)=>{let x=`attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail cache=${T}`;if(g.kind==="failure")return o[dd(g)](`${g.status} ${x} reason=${g.reason} code=${g.code??"-"}`),S.fail(g.status,St[g.status],Ae(g.status));let O=ud[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${x} reason=${g.reason}${O}`),S.fail(404,St[404]);let w=g.identity==="verified"?{"Cache-Control":Bi,ETag:C}:{"Cache-Control":cd},v=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...w,"Content-Security-Policy":"default-src 'none'; sandbox",...Gt});return S.cookie&&v.append("Set-Cookie",S.cookie),o.info(`200 ${x} type=${g.contentType} bytes=${g.bytes.byteLength}${O}`),new Response(g.bytes,{status:200,headers:v})},f=(S,g)=>{let C=S.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return C===null?null:g.fail(C.status,C.message,C.headers)},D=S=>f(d,S),E=(S,g)=>g?f(u,S):D(S);return async(S,g)=>{let{request:C,attachmentId:T,internalUserId:x,readAttachment:O,cookie:w,fail:v}=S,_=to[g],q=C.headers.get("If-None-Match"),J=q!==null,G=E(S,J);if(G)return G;let F=await n(C,"initial");if(!F.ok)return v(503,St[503],Ae(503));let I=await t.getAttachmentForUser(F.scope,T,x),W=I!==null&&jr(I,i)?vi({rendererId:s.id,box:_,attachmentId:T,filePath:I.filePath,fileType:I.fileType,fileSize:I.fileSize}):null;if(W&&oo(q,W.etag)){let b=new Headers({"Cache-Control":Bi,ETag:W.etag,...Gt});return w&&b.append("Set-Cookie",w),o.info(`304 attachment=${T} viewer=${x} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:b})}if(J){let b=D(S);if(b)return b}if(!I)return o.warn(`404 attachment=${T} viewer=${x} variant=thumbnail reason=not_visible`),v(404,St[404]);if(!W)return d.refund(x,Ui),o.info(`404 attachment=${T} viewer=${x} variant=thumbnail reason=not_eligible`),v(404,St[404]);let{key:ce,etag:ne}=W,de=m.get(ce);if(de)return d.refund(x,Ui),p(S,{...de,identity:"verified"},ne,"hit");let Se=b=>R({key:ce,attachmentId:T,filePath:I.filePath,fileSize:I.fileSize,box:_,owner:x,readAttachment:O,renderer:s},b),Q;try{Q=await y.join(ce,C.signal,Se)}catch(b){return o.error(`500 attachment=${T} viewer=${x} variant=thumbnail cache=miss reason=port_exception message=${b instanceof Error?b.message:"unknown"}`),v(500,St[500])}return p(S,Q,ne,"miss")}};var pd='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',md=()=>Br(403,lo,{cookie:null}),ji=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=ro(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Br(404,Rr[404],{cookie:null}),crossSiteRejection:md}),Wi=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:ai(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:di({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:qi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,h=(m,y,R={})=>Br(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=ro(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(pd);let p=s.idCodec.decode(d.token);if(p===null||!it(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,St[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,ht)}}};var yd=32*1024*1024,hd=60,fd=4,Rd=120,Sd=2,gd=8*1024*1024,Wr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bd=e=>{if(e===void 0)throw Ye("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Wr(e))throw K("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Ye("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw K("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw K("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Dd=e=>{if(e===void 0)return null;if(!Wr(e))throw K("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:bd(e.renderer),rateLimitPerMinute:Ne("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Rd),concurrency:Ne("attachments.thumbnails.concurrency",e.concurrency,1,Sd),cacheBytes:Ne("attachments.thumbnails.cacheBytes",e.cacheBytes,0,gd)})},Yi=e=>{let t=e;if(t===void 0)return null;if(!Wr(t))throw K("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Ye("attachments.idCodec","injected when attachments is given");if(!Wr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw K("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Ye("attachments.read","injected when attachments is given");if(typeof n!="function")throw K("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Ne("attachments.maxBytes",t.maxBytes,1,yd),rateLimitPerMinute:Ne("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,hd),concurrency:Ne("attachments.concurrency",t.concurrency,1,fd),thumbnails:Dd(t.thumbnails)})},Td=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"]]),Yr=e=>{for(let[t,r]of Td)if(Object.hasOwn(e,t))throw Ye(r,`given in place of the flat key ${t}`)};var Gi=8,Ad=8*Gi,Ed=128,wd=2,Ki=wd*Ed,Id=4*Ki,_d=6e4,xd=6e4,Cd="Too many reads",zi=Object.freeze(Object.keys(Ft).filter(e=>Ft[e].admission.includes("miss-gate"))),Ji=e=>{let t=lt({limit:Ad,maxHeldPerOwner:Gi,queue:{max:Id,maxPerOwner:Ki,maxWaitMs:_d}}),r=Me({windowMs:xd,tallies:zi,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${zi.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}})}},zr=(e,t,r)=>{let n=e(t,r,{error:{message:Cd}},503);for(let[o,a]of Object.entries(Ae(503)))n.headers.set(o,a);return n};var Qi=e=>{let t=e.get(be.cursorReportHubId),r=e.get(be.cursorBusinessDate),n=e.get(be.cursorSnapshot),o=xa(n)?n:null,a=null;if(t!==null){let l=Xe(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!_a(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=hr(e.get(be.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var Gr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Md=2,kd=16,Pd=Md*kd,vd=6e4,Xi=()=>{},Ld=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Zi=e=>{let t=lt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Pd,queue:null}),r=Me({windowMs:vd,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 Xi;if(a.aborted){if(t.canAcquire(n))return Xi}else{let i=await t.acquire(n,a);if(i!==null)return Ld(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var Kr=30,os=4e3,Nd="stream interrupted by server error",Od="Too many streams",Hd=15e3,as=Symbol("ids-stream-heartbeat"),es=()=>{},ts=e=>e.return(void 0).then(es,es),Fd=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(as),Hd)}),stop:()=>clearTimeout(e)}};async function*rs(e,t,r,n){let o=t?ka(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:os),e.length),l=zt(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 is=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...st});return e&&t.append("Set-Cookie",e),t},ns=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await ts(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=Fd();try{s===null&&(s=t.next());let h=await Promise.race([s,u.fired]);if(u.stop(),h===as){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 Qe||n.error(`ids-stream emission failed: ${h instanceof Error?h.message:String(h)}`);try{let m={kind:"error",error:Nd};d.enqueue(i.encode(`${JSON.stringify(m)}
4
+ `)),d.close()}catch{}}},cancel(){l=!0,o(),ts(t)}});return new Response(c,{status:200,headers:is(e)})},ss=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,Kr).then(g=>({items:g,streamAnchor:S}))).then(S=>R?.(S),S=>p?.(S))}});if(D.catch(()=>{}),l.cursor){let{items:S,streamAnchor:g,snapshot:C}=await D,T=l.snapshot!==null&&l.snapshot===C;return ns(d,rs(S,T?l.cursor:null,Kr,{snapshot:C,restarted:!T,streamAnchor:g}),u,r,h)}let E=(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,C=!1;if(S.kind==="full")g=S.source;else if(S.kind==="page"){let{items:T,streamAnchor:x}=S.page;if(T.length<Kr){yield{kind:"chunk",...zt(T,0,T.length),nextCursor:null,isLast:!0,total:T.length,streamAnchor:x};return}yield{kind:"chunk",...zt(T,0,T.length),nextCursor:null,isLast:!1,provisional:!0},C=!0}else if(S.kind==="full-error"&&y){let T=await f.catch(()=>null);T&&T.items.length>0&&(yield{kind:"chunk",...zt(T.items,0,T.items.length),nextCursor:null,isLast:!1,provisional:!0})}g===null&&(g=await D),yield*rs(g.items,null,C?os:Kr,{snapshot:g.snapshot,streamAnchor:g.streamAnchor})})();return ns(d,E,u,r,h)};return async(l,s,c,d,u,h)=>{let m=Qi(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=Gr(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:Od}},503);for(let[E,S]of Object.entries(Ae(503)))D.headers.set(E,S);return D}if(R.aborted)return new Response(null,{status:200,headers:is(s)});try{return await i(y,d,u,s,R,f,p===null?void 0:o.admissionFor(p,le.idsStream,R))}catch(D){if(f(),D instanceof Qe)return zr(h,c,s);throw D}}};import{inArray as $d,sql as Jr}from"drizzle-orm";var je="Internal",ls=e=>e.trim().toLowerCase();var Ud="",Bd=64,Vd=e=>e.toLowerCase(),cs=e=>{let t=new Set;if(!Array.isArray(e))return t;for(let r of e){if(typeof r!="string")continue;let n=ls(r);n.length>0&&t.add(n)}return t};function Ie(e,t){return e===null?!0:t==null?!1:e.has(Vd(t))}function Fe(e){return e!==null&&e.size===0}var qd=4e3,go=e=>{let t=e.getSQLType();if(!t.startsWith("nvarchar("))throw K("tables.hub.sourceType","an nvarchar(n) column with a declared length (source types compare as UTF-16 bytes)",t);return ie("tables.hub.sourceType.length",e.length,1,qd)};function br(e,t){if(t===null)return;let r=go(e),n=[...t].filter(a=>a.length<=r);if(n.length===0)return Jr`1 = 0`;let o=Jr.raw(`VARBINARY(${2*r})`);return $d(Jr`CAST(LOWER(${e}) AS ${o})`,n.map(a=>Jr`CAST(${a} AS ${o})`))}var Jt,Qt,gr=class gr{constructor(t,r){wn(this,Jt);wn(this,Qt);In(this,Jt,t),In(this,Qt,r)}get visible(){return nr(this,Jt)===null?null:new Set(nr(this,Jt))}get commentable(){return nr(this,Qt)===null?null:new Set(nr(this,Qt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=cs(r?t.read:t);if(!r||t.comment===void 0)return new gr(n,n);let o=new Set;for(let a of cs(t.comment))n.has(a)&&o.add(a);return new gr(n,o)}static unrestricted(t){return new gr(null,null)}};Jt=new WeakMap,Qt=new WeakMap;var et=gr,So=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),jd=new Set(["read","comment"]),ds=e=>{if(So(e))return et.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?et.unrestricted(o):null}let{read:r,comment:n}=e;return t.every(o=>jd.has(o))&&So(r)?n===void 0?et.restrictTo({read:r}):So(n)?et.restrictTo({read:r,comment:n}):null:null};function Qr(e){let t=us(e.visible),r=us(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function us(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Ud);if(t.length<=Bd)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 ps=(e,t,r,n)=>Ie(n.commentable,t)||e.authorUserId===r;import{parseQuerySets as _p}from"@aiquants/fuzzy-search";import{createHash as Wd}from"crypto";import{setImmediate as ms}from"timers/promises";import{clusterCountOf as Yd,DEFAULT_NORMALIZE_OPTIONS as Zr,InteriorPairs as zd,isAnswerTier as Gd,normalizeText as Kd,queryNeedles as Jd,resolveNormalizeOptions as Qd,toMappedFormsInto as Xd,trimmedRange as Zd}from"@aiquants/fuzzy-search/normalize";var en=`
5
+ `,bo=4e3,ep=1,Rs=new Set([8203,8288,65279,173]),tp=new RegExp(`[${String.fromCodePoint(...Rs)}]`,"gu"),Ss=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),gs=/(\s+)/u,rp=/^\s+$/u,np=new RegExp(gs.source,"gu"),op=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,ap=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]),tn=e=>e.replace(tp,"");var Do=e=>Kd(e,Zr),Xr=e=>Do(tn(e)),ip=Qd({...Zr,convertRomaji:!0},"[daily-report] search reading options"),sp=3,lp=/^[-ー]+/u,cp=/[^\p{L}\p{M}]/gu,up=/ー{2,}/gu,dp=/\p{Script=Latin}/u,ys=/(?=\p{L})\p{Script=Latin}/u,pp=e=>Yd(e.replace(lp,"").replace(cp,"").replace(up,"\u30FC")),mp=(e,t)=>{for(let r of t)if(!Gd(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})`)},bs=e=>{if(!ys.test(e))return[];let t=Xr(e);if(!ys.test(t))return[];let r=Jd(t,ip,!1);mp(t,r);let n=[];for(let o of r){if(o.tier===Ht.word)continue;let a=Xr(o.text);if(!(a.length===0||a.length>Ce.maxWordLength)&&!(a===t||dp.test(a))&&!(pp(a)<sp||n.includes(a))&&(n.push(a),n.length===Gn))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},Ds=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&To(e,t-1)?t-2:t-1;return op.test(String.fromCodePoint(r))&&!ap.has(e.codePointAt(n))},yp=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!Ds(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(gs)){let c=o;if(o+=s.length,i+s.length<=t){i===0&&(a=c),i+=s.length;continue}if(l(),rp.test(s))continue;if(s.length<=t){a=c,i=s.length;continue}let d=yp(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}},hp=(e,t)=>{let r=0;for(let n of e.matchAll(Ss))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},fp=(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},Ts=(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=fp(Xd(d,Zr,new zd(0)),d),[h,m]=Zd(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}},rn=(e,t=bo)=>{let r=[],n=0;return hp(tn(e),o=>{let a=Eo(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(en),forcedCuts:n}},As=e=>e.filter(t=>t.length>0).join(en),wo=(e,t)=>{let r=null;return{advance:n=>{if(r!==null)return 0;e.units=ie("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}}},hs=4096;function*Rp(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);Rs.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+=hs)r.push(Reflect.apply(String.fromCharCode,null,c.subarray(d-s,Math.min(o,d+hs)-s)))}i=l}return a?{text:r.join(""),rawIndex:n.subarray(0,o)}:{text:e,rawIndex:null}}var Es=e=>{let t={units:0};return wo(t,Rp(e,t))};function*Sp(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(Ss)){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 ws=(e,t)=>{let r={units:0};return wo(r,Sp(e,t,r))};function*fs(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,Ds(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*gp(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(np)){let f=m+p.index;f>R&&u(f),R=f+p[0].length;let D=h(R);if(D>=0){let E=yield*fs(e,D,f,t,r);o+=E.forcedCuts,n.push(E.pieces)}}y>R&&u(y),m=y}if(d(l,s,c)){let m=yield*fs(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 Is=(e,t)=>{let r={units:0};return wo(r,gp(e,t,r))},bp=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
6
+ `)},Dp=[`\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`],Tp=["","\u30A2","\u4F50"," "],Ap=()=>JSON.stringify(Dp.map(e=>rn(e,8))),Ep=e=>`dr-search-v${ep};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var wp=async()=>{let e=Wd("sha256");e.update(JSON.stringify(Zr));for(let t of Tp)await ms(),e.update("\0"),e.update(Do(bp(t)));return await ms(),e.update("\0"),e.update(Ap()),Ep(e.digest("hex"))},Ip=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},Io=Ip(wp);var xp=/^-+/u,Cp=/\s+/u,_s=e=>{let t=xp.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Mp=(e,t)=>{let r=[..._s(e).map(n=>({text:n,tier:Ht.word})),...t.flatMap(n=>_s(n).map(o=>({text:o,tier:Ht.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},kp=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),nn=(e,t)=>{if(e.length>Ce.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of _p(tn(e),t).sets){let i=[],l=new Set;for(let c of a.split(Cp)){let d=Xr(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>Ce.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=Mp(d,bs(c)),h=kp(u);l.has(h)||(l.add(h),i.push({alternatives:u}))}if(i.length>Ce.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>Ce.maxSets?{ok:!1,reason:"too-many-sets"}:o>Ce.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},Dr=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var pS=Object.freeze({sourceTypes:null,authors:null,customers:null}),Pp=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,xs=(e,t,r)=>{if($a(e)&&Pp(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=nn(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var Cs=6e4,vp=1,Lp=3200,Ms=2e3,Np=Object.freeze({search:Lp,reports:Ms,"search-marks":Ms,"search-facets":null}),Op=(e,t)=>{let r=Np[e];return r===null?null:{max:t,maxPerOwner:Fr,maxWaitMs:r}},Tr=e=>{let{concurrency:t,route:r,logger:n}=e,o=ft({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:Cs,logger:n,windowFields:()=>`route=${r}`}),a=lt({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:Op(r,t)}),i=Object.freeze({status:429,message:uo,headers:Object.freeze({"Retry-After":String(vp)})}),l=Me({windowMs:Cs,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})}}};import{systemSseRuntime as Wp}from"@aiquants/sse";import{createSseResponse as Yp,readLastEventId as zp,startSseHeartbeat as Gp,terminalStreamResponse as Kp}from"@aiquants/sse/server";var Ar=(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=Bn.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}},ks=new WeakMap,Ps=(e,t,r)=>{let n=ks.get(e);n===void 0&&(n=new Map,ks.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,Hp=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)}}},Fp=(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})},vs=(e,t,r)=>{let{parsed:n}=e;if(n.type!=="report-create"&&n.type!=="report-update"&&n.type!=="report-publish")return Ps(e,"every-viewer",()=>JSON.stringify(Hp(n)));let o=n.actorRawUserId===t;return Ps(e,`${o?"actor":"observer"}${r?"-comments-redacted":""}`,()=>JSON.stringify(Fp(n,o,r)))};import{systemSseRuntime as $p}from"@aiquants/sse";import{createSharedSource as Up}from"@aiquants/sse/shared-source";var _t="daily-report:ids:",xo=(e,t)=>`${e}st:${t}`,Co=e=>`${_t}user:${e}:`,Ls=(e,t)=>xo(Co(e),t),Xt=e=>`daily-report:date:${e}:user:`,Zt=(e,t)=>`${Xt(e)}${t}:`,Ns=(e,t,r)=>xo(Zt(e,t),r),Ge=e=>`daily-report:detail:${e}:user:`,Mo=(e,t)=>`${Ge(e)}${t}:`,Os=(e,t,r)=>xo(Mo(e,t),r);var gt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},Bp=5e3,Vp=$r,Er=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=De(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:wt}_createSource(){return Up({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:$p,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:Bp,COUNT:Vp});if(i)for(let l of i)for(let s of l.messages){a=s.id;let{entry:c,json:d}=Ar(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(_t),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ge(n))}};var qp=6e4,wr="Report visibility is unavailable",Hs=["initial","refresh"],Fs=Object.freeze({ok:!1}),jp=e=>e===null?"null":Array.isArray(e)?"array":typeof e,$s=(e,t)=>{let r=Me({windowMs:qp,tallies:Hs,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{t.error(`visibility_unavailable_suppressed count=${o} since=${a} cause=${n} reasons=${Hs.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)),Fs}let i=ds(a);return i===null?(r.record("port_contract",o,()=>t.error(`visibility unavailable cause=port_contract reason=${o} answer=${jp(a)}`)),Fs):{ok:!0,scope:i}}},Us=(e,t,r)=>{let n=e(t,r,{error:{message:wr}},503);for(let[o,a]of Object.entries(Ae(503)))n.headers.set(o,a);return n};var Vs=Object.freeze({...fr,route:"sse",frameworkDataRefusal:Ur}),Bs=864e5,Jp={baseMs:2e3,jitterMs:8e3},qs=6e4,ko=$r,js=JSON.stringify({type:"connected"}),Qp=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},Xp=(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 Ie(t,e.report.sourceType);case"comment-add":case"comment-delete":return Ie(r,e.sourceType);case"report-delete":return Ie(t,e.sourceType)}},Zp=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Ie(t,e.report.sourceType),em=(e,t)=>{e.writeEvent({event:null,id:t,data:js})},tm=(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||!Xp(o,r.visibleSet,r.commentableSet)){em(e,t.id);return}e.writeEvent({event:null,id:t.id,data:vs(n,r.internalUserId,Zp(o,r.commentableSet))})},Ws=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 _=++f;n(h,"refresh").then(q=>{if(_===f){if(!q.ok){d.close();return}R=q.scope.visible,p=q.scope.commentable}})},qs);d.onClose(()=>clearInterval(D));let E=y===null?wt:y,S=y!==null&&o!==void 0,g=[],C=null,T=_=>{gt(_.id,E)||(E=_.id,tm(d,_,{internalUserId:m,visibleSet:R,commentableSet:p}))},x=async(_,q)=>{let[J]=await _.xRange(i,"-","+",{COUNT:1});return J!==void 0&&!gt(J.id,q)},O=async(_,q)=>{let[J]=await _.xRange(i,"-","+",{COUNT:1});if(J===void 0)return!0;let G;if(q===wt){if(Qp(await _.xInfoStream(i))>0)return!1;G=J.id}else{if(!gt(J.id,q))return!1;G=q}for(;;){let F=await _.xRange(i,G,"+",{COUNT:ko}),I=F[0];if(I!==void 0&&I.id!==G&&await x(_,G))return!1;for(let W of F){if(C!==null&&gt(C,W.id))return!0;gt(W.id,E)||T(Ar(W,s).entry)}let U=F.at(-1);if(F.length<ko||U===void 0||d.isClosed())return!0;G=U.id}},w=a.subscribe(_=>{if(!S){T(_);return}gt(_.id,E)||(C===null&&(C=_.id),g.push(_))},_=>{s.error(`[SSE:${m}] Fan-Out reader error:`,_),d.close()});if(d.onClose(w),y===null){await a.ready();try{let _=await o?.getClient();if(_){let q=await _.xRevRange(i,"+","-",{COUNT:1});q.length>0&&!gt(q[0].id,E)&&(E=q[0].id)}}catch{}}if(d.writeEvent({event:null,id:E===wt?null:E,data:js}),Gp(d,{intervalMs:ga,retry:Jp,runtime:Wp}),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 O(v,y)){d.writeRetry(Bs),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}S=!1;for(let _ of g.splice(0))T(_)};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(st))R.set(p,f);return R},y=R=>Kp(R,{data:"",retryMs:Bs,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=zp(d,ba);if(D!==null&&!Da(D))return s.warn(`[SSE:${f}] malformed resume cursor; asking the client to resync`),y("resync-required");let E=Gr(d),S=await l.admit(f,"sse",E);if(S===null){let C=m();for(let[T,x]of Object.entries(Ae(503)))C.set(T,x);return new Response("Too many streams",{status:503,headers:C})}let g=!1;try{let C=await n(d,"initial");if(!C.ok){let x=m();for(let[O,w]of Object.entries(Ae(503)))x.set(O,w);return new Response(wr,{status:503,headers:x})}let T=C.scope;return Yp({requestSignal:E,headers:m(),onError:(x,O)=>s.error(`[SSE:${f}] ${O} failed:`,x),produce:x=>(g=!0,x.onClose(S),c(x,{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 Ys=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...st});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},nm=Object.freeze({...fr,route:"api",frameworkDataRefusal:({params:e})=>eo(e.endpoint)&&Ft[e.endpoint].body==="stream"?Ur():null}),om=Object.freeze({...fr,route:"action"}),am=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),Qs=6e4,Xs=5,im=Xs*Math.ceil(Qs/500),sm=2,lm=6,cm=6e4,um=Xs*sm*lm,dm=2,pm=10,mm=2,ym=10,zs=(e,t)=>Math.max(e,Fr)*t,Zs=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},hm=Object.freeze({etag:(e,t,r)=>ei(e,t,r,200),"no-store":(e,t,r)=>ao(t,r,200)}),fm=e=>io(e.body==="json"?hm[e.cache]:null),Gs=io(null),Ks=(e,t,r,n)=>Zs(e(t,r,{error:{message:n.message}},n.status),n.headers),Js=(e,t,r)=>Zs(e(t,r,null,503),Ae(503));function Po(e){Yr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:ie("service.titleMaxLength",r.titleMaxLength,1)},{loginRedirectPath:s}=e;if(typeof s!="string"||s.trim()==="")throw K("loginRedirectPath","the non-blank path of the host's sign-in route",s);let c=De(e.logger,3,"API"),d=De(e.logger,3,"Visibility"),u=$s(or("resolveVisibleSourceTypes",e.resolveVisibleSourceTypes),d),h=De(e.logger,1,"SSE"),m=De(e.logger,1,"Attachment"),y=De(e.logger,2,"Isolation"),R=De(e.logger,2,"Action"),p=De(e.logger,2,"Search"),f=De(e.logger,2,"Refresh"),D=De(e.logger,2,"Streams"),E=De(e.logger,2,"Reads"),S=ft({reason:"refresh_rate_limit",limitPerWindow:um,windowMs:cm,logger:f,windowFields:()=>"route=api"}),g=Zi(D),C=Ji(E),T=async(b,N,L,P,H,Y)=>{let X=await r.getUserIdByExternalId(N.id);try{return await Y(X===null?void 0:C.admissionFor(X,b,L.signal))}catch(z){if(z instanceof Qe)return zr(H,L,P);throw z}},x=(b,N,L,P,H)=>{let Y=S.spend(N.id,`endpoint=${b}`);return Y===null?null:Ks(H,L,P,Y)},O=async({request:b})=>{let{user:N,cookie:L}=await t(b,{failureRedirect:s}),P=new Headers;L&&P.append("Set-Cookie",L);let H=await r.getUserIdByExternalId(N.id),Y=H?n(H):null;return{data:{user:N,userId:Y},headers:P}},w=b=>{let{limiter:N}=b;return async(L,P,H,Y,X,z)=>{if(N===null)return z(H,P,{error:{message:"Unknown endpoint"}},404);let M=b.parse(L);if(!M.ok)return z(H,P,M.invalid,400);let k=await r.getUserIdByExternalId(Y.id);if(!k)return z(H,P,b.emptyAnswer(M.parsed),200);let{signal:A}=H,$=await N.admit(k,A);if("refusal"in $)return A.aborted?Js(z,H,P):Ks(z,H,P,$.refusal);try{A.throwIfAborted();let j=await b.read(M.parsed,{userId:k,user:Y,scope:X},A);return A.throwIfAborted(),z(H,P,j,200)}catch(j){if(A.aborted&&j===A.reason)return Js(z,H,P);throw j}finally{$.release()}}},v=r.searchLimits===null?null:Tr({...r.searchLimits,route:le.search,logger:p}),_=r.searchLimits===null?null:Tr({concurrency:zs(r.searchLimits.concurrency,dm),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*pm,route:le.reports,logger:p}),q=r.searchLimits===null?null:Tr({concurrency:zs(r.searchLimits.concurrency,mm),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*ym,route:le.searchMarks,logger:p}),J=r.searchLimits===null?null:Tr({...r.searchLimits,route:le.searchFacets,logger:p}),G={[le.businessDate]:async(b,N,L,P,H,Y)=>{let X=b.searchParams.get(be.businessDate),z=X===null?null:jt(X);if(z===null)return Y(L,N,{error:{message:"Invalid business date"}},400);let M=hr(b.searchParams.get(be.forceRefresh));if(M===null)return Y(L,N,{error:{message:"Invalid forceRefresh"}},400);let k=M?x(le.businessDate,P,L,N,Y):null;return k!==null?k:T(le.businessDate,P,L,N,Y,async A=>{let $=await r.getDailyReportsByBusinessDateByExternalId(H,z,P.id,{forceRefresh:M,admission:A});return Y(L,N,{businessDate:z,reports:$},200)})},[le.idsStream]:ss({service:r,logger:c,streamSlots:g,missGate:C,refuseForcedRead:(b,N,L,P)=>x(le.idsStream,b,N,L,P)}),[le.report]:async(b,N,L,P,H,Y)=>{let X=Xe(b.searchParams.get(be.reportHubId));if(X===null)return Y(L,N,{error:{message:"Invalid reportHubId"}},400);let z=hr(b.searchParams.get(be.forceRefresh));if(z===null)return Y(L,N,{error:{message:"Invalid forceRefresh"}},400);let M=z?x(le.report,P,L,N,Y):null;return M!==null?M:T(le.report,P,L,N,Y,async k=>{let A=await r.getDailyReportDetailByIdByExternalId(H,X,P.id,{snapshot:!0,forceRefresh:z,admission:k});return A?Y(L,N,{report:A},200):Y(L,N,{error:{message:"Report not found"}},404)})},[le.search]:w({limiter:v,parse:b=>{let N=b.searchParams.get(be.searchQuery),L=Xn(b.searchParams.get(be.searchCombine));if(N===null||L===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let P=Ba(b.searchParams,r.searchFilterSourceTypes);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:P.reason}}};let H=xs(N,L,P.filters);if(!H.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:H.reason}}};let{criteria:Y}=H;return{ok:!0,parsed:{criteria:Y,words:Y.plan===null?[]:Dr(Y.plan)}}},emptyAnswer:({words:b})=>Kn([],b),read:async({criteria:b,words:N},{userId:L,scope:P})=>Kn(await r.searchDailyReports(P,L,b),N)}),[le.reports]:w({limiter:_,parse:b=>{let N=Zn(b.searchParams.get(be.reportIds));return N===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:N}},emptyAnswer:b=>({outcomes:b.map(yr)}),read:async(b,{user:N,scope:L},P)=>({outcomes:await r.getDailyReportDetailsByIdsByExternalId(L,b,N.id,{signal:P})})}),[le.searchMarks]:w({limiter:q,parse:b=>{let N=b.searchParams.get(be.searchQuery),L=Xn(b.searchParams.get(be.searchCombine));if(N===null||L===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let P=nn(N,L);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:P.reason}}};let H=Zn(b.searchParams.get(be.reportIds));return H===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:P.plan,ids:H}}},emptyAnswer:({plan:b})=>({wordsDigest:Hr(Dr(b)),reports:[],deferred:[]}),read:({plan:b,ids:N},{userId:L,scope:P},H)=>r.markDailyReportSearchHits(P,L,b,N,{signal:H})}),[le.searchFacets]:w({limiter:J,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(b,{userId:N,scope:L})=>r.listDailyReportSearchFacets(L,N)})},F=async({request:b,params:N})=>{let{user:L,cookie:P}=await t(b,{failureRedirect:null}),H=P??null;if(!L)return Gs(b,H,{error:{message:"Unauthorized"}},401);let Y=N.endpoint;if(!eo(Y))return Gs(b,H,{error:{message:"Unknown endpoint"}},404);let X=Ft[Y],z=fm(X),M=Qa[X.body];if(!M.includes(b.method)){let A=z(b,H,{error:{message:"Method not allowed"}},405);return A.headers.set("Allow",M.join(", ")),A}let k=se();try{let A=new URL(b.url),$=await u(b,"initial"),j=$.ok?await G[Y](A,H,b,L,$.scope,z):Us(z,b,H);return X.body==="json"&&c.debug(j.headers.has("ETag")?`${j.status} endpoint=${Y} etag_match=${j.status===304}`:`${j.status} endpoint=${Y}`),j}catch(A){let $=se()-k,j=A instanceof Error?A:new Error(String(A));return c.error(`500 endpoint=${Y} elapsed=${$}ms name=${j.name} code=${"code"in j?j.code:"N/A"} message=${j.message}`,j),z(b,H,{error:{message:"Internal Server Error"}},500)}},I=Ja(R),U=ft({reason:"rate_limit",limitPerWindow:im,windowMs:Qs,logger:R,windowFields:()=>"route=action"}),W=async(b,N,L,P,H)=>{let{clientTempId:Y}=b;if(b.intent==="create")try{let A=await r.createDailyReport(L,N,b.businessDate,Y);return H(b,A.reportHubId,{report:A})}catch(A){if(A instanceof Error&&A.message==="Forbidden")return P({error:"Creating reports is restricted"},{status:403});throw A}let{reportHubId:X,businessDate:z}=b,M=async(A,$)=>{try{let j=await $();return H(A,X,{updatedStatus:{isStarred:j.isStarred,isRead:j.isRead,readContentDigest:j.readContentDigest},operationTimestamp:A.operationTimestamp})}catch(j){if(j instanceof Error&&j.message==="Not Found")return P({error:"Report not found"},{status:404});throw j}},k=A=>A instanceof Error?A.message==="Forbidden"?P({error:"Reports from this source are read-only"},{status:403}):A.message==="Unauthorized"?P({error:"Unauthorized"},{status:403}):A.message==="Not Found"?P({error:"Report not found"},{status:404}):null:null;switch(b.intent){case"update":try{return await r.updateDailyReport(L,X,N,b.changes,Y),H(b,X,{})}catch(A){let $=k(A);if($===null)throw A;return $}case"publish":try{let A=await r.publishDailyReport(L,X,N,Y);return H(b,X,{report:A})}catch(A){let $=k(A);if($===null)throw A;return $}case"delete":try{return await r.deleteDailyReport(L,X,N,Y),H(b,X,{})}catch(A){let $=k(A);if($===null)throw A;return $}case"toggleStar":return await M(b,()=>r.setStarStatus(L,N,X,z,b.value,Y));case"toggleRead":return await M(b,()=>r.setReadStatus(L,N,X,z,b.value?{isRead:!0,contentDigest:b.contentDigest}:{isRead:!1},Y));case"addComment":try{let A=await r.addComment(L,N,X,b.content,z,Y);return H(b,X,{newComment:A})}catch(A){if(A instanceof Error){if(A.message==="Not Found")return P({error:"Report not found"},{status:404});if(A.message.startsWith("Comments are restricted"))return P({error:"Comments are restricted for this report"},{status:403})}throw A}case"deleteComment":try{return await r.deleteComment(L,N,X,b.commentId,z,Y),H(b,X,{deletedCommentId:b.commentId})}catch(A){if(A instanceof Error){if(A.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(A.message==="Not Found")return P({error:"Comment not found"},{status:404})}throw A}}},ce=async({request:b,params:N})=>{let{user:L,cookie:P}=await t(b,{failureRedirect:null}),H=(z,M)=>Ys(z,{...M,setCookie:P}),Y=(z,M,k)=>Ys(am(z,M,k),{setCookie:P});if(!L)return H({error:"Unauthorized"},{status:401});let X=se();try{if(N.endpoint!==le.action)return H({error:"Unknown endpoint"},{status:404});let z=U.spend(L.id,"action");if(z!==null)return H({error:z.message},{status:z.status,headers:z.headers});let M=await Ka(b,l);if("refusal"in M){let{refusal:j}=M;return j.status===413&&I(j.measuredBy),H({error:j.error},{status:j.status})}let{command:k}=M;if(k.intent==="clearCache"&&!e.enableDevCacheClear)return H({error:"Invalid intent"},{status:400});let A=await u(b,"initial");if(!A.ok)return H({error:wr},{status:503,headers:{...Ae(503),"Cache-Control":"no-store"}});let $=await r.getUserIdByExternalId(L.id);return $?k.intent==="clearCache"?(await r.clearCache(),H({status:"OK",intent:"clearCache"})):await W(k,$,A.scope,H,Y):H({error:"User not found"},{status:404})}catch(z){if(z instanceof Response)throw z;let M=se()-X,k=z instanceof Error?z:new Error(String(z));return c.error(`500 action elapsed=${M}ms name=${k.name} message=${k.message}`,k),H({error:"Internal Server Error"},{status:500})}},ne=Ws({authenticate:t,service:r,resolveViewerScope:u,redis:o,sseReader:a,streamKey:i,streamSlots:g,logger:h}),de=Wi({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:u,logger:m}),Se=oi(y),Q=(b,N)=>async L=>{let P=ni(L.request)?b.frameworkDataRefusal(L):null;if(P!==null)throw P;let H=rm(L.request,b);return H===void 0?N(L):(Se(b.route,H,L.request),b.crossSiteRejection())};return{index:{loader:O},api:{loader:Q(nm,F),action:Q(om,ce)},sse:{loader:Q(Vs,ne)},attachment:{loader:Q(ji,de)}}}import{chunk as Dy,MAX_IN_LIST as Ty,runWithTransactionRetry as Ay}from"@aiquants/mssql";import{asc as Dt,eq as gn,inArray as bn}from"drizzle-orm";var Rm=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],Sm=["document","comment"],gm=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],bm=["hubId","ordinal","authorUserId","commentText"],vo=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},el=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw _n(e,n,r)},tl=(e,t,r)=>{if(typeof t!="object"||t===null)throw K(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw K(`${e}.${o}`,"a column",n[o])},rl=(e,t)=>{if(!vo(e))throw K("search","a plain object",e);el("search key",e,Rm);let{tables:r}=e;if(!vo(r))throw K("search.tables","a plain object with document and comment",r);el("search.tables key",r,Sm),tl("search.tables.document",r.document,gm),tl("search.tables.comment",r.comment,bm);let n=new Map;if(e.externalSourceTexts!==void 0){if(!vo(e.externalSourceTexts))throw K("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw _n("search.externalSourceTexts key",o,t);if(typeof a!="function")throw K(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:ie("search.concurrency",e.concurrency,1),rateLimitPerMinute:ie("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var xt=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},$t=(e,t)=>{let r=typeof e=="string"?Xe(e):typeof e=="number"&&it(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},Ut=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};import{sql as B}from"drizzle-orm";import{sql as Ct}from"drizzle-orm";var nl=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 Ct.join(e.map(t=>Ct`${t}`),Ct`, `)},an=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return Ct`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${nl(t)}))`},ol=(e,t)=>{let{hubLabel:r,label:n}=e;return Ct`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${nl(t)}))`},sn=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?Ct`${o.userId} = ${t} OR ${o.userId} IS NULL`:Ct`${o.userId} = ${t}`;return Ct`(${a} OR NOT ${an(e,r)})`};var Dm=/[[%_]/gu,Tm=e=>e.replace(Dm,t=>`[${t}]`),al=e=>`%${Tm(e)}%`;var tt=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),Bt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),_r=Object.freeze({value:"value"}),ke=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),V=e=>B`${B.identifier(e.name)}`,Ir=e=>B.join(e.map(t=>B`${t}`),B`, `),il=(e,t)=>B`SELECT ${V(e.id)} AS ${B.identifier(ke.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${Ir(t)}) ORDER BY ${e.id}`,Am=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>al(u.text)),l=B.join(i.map(u=>B`${o.searchText} LIKE ${u}`),B` OR `),s=B.join(i.map(u=>B`${a.commentText} LIKE ${u}`),B` OR `),c=br(n.sourceType,r.scope.commentable),d=c===void 0?B``:B` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return B`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},sl=(e,t,r)=>B`(${B.join(t.words.map(n=>Am(e,n,r)),B` AND `)})`,Lo=(e,t,r,n)=>{let{hub:o}=e,a=[B`${o.deletedAt} IS NULL`,sn(e,t.userId,r,"author")],i=br(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(B`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},Em=(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(B`LOWER(${r.sourceType}) IN (${Ir([...t.sourceTypes])})`)}return t.authors!==null&&o.push(B`${n.authorName} IN (${Ir(t.authors)})`),t.customers!==null&&o.push(B`${n.customerName} IN (${Ir(t.customers)})`),o},ll=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...Lo(e,r,n,o),...Em(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?B` AND `:B` OR `;s.push(B`(${B.join(l.sets.map(d=>sl(e,d,r)),c)})`)}return B`SELECT ${V(a.id)} AS ${B.identifier(tt.reportHubId)}, CONVERT(char(10), ${V(a.businessDate)}, 23) AS ${B.identifier(tt.businessDate)}, ${V(a.sourceType)} AS ${B.identifier(tt.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(s,B` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},cl=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=B.join(t.sets.map((s,c)=>B`(CASE WHEN ${sl(e,s,r)} THEN ${2**c} ELSE 0 END)`),B` + `);return B`SELECT ${V(a.id)} AS ${B.identifier(Bt.reportHubId)}, ${l} AS ${B.identifier(Bt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(Lo(e,r,n,o),B` AND `)}`},ul=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...Lo(e,r,n),B`${i} IS NOT NULL`];return B`SELECT ${i} AS ${B.identifier(_r.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${B.join(l,B` AND `)} GROUP BY ${i} ORDER BY ${i}`},dl=(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 B`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${V(n.hubId)} bigint, ${V(n.searchText)} nvarchar(max), ${V(n.sourceDigest)} char(64), ${V(n.normalizerVersion)} varchar(64), ${V(n.authorName)} nvarchar(max), ${V(n.customerName)} nvarchar(max))) AS s ON t.${V(n.hubId)} = s.${V(n.hubId)}
8
8
  WHEN MATCHED THEN UPDATE SET t.${V(n.searchText)} = s.${V(n.searchText)}, t.${V(n.sourceDigest)} = CONVERT(binary(32), s.${V(n.sourceDigest)}, 2), t.${V(n.normalizerVersion)} = s.${V(n.normalizerVersion)}, t.${V(n.authorName)} = s.${V(n.authorName)}, t.${V(n.customerName)} = s.${V(n.customerName)}, t.${V(n.indexedAt)} = SYSUTCDATETIME()
9
9
  WHEN NOT MATCHED THEN INSERT (${V(n.hubId)}, ${V(n.searchText)}, ${V(n.sourceDigest)}, ${V(n.normalizerVersion)}, ${V(n.authorName)}, ${V(n.customerName)}) VALUES (s.${V(n.hubId)}, s.${V(n.searchText)}, CONVERT(binary(32), s.${V(n.sourceDigest)}, 2), s.${V(n.normalizerVersion)}, s.${V(n.authorName)}, s.${V(n.customerName)});
10
10
  DELETE FROM ${o} WHERE ${o.hubId} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${l}));
11
- INSERT INTO ${o} (${V(o.hubId)}, ${V(o.ordinal)}, ${V(o.authorUserId)}, ${V(o.commentText)}) SELECT ${V(o.hubId)}, ${V(o.ordinal)}, ${V(o.authorUserId)}, ${V(o.commentText)} FROM OPENJSON(${i}) WITH (${V(o.hubId)} bigint, ${V(o.ordinal)} int, ${V(o.authorUserId)} bigint, ${V(o.commentText)} nvarchar(max));`},al=(e,t)=>B`SELECT ${V(e.hubId)} AS ${B.identifier(Me.hubId)}, LOWER(CONVERT(char(64), ${V(e.sourceDigest)}, 2)) AS ${B.identifier(Me.sourceDigest)}, ${V(e.normalizerVersion)} AS ${B.identifier(Me.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${Er(t)})`,il=(e,t,r)=>B`SELECT TOP (${r}) ${V(e.id)} AS ${B.identifier(Me.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var sl=e=>({search:async(t,r)=>He(r.scope.visible)?[]:It(await t.execute(tl(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Ft(o[et.sourceType],et.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${et.sourceType} is null`);return{reportHubId:Ht(o[et.reportHubId],et.reportHubId),businessDate:Ft(o[et.businessDate],et.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(He(r.scope.visible))return new Map;let n=It(await t.execute(rl(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[$t.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${$t.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(Ht(i[$t.reportHubId],$t.reportHubId),l)}return a},facetValues:async(t,r)=>He(r.scope.visible)?[]:It(await t.execute(nl(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Ft(o[wr.value],wr.value);if(a===null)throw new Error(`[daily-report] search: column ${wr.value} is null`);return a})});import{chunk as an,MAX_IN_LIST as sn}from"@aiquants/mssql";import{sql as cl}from"drizzle-orm";import{createHash as mm}from"crypto";var ym=Object.freeze({authorName:"author",customerName:"customer"}),Po=e=>e===null?null:Yn(e),ll=(e,t,r)=>{let n=Po(r);if(n!==null&&n.length>mt.maxValueLength){let o=mt.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${ym[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},Ir=e=>e===null?"n;":`s${e.length}:${e}`,_r="utf16le",hm=e=>{let t=mm("sha256");t.update(`F${e.fields.length};`,_r);for(let[r,n]of e.fields)t.update(Ir(r)+Ir(n),_r);return t.update(`C${e.comments.length};`,_r),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${Ir(r.text)}`,_r)}),t.update(`P;${Ir(Po(e.filterValues.authorName))}${Ir(Po(e.filterValues.customerName))}`,_r),t.digest("hex")},ko=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=en(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=en(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:fs(r),comments:n,sourceDigest:hm(e),forcedCuts:t,authorName:ll(e.hubId,"authorName",e.filterValues.authorName),customerName:ll(e.hubId,"customerName",e.filterValues.customerName)}};var ul=e=>{let t=async(s,c)=>{let d=[];for(let u of an(c,sn))for(let h of It(await s.execute(Zs(e.hub,u))))d.push(Ht(h[Me.hubId],Me.hubId));return d},r=async(s,c)=>{for(let d of an(c,sn))await s.execute(ol(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of an(c,sn))for(let h of It(await s.execute(al(e.tables.document,u))))d.set(Ht(h[Me.hubId],Me.hubId),{sourceDigest:Ft(h[Me.sourceDigest],Me.sourceDigest),normalizerVersion:Ft(h[Me.normalizerVersion],Me.normalizerVersion)});return d},o=async(s,c,d)=>It(await s.execute(il(e.hub,c,d))).map(u=>Ht(u[Me.hubId],Me.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(ko);u.length>0&&await r(s,u)},i=s=>e.inTransaction(async c=>{await c.execute(cl`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),h=(await e.loadSources(c,d)).map(ko),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(cl`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;ie("reconcileSearchIndex: batchSize",d,1,sn);let y=se(),f=u===void 0?null:an([...new Set(u)].sort((R,T)=>R-T),d),m={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let R=0;;R++){h?.throwIfAborted();let T=f===null?await o(s,m.lastHubId===null?0:m.lastHubId,d):f[R];if(T===void 0||T.length===0)break;let E=await i(T);m={scanned:m.scanned+E.scanned,written:m.written+E.written,skipped:m.skipped+E.scanned-E.written,forcedCuts:m.forcedCuts+E.forcedCuts,lastHubId:T[T.length-1]},p?.(m)}return{...m,elapsedMs:se()-y}}}};import{holdsMultiUnitCluster as fm}from"@aiquants/fuzzy-search/normalize";var Lo=255,ln=Object.values(Nt).sort((e,t)=>e-t),Rm=new Intl.Segmenter("und",{granularity:"grapheme"}),fe=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),ut=5e5,cn=Math.floor(ut/fe.linear),Sm=Math.floor(ut/fe.segment),dl=Math.floor(ut/fe.sweep),ml=Math.floor(ut/fe.scan),xr=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),yl=(e,t)=>{let r=0,n=t(),o=ut,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+ut,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=ut,a=!1}}},Lg=Object.freeze({fits:()=>!0,charge:()=>{}}),hl=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 gm=(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},bm=(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*Dm(e,t,r,n){let o=!1;for(let c=t;c<r&&!o;c+=cn){let d=Math.min(r,c+cn),u=(d-c)*fe.linear;n.fits(u)||(yield),o=fm(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=Rm.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(Sm,s.value.segment.length);n.fits(c*fe.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*fe.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var Am=256,Tm=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]},Em=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=Tm(r),a=Math.max(ml-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(Am/o))},windowStarts:a}})},un=(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)},pl=(e,t,r)=>{let n=un(e,t);return e.pieces[n>=0?n:un(e,r==="start"?t-1:t+1)]},fl=(e,t)=>{let r=un(e,t);if(r<0)return Rl(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},Rl=(e,t)=>{let r=un(e,t);if(r<0)return fl(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},wm=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),Im=Object.freeze({kind:"done"}),vo=Object.freeze({kind:"slice"}),_m=Object.freeze({kind:"clusters"}),xm=(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(fe.run))return vo;let p=pl(e,n.closedStart,"start"),y=pl(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 _m;let f=t(e.offset+fl(e,n.closedStart)),m=t(e.offset+Rl(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(fe.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(ut))return vo;let{period:p,continuation:y}=c,f=n.periodicEnd,m=Math.min(i.length,f+Math.max(ml,y.length)),R=f;for(;R+y.length<=m&&i.startsWith(y,R);)R+=y.length;let T=R+y.length>m&&m<i.length;if(!T)for(;R<i.length&&i.charCodeAt(R)===i.charCodeAt(R-p);)R++;if(o.charge((R-f)*fe.scan),T){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 Im;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(ut))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)*fe.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*fe.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(ut/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*Cm(e,t,r,n,o){if(t.length===0)return;let a=yield*No(Rs(e),fe.strip,n),i=[],l=[];yield*No(Ss(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),fe.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(fe.line)||(yield),n.charge(fe.line);let d=i[c],u=a.text.slice(d,l[c]),h=yield*No(gs(u,r),fe.plan,n),p=[],y="";for(let m of h.chunks){let R="",T=[];for(let E of m){let S=(E.end-E.start)*fe.normalize;n.fits(S)||(yield);let g=bo(E.start===0&&E.end===u.length?u:u.slice(E.start,E.end),r).text;n.charge(S),g.length>0&&T.push({start:E.start,end:E.end,text:g,chunkStart:R.length}),R+=g}if(R.length!==0){y.length>0&&(y+=" ");for(let E of T)p.push({start:E.start,end:E.end,text:E.text,plainStart:y.length+E.chunkStart,mapped:null});y+=R}}if(y.length===0)continue;let f={offset:d,plain:y,pieces:p,isCut:!bm(h,u),lastPiece:0,clusters:void 0};for(let m of t){let R=wm();for(;;){let T=xm(f,s,m,R,n,o);if(T.kind==="done")break;if(T.kind==="slice"){yield;continue}if(T.kind==="clusters"){f.clusters=yield*Dm(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:E}=T,S=(E.end-E.start)*fe.map;n.fits(S)||(yield);let g=u.slice(E.start,E.end);E.mapped=gm(hs(g,go(g,r)),E.text),n.charge(S)}}}}function*Mm(e,t,r,n){let o=new Int32Array(ln.length),a=0,i=Lo;for(let l=0;l<=e;l+=dl){let s=Math.min(e+1,l+dl),c=(s-l)*fe.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=Lo;for(let h=ln.length-1;h>=0;h--){let p=ln[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*Pm(e,t,r,n,o){let a=null;return yield*Cm(e,t,r,n,(l,s,c)=>{a===null&&(a=ln.map(()=>new Int32Array(e.length+1))),a[c][l]++,a[c][s]--}),a===null?!0:yield*Mm(e.length,a,n,o)}var km=(e,t,r,n)=>{let o=Em(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return hl(function*(){return(yield*Pm(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var Sl=(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)},gl=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of _a)r(pt.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(pt.interviewer(o,"name"),n.name),r(pt.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(pt.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(pt.comment($n(o),"author"),n.name),r(pt.comment($n(o),"content"),n.text)});for(let n of e.postedComments)r(pt.comment(n.id,"author"),n.userName),r(pt.comment(n.id,"content"),n.content);return t};function*Lm(e,t){let r=Vn;for(let n=0;n<e.length;n+=cn){let o=Math.min(e.length,n+cn),a=(o-n)*fe.linear;t.fits(a)||(yield),r=qn(r,e,n,o),t.charge(a)}return r}var bl=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(hl(Lm(p,n))),f=await i(km(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:[]}};import{and as Hm,asc as Tl,eq as pn,inArray as Fm,isNull as $m}from"drizzle-orm";import{and as Dl,asc as vm,eq as dn,getColumns as Nm,sql as Om}from"drizzle-orm";var gt=e=>Nm(e),Ie=(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}`},Al=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=w=>Sr(i.sourceType,w),h=(w,k)=>on(a,w,c,k),p=Om`CASE WHEN ${nn(a,c)} THEN 1 ELSE 0 END`,y=async w=>{let[k]=await t.select({id:i.id}).top(1).from(i).where(Dl(dn(i.id,w),nn(a,c)));return k!==void 0},f=w=>w==null||w===""?null:/^\d+$/.test(w)?n(Number(w)):w,m=()=>{let w={};for(let k of s)w[`ext_${k.sourceType}`]=gt(k.table);return w},R=w=>{let k=w;for(let x of s)k=k.leftJoin(x.table,Dl(dn(i.sourceType,x.sourceType),dn(i.sourceIdNum,x.idColumn)));return k},T=w=>{let{hub:k,internal:x}=w,q=k.summary,K=[],z=null,F=null,I=null,$=null,j=null,ce=null,ne=[],de=s.find(J=>J.sourceType===k.sourceType),Re=de?w[`ext_${de.sourceType}`]:void 0;if(de&&Re){let J=de.mapRow(Re);J.content!==void 0&&(q=J.content),J.employeeName!==void 0&&(ce=J.employeeName),J.category!==void 0&&(z=J.category),J.creationCategory!==void 0&&(F=J.creationCategory),J.visitTimeFrom!==void 0&&(I=J.visitTimeFrom),J.visitTimeTo!==void 0&&($=J.visitTimeTo),J.customerName!==void 0&&(j=J.customerName),J.interviewers!==void 0&&(K=J.interviewers),J.externalComments!==void 0&&(ne=J.externalComments)}else k.sourceType===Xe&&x&&(q=x.body);return{content:q,author:w.creatorName??f(k.createdBy)??"",employeeName:ce??w.creatorName??f(k.createdBy),updatedBy:f(k.updatedBy),category:z,creationCategory:F,visitTimeFrom:I,visitTimeTo:$,customerName:j,interviewers:K,externalComments:ne}},E=w=>{if(w===1)return!0;if(w===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${Pt(w)}`)},S=w=>w.creationCategory!==null&&c.includes(w.creationCategory),g=(w,k)=>E(w.hasDraftLabel)?!0:S(k),C=async w=>{let[k]=await w.select({id:l.id}).top(1).from(l).where(dn(l.name,d)).orderBy(vm(l.id));return k===void 0?null:k.id},A=()=>C(t);return{visibleSourceTypeCondition:u,draftVisibleTo:h,draftLabelFlag:p,isDraftReport:y,externalSelections:m,applyExternalJoins:R,resolveHubDisplayFields:T,readCanonicalDraftLabelId:C,getDraftLabelId:A,resolveCreationCategoryDraftLabelId:w=>w.some(S)?A():Promise.resolve(null),mapHubRecord:(w,k,x,q,K)=>{let{hub:z}=k,F=k.labels.map(j=>({id:j.id,name:j.name,color:j.color})),I=k.postedCommentRows,$=we(w.commentable,z.sourceType);return q!==null&&S(x)&&!F.some(j=>j.id===q)&&F.push({id:q,name:d,color:null}),{reportHubId:z.id,date:Ie(z.businessDate,"YYYY-MM-DD"),author:x.author,userId:z.userId?n(z.userId):"",sourceType:z.sourceType,createdAt:Ie(z.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:Ie(z.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:z.title,content:x.content,externalComments:$?x.externalComments:[],isRead:k.isRead??!1,isStarred:k.isStarred??!1,isDraft:g(k,x),labels:F,postedComments:I.filter(j=>as({authorUserId:j.userId},z.sourceType,K,w)).map(j=>({...j,userId:n(j.userId),isMine:K?j.userId===K:!1})),attachments:k.attachments}}}};var El=(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,T=s.thumbnails!==null,E=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(Fm(m.hubId,y)).orderBy(Tl(m.createdAt),Tl(m.id));for(let S of E){let g=S.fileType?String(S.fileType):null,C=S.fileSize!=null?Number(S.fileSize):null,A=c(S.objectCheckedAt,S.objectMissingAt),_={id:R.encode(Number(S.id)),fileName:String(S.fileName),fileType:g,fileSize:C,createdAt:Ie(S.createdAt,"YYYY-MM-DD HH:mm:ss"),state:A,hasThumbnail:T&&A!=="absent"&&Vr({fileType:g,fileSize:C},s.maxBytes)},H=f.get(Number(S.hubId));H?H.push(_):f.set(Number(S.hubId),[_])}return f},getAttachmentForUser:async(y,f,m)=>{let R=o.attachment;return!R||He(y.visible)?null:(await n.select({fileName:R.fileName,filePath:R.filePath,fileType:R.fileType,fileSize:R.fileSize}).top(1).from(R).innerJoin(l,pn(l.id,R.hubId)).where(Hm(pn(R.id,f),$m(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(pn(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(pn(f.id,y))}catch(R){a.error("markAttachmentPresent failed",R)}}}};import{eq as Oo}from"drizzle-orm";import{and as Um,eq as wl,isNull as Bm}from"drizzle-orm";var Xt=async(e,t,r,n)=>{if((await e.update(t).set({deletedAt:null}).output().where(Um(wl(t.id,r),Bm(t.deletedAt),n===null?void 0:wl(t.userId,n)))).length===0)throw new Error("Not Found")};var Il=(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,C,A,_,H)=>{let w=await r(S,C,g);if(!we(S.commentable,w.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(w.sourceType.toLowerCase()!==Xe.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let k=await m(C,w.userId),x=await d(),q=await c(async I=>{await Xt(I,y,C,null);let[$]=await I.insert(f).output().values({hubId:C,userId:g,body:A,createdAt:new Date,createdBy:String(g),updatedAt:new Date,updatedBy:String(g)});return x!==null&&await x.writeHubs(I,[C]),$}),[K]=await o.select({displayName:i.displayName}).top(1).from(i).where(Oo(i.id,g)),z=K?.displayName??"";if(_){let I=Ue(_);I&&(s.invalidatePrefix(Jt(I)),await n(`${h}${I}`))}s.invalidatePrefix(Ye(C)),await n(`${p}${C}`);let F={id:q.id,userId:l(q.userId),userName:z,content:q.body,createdAt:Ie(q.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(Mn.parse({type:"comment-add",reportHubId:C,comment:F,clientTempId:H,recipientRawUserId:k,sourceType:w.sourceType}),"addComment"),F},T=async(S,g)=>await S.select().top(1).from(f).where(Oo(f.id,g));return{addComment:R,deleteComment:async(S,g,C,A,_,H)=>{let w=await T(o,A);if(w.length===0)throw new Error("Not Found");if(w[0].hubId!==C)throw new Error("Not Found");let k=await r(S,w[0].hubId,g);if(w[0].userId!==g)throw new Error("Unauthorized");let x=await m(C,k.userId),q=await d();if(await c(async K=>{await Xt(K,y,C,null),await K.delete(f).where(Oo(f.id,A)),q!==null&&await q.writeHubs(K,[C])}),_){let K=Ue(_);K&&(s.invalidatePrefix(Jt(K)),await n(`${h}${K}`))}s.invalidatePrefix(Ye(C)),await n(`${p}${C}`),await u(Pn.parse({type:"comment-delete",reportHubId:C,commentId:A,clientTempId:H,recipientRawUserId:x,sourceType:k.sourceType}),"deleteComment")}}};import{and as _l,eq as Ut,isNull as Vm}from"drizzle-orm";var xl=e=>e===""?null:e,Cl=(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:T,internal:E,hubLabel:S,userStatus:g}=l,{canonicalDraftLabelName:C,draftLabelNames:A}=p,_=async(F,I,$,j)=>{if(!Mr($))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",$);if(!we(F.visible,Xe))throw new Error("Forbidden");c.info("createDailyReport called",{userId:I,businessDate:$});let ce=await u();try{let ne=await d(async b=>{c.info("Starting transaction");let v=await t(b);if(v===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(C)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let L=`internal-temp-${Date.now()}-${Math.random()}`,[P]=await b.insert(T).output().values({sourceType:Xe,sourceId:L,businessDate:new Date(`${$}T00:00:00Z`),userId:I,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(I),updatedAt:new Date,updatedBy:String(I)});return await b.update(T).set({sourceId:String(P.id)}).where(Ut(T.id,P.id)),c.info("Hub created",P),await b.insert(E).values({hubId:P.id,body:"",createdAt:new Date,createdBy:String(I),updatedAt:new Date,updatedBy:String(I)}),c.info("Internal created"),await b.insert(S).values({hubId:P.id,labelId:v,createdAt:new Date,createdBy:String(I)}),c.info("Label assigned"),await b.insert(g).values({hubId:P.id,userId:I,isRead:!0,isStarred:!1,createdAt:new Date,createdBy:String(I),updatedAt:new Date,updatedBy:String(I)}),ce!==null&&await ce.writeHubs(b,[P.id]),P.id});s.invalidatePrefix(Qt($,I)),s.invalidatePrefix(wo(I)),await a(f),await a(`${m}${$}`);let de=await n(Ze.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),ne,I,{forceRefresh:!0});if(de===null)throw new Error(`[daily-report] createDailyReport: report ${ne} was committed but its detail read returned nothing`);let Re=await r(de.reportHubId);await h(vn.parse({type:"report-create",reportHubId:de.reportHubId,report:de,clientTempId:j,recipientRawUserId:Re?I:void 0,actorRawUserId:I}),"createDailyReport");let J=await n(F,ne,I,{forceRefresh:!0});if(J===null)throw new Error(`[daily-report] createDailyReport: the actor's scope cannot read report ${ne} it just created`);return J}catch(ne){throw c.error("Error in createDailyReport",ne),ne}},H=async(F,I)=>await F.select().top(1).from(T).where(Ut(T.id,I)),w=async(F,I,$)=>{await o(F,I,$);let[j]=await H(i,I);if(j===void 0||j.deletedAt)throw new Error("Not Found");if(j.userId!==$)throw new Error("Unauthorized");return j},k=async(F,I,$)=>{await F.update(T).set($).where(Ut(T.id,I))},x=async(F,I,$)=>{await F.update(E).set($).where(Ut(E.hubId,I))};return{createDailyReport:_,updateDailyReport:async(F,I,$,j,ce)=>{let ne=await w(F,I,$),de=await u();await d(async b=>{await Xt(b,T,I,$),j.title!==void 0&&await k(b,I,{title:xl(j.title),updatedAt:new Date,updatedBy:String($)}),j.content!==void 0&&await x(b,I,{body:xl(j.content),updatedAt:new Date,updatedBy:String($)}),de!==null&&await de.writeHubs(b,[I])}),s.invalidatePrefix(Ye(I)),await a(`${R}${I}`);let Re=Ue(Ie(ne.businessDate,"YYYY-MM-DD"));Re&&(s.invalidatePrefix(Jt(Re)),await a(`${m}${Re}`));let J=await n(Ze.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),I,$,{forceRefresh:!0});if(J){let b=await r(I);await h(Nn.parse({type:"report-update",reportHubId:J.reportHubId,report:J,clientTempId:ce,recipientRawUserId:b?$:void 0,actorRawUserId:$}),"updateDailyReport")}},publishDailyReport:async(F,I,$,j)=>{let ce=await w(F,I,$),ne=await u();if(await d(async b=>{await Xt(b,T,I,$),await b.delete(S).where(_l(Ut(S.hubId,I),Qs(y,A))),ne!==null&&await ne.writeHubs(b,[I])}),s.invalidatePrefix(Ye(I)),s.invalidatePrefix(wt),await a(f),ce.businessDate){let b=Ue(Ie(ce.businessDate,"YYYY-MM-DD"));b&&await a(`${m}${b}`)}let de=Ue(Ie(ce.businessDate,"YYYY-MM-DD"));de&&s.invalidatePrefix(Qt(de,$));let Re=await n(Ze.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),I,$,{forceRefresh:!0});if(Re===null)return null;let J=await r(I);return await h(On.parse({type:"report-publish",reportHubId:Re.reportHubId,report:Re,clientTempId:j,recipientRawUserId:J?$:void 0,actorRawUserId:$}),"publishDailyReport"),await n(F,I,$,{forceRefresh:!0})},deleteDailyReport:async(F,I,$,j)=>{let ce=await w(F,I,$);if(await d(async ne=>{if((await ne.update(T).set({deletedAt:new Date,deletedBy:String($),updatedAt:new Date,updatedBy:String($)}).output().where(_l(Ut(T.id,I),Ut(T.userId,$),Vm(T.deletedAt)))).length===0)throw new Error("Not Found")}),s.invalidatePrefix(Ye(I)),s.invalidatePrefix(wt),await a(f),ce.businessDate){let ne=Ue(Ie(ce.businessDate,"YYYY-MM-DD"));ne&&await a(`${m}${ne}`)}await h(Lr.parse({type:"report-delete",reportHubId:I,clientTempId:j,sourceType:ce.sourceType}),"deleteDailyReport")}}};import{and as Zt,asc as Ml,desc as Cr,eq as Pe,inArray as Ho,isNull as mn,sql as qm}from"drizzle-orm";var Pl=vr([]),jm=6e4,$o=(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},Uo=e=>{let t=async()=>{await new Promise(r=>setImmediate(r)),e.throwIfAborted()};return{sliceMs:xr.sliceMs,now:se,pause:t}},Fo=e=>{try{return{ok:!0,value:e()}}catch(t){return{ok:!1,cause:t}}},Wm=e=>Fo(()=>{let t=ur.safeParse(JSON.parse(JSON.stringify(e)));if(!t.success)throw new Error(`[daily-report] the detail does not match the delivered detail schema (${Ma(t.error)})`);return t.data}),kl=(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:T,settings:E}=e,{idsEpoch:S,dateEpochPrefix:g,detailEpochPrefix:C}=e.settings.redisKeys,{hub:A,internal:_,comment:H,label:w,hubLabel:k,userStatus:x}=p,q=E.idsTtlMs,K=E.businessDateTtlMs,z=async(M,D)=>(await h.select({reportHubId:A.id,businessDate:A.businessDate,sourceType:A.sourceType}).from(A).where(Zt(mn(A.deletedAt),t(D,"author-or-authorless"),r(M.visible))).orderBy(Cr(A.businessDate),Cr(A.id))).map(U=>({...U,businessDate:Ie(U.businessDate,"YYYY-MM-DD")})),F=async(M,D,N)=>{let U=await $(D);return U?He(M.visible)?[]:(await h.select({reportHubId:A.id,businessDate:A.businessDate,sourceType:A.sourceType}).top(N).from(A).where(Zt(mn(A.deletedAt),t(U,"author-or-authorless"),r(M.visible))).orderBy(Cr(A.businessDate),Cr(A.id))).map(he=>({...he,businessDate:Ie(he.businessDate,"YYYY-MM-DD")})):[]},I=new Map,$=async M=>{if(!E.disableUserIdCache&&I.has(M))return I.get(M)??null;let D=await f(M);return D!==null&&!E.disableUserIdCache&&I.set(M,D),D},j=async(M,D,{forceRefresh:N=!1,snapshot:U=!1,ttlMsOverride:G,onFetchStart:he,admission:Oe}={})=>{let Ae=await $(D);if(!Ae)return{items:[],streamAnchor:null,snapshot:Pl};if(He(M.visible))return{items:[],streamAnchor:await d(),snapshot:Pl};let ye=_s(Ae,Kr(M)),[Se]=await m.getOrFetch({cacheKey:ye,fetcher:async()=>{let qe=await d(),rt=await z(M,Ae);if(!Ta(rt)){T.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let re=[...rt].sort(Fn);return[{items:re,streamAnchor:qe,snapshot:vr(re)}]}return[{items:rt,streamAnchor:qe,snapshot:vr(rt)}]},onFetchStart:he,forceRefresh:N,snapshot:U,admission:Oe,ttlMsOverride:G??q,epochKey:S,refreshAheadRatio:.5});if(Se===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return Se},ce=async(M,D,N)=>{let U=await a(h.select({hub:gt(A),internal:gt(_),isRead:x.isRead,isStarred:x.isStarred,creatorName:y.displayName,hasDraftLabel:n,...o()}).from(A)).leftJoin(_,Pe(A.id,_.hubId)).leftJoin(x,Zt(Pe(A.id,x.hubId),Pe(x.userId,D))).leftJoin(y,Pe(A.userId,y.id)).where(Zt(N,mn(A.deletedAt),t(D,"author"),r(M.visible))).orderBy(Cr(A.id));if(U.length===0)return[];let G=U.map(re=>re.hub.id),he=await h.select({hubId:k.hubId,id:w.id,name:w.name,color:w.color}).from(k).innerJoin(w,Pe(k.labelId,w.id)).where(Ho(k.hubId,G)),Oe=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,Pe(H.userId,y.id)).where(Ho(H.hubId,G)).orderBy(Ml(H.createdAt)),Ae=await c(G),ye=new Map,Se=new Map;for(let re of he){let Le=ye.get(re.hubId);Le||(Le=[],ye.set(re.hubId,Le)),Le.push({id:re.id,name:re.name,color:re.color})}for(let re of Oe){let Le=Se.get(re.hubId);Le||(Le=[],Se.set(re.hubId,Le)),Le.push({id:re.id,content:re.body,createdAt:Ie(re.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:re.userId,userName:re.userName||""})}let qe=U.map(re=>Fo(()=>i(re))),rt=await l(qe.flatMap(re=>re.ok?[re.value]:[]));return U.map((re,Le)=>{let dt=re.hub.id,Ct=qe[Le],Dt=Ct.ok?Fo(()=>s(M,{...re,attachments:Ae.get(dt)??[],labels:ye.get(dt)||[],postedCommentRows:Se.get(dt)||[]},Ct.value,rt,D)):Ct;return Dt.ok?{reportHubId:dt,outcome:"ok",report:Dt.value}:{reportHubId:dt,outcome:"failed",cause:Dt.cause}})},ne=async(M,D,N)=>(await ce(M,D,N)).map(U=>{if(U.outcome==="failed")throw U.cause;return U.report}),de=M=>Ce({windowMs:jm,tallies:["failed"],writeSuppressed:(D,{count:N,since:U})=>{T.warn(`failed_report_suppressed count=${N} since=${U} read=${M} report=${D}`)}}),Re={markDailyReportSearchHits:de("markDailyReportSearchHits"),getDailyReportDetailsByIdsByExternalId:de("getDailyReportDetailsByIdsByExternalId")},J=(M,D,N)=>{Re[M].record(D,"failed",()=>T.error(`${M}: report ${D} passed the visibility predicate but its own assembly failed`,N))},b=(M,D)=>{let N=D.outcome==="ok"?Wm(D.report):{ok:!1,cause:D.cause};return N.ok?{reportHubId:D.reportHubId,outcome:"ok",report:N.value}:(J(M,D.reportHubId,N.cause),{reportHubId:D.reportHubId,outcome:"failed"})},v=async(M,D,N,{read:U,signal:G,slicing:he})=>{let Oe=await ce(M,D,Ho(A.id,[...N]));G.throwIfAborted();let Ae=[],ye=he.now();for(let Se of Oe)Ae.length>0&&he.now()-ye>=he.sliceMs&&(await he.pause(),ye=he.now()),Ae.push(b(U,Se));return Ae},L=async(M,D,N,{forceRefresh:U=!1,snapshot:G=!1,ttlMsOverride:he,admission:Oe}={})=>{let Ae=await $(N);if(!Ae)return[];let ye=Ue(D);if(!ye)return[];if(He(M.visible))return[];let Se=xs(ye,Ae,Kr(M));return m.getOrFetch({cacheKey:Se,fetcher:()=>ne(M,Ae,Pe(A.businessDate,qm`${ye}`)),forceRefresh:U,snapshot:G,admission:Oe,ttlMsOverride:he??K,epochKey:`${g}${ye}`})},P=async(M,D,N,{forceRefresh:U=!1,snapshot:G=!1,ttlMsOverride:he,admission:Oe}={})=>{if(He(M.visible))return null;let Ae=Cs(D,N,Kr(M));return(await m.getOrFetch({cacheKey:Ae,fetcher:async()=>{let Se=await a(h.select({hub:gt(A),internal:gt(_),isRead:x.isRead,isStarred:x.isStarred,creatorName:y.displayName,hasDraftLabel:n,...o()}).from(A)).leftJoin(_,Pe(A.id,_.hubId)).leftJoin(x,Zt(Pe(A.id,x.hubId),Pe(x.userId,N))).leftJoin(y,Pe(A.userId,y.id)).where(Zt(Pe(A.id,D),mn(A.deletedAt),t(N,"author"),r(M.visible)));if(Se.length===0)return[];let qe=Se[0].hub.id,rt=await h.select({id:w.id,name:w.name,color:w.color}).from(k).innerJoin(w,Pe(k.labelId,w.id)).where(Pe(k.hubId,qe)),re=await h.select({id:H.id,body:H.body,createdAt:H.createdAt,userId:H.userId,userName:y.displayName}).from(H).leftJoin(y,Pe(H.userId,y.id)).where(Pe(H.hubId,qe)).orderBy(Ml(H.createdAt)),Le=await c([qe]),dt=rt.map(ze=>({id:ze.id,name:ze.name,color:ze.color})),Ct=re.map(ze=>({id:ze.id,content:ze.body,createdAt:Ie(ze.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ze.userId,userName:ze.userName||""})),Dt=i(Se[0]),Dn=await l([Dt]);return[s(M,{...Se[0],attachments:Le.get(qe)??[],labels:dt,postedCommentRows:Ct},Dt,Dn,N)]},forceRefresh:U,snapshot:G,admission:Oe,ttlMsOverride:he??K,epochKey:`${C}${D}`}))[0]??null};return{getUserIdByExternalId:$,getDailyReportIdsByExternalId:j,getDailyReportIdsFirstPageByExternalId:F,getDailyReportsByBusinessDateByExternalId:L,getDailyReportDetailById:P,getDailyReportDetailByIdByExternalId:async(M,D,N,U={})=>{let G=await $(N);return G?P(M,D,G,U):null},getDailyReportDetailsByIdsByExternalId:async(M,D,N,U)=>{let G=$o("getDailyReportDetailsByIdsByExternalId",U);if(D.length>xe.maxDetailIds)throw Q("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${xe.maxDetailIds} ids`,D.length);let he=await $(N);if(!he||D.length===0||He(M.visible))return D.map(pr);G.throwIfAborted();let Oe=await v(M,he,D,{read:"getDailyReportDetailsByIdsByExternalId",signal:G,slicing:Uo(G)}),Ae=new Map(Oe.map(ye=>[ye.reportHubId,ye]));return D.map(ye=>{let Se=Ae.get(ye);return Se===void 0?pr(ye):Se})},fetchDeliveredHubOutcomes:v,invalidateHubReadCaches:async(M,D)=>{m.invalidatePrefix(wt),await u(S);for(let N of new Set(M))m.invalidatePrefix(Ye(N)),await u(`${C}${N}`);for(let N of new Set(D)){let U=Ue(N);U&&await u(`${g}${U}`)}},clearCache:async()=>{m.clearAll(),I.clear(),R&&await u(S),T.info("Server-side DB/SQL caches cleared successfully.")}}};var Ym="v4",zm=/^(?!:)[^\s\p{Cc}]+(?<!:)$/u,Bo=e=>{if(typeof e!="string"||!zm.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:${Ym}`,idsEpoch:`${e}:ids:epoch`,dateEpochPrefix:`${e}:date-epoch:`,detailEpochPrefix:`${e}:detail-epoch:`})};var yn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,redisKeyPrefix:"daily-report",streamMaxLen:1e4}),Gm=e=>{let{length:t}=e;if(t===void 0)throw Q("tables.hub.title","a character column with a declared length",t);return ie("tables.hub.title.length",t,1)},Km=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])},Jm=e=>{let t=new Map([[Xe.toLowerCase(),`the internal source type ${JSON.stringify(Xe)}`]]);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([Xe,...e.map(r=>r.sourceType)])},Ll=e=>{let t=e.externalSources??[],r=Km(e.draftLabelNames);if(jr(e),Object.hasOwn(e,"streamKey"))throw je("redisKeyPrefix","given in place of the removed key streamKey");let n=$i(e.attachments),o=Gm(e.tables.hub.title);ho(e.tables.hub.sourceType);let a=ve("idsTtlMs",e.idsTtlMs,1,yn.idsTtlMs),i=ve("businessDateTtlMs",e.businessDateTtlMs,1,yn.businessDateTtlMs),l=ve("streamMaxLen",e.streamMaxLen,1,yn.streamMaxLen),s=Bo(e.redisKeyPrefix===void 0?yn.redisKeyPrefix:e.redisKeyPrefix);return Object.freeze({externalSources:t,sourceTypes:Jm(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamMaxLen:l,redisKeys:s,disableUserIdCache:!!e.disableUserIdCache})};var vl=({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=se();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let y=se()-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?Tt:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});import{and as Xm,eq as Zm,sql as De}from"drizzle-orm";var hn=["hubId","userId","isRead","isStarred","createdAt","createdBy","updatedAt","updatedBy"],ey={isRead:{statusType:"read",callerName:"setReadStatus"},isStarred:{statusType:"star",callerName:"setStarStatus"}},Ve=e=>De`${De.identifier(e.name)}`,ty=(e,t,{reportHubId:r,userId:n,value:o,at:a})=>{let i=String(n),l=Ve(e[t]),s=(p,y)=>De`t.${Ve(p)} = CASE WHEN t.${l} = ${o} THEN t.${Ve(p)} ELSE ${y} END`,c={hubId:De`s.${Ve(e.hubId)}`,userId:De`s.${Ve(e.userId)}`,isRead:De`${t==="isRead"?o:!1}`,isStarred:De`${t==="isStarred"?o:!1}`,createdAt:De`${a}`,createdBy:De`${i}`,updatedAt:De`${a}`,updatedBy:De`${i}`},d=De.join(hn.map(p=>Ve(e[p])),De`, `),u=De.join(hn.map(p=>c[p]),De`, `),h=De.join(hn.map(p=>De`inserted.${Ve(e[p])} AS ${De.identifier(p)}`),De`, `);return De`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}, ${s(e.updatedAt,a)}, ${s(e.updatedBy,i)}
13
- WHEN NOT MATCHED THEN INSERT (${d}) VALUES (${u})
14
- OUTPUT ${h};`},Nl=(e,t)=>(typeof e=="number"||typeof e=="string")&&String(e)===String(t),Ol=e=>e instanceof Date||typeof e=="string",ry=e=>{if(!Array.isArray(e))return`recordset ${Pt(e)}`;if(e.length!==1)return`${e.length} rows`;let[t]=e;return typeof t!="object"||t===null?`a row of ${Pt(t)}`:hn.map(r=>`${r}=${Pt(t[r])}`).join(", ")},ny=(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||!Nl(a.hubId,t)||!Nl(a.userId,r)||typeof a.isRead!="boolean"||typeof a.isStarred!="boolean"||!Ol(a.createdAt)||!Ol(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 ${ry(n)}`);return{hubId:t,userId:r,isRead:a.isRead,isStarred:a.isStarred,createdAt:a.createdAt,createdBy:a.createdBy,updatedAt:a.updatedAt,updatedBy:a.updatedBy}},Hl=(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[T]=await n.select({sourceType:c.sourceType,userId:c.userId,deletedAt:c.deletedAt}).top(1).from(c).where(Xm(Zm(c.id,m),t(R,"author")));return T??null},h=async(m,R,T)=>{let E=await u(R,T);if(!E||E.deletedAt||!we(m.visible,E.sourceType))throw new Error("Not Found");return{sourceType:E.sourceType,userId:E.userId}},p=async(m,R,T,E,S,g,C)=>{await h(R,E,T);let A={reportHubId:E,userId:T,value:g,at:new Date},_=ny(await n.execute(ty(d,m,A)),A);if(S){let k=Ue(S);k&&(a.invalidatePrefix(Qt(k,T)),await r(`${l}${k}`))}a.invalidatePrefix(Io(E,T)),await r(`${s}${E}`);let{statusType:H,callerName:w}=ey[m];return await i(Cn.parse({type:"status-update",reportHubId:E,recipientRawUserId:T,statusType:H,value:g,clientTempId:C}),w),_};return{assertHubMutable:h,setStarStatus:(m,R,T,E,S,g)=>p("isStarred",m,R,T,E,S,g),setReadStatus:(m,R,T,E,S,g)=>p("isRead",m,R,T,E,S,g)}};var sy=Object.freeze([]),Vo=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},Sn=(e,t)=>e.get(t)??sy,Fl=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Xr);function qo(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=Ll(e),{externalSources:f,draftLabelNames:m,attachmentDelivery:R,titleMaxLength:T}=y,E=be(e.logger,1,"Service"),S=ee=>iy(me=>t.transaction(Z=>me(()=>ee(Z))),e.transactionRetry),g=e.search===void 0?null:Ks(e.search,f.map(ee=>ee.sourceType)),C={hub:c,hubLabel:p,label:h},A=g===null?null:sl({tables:{...C,search:g.tables},draftLabelNames:m});g!==null&&Ao();let _=null,H=async()=>{if(g===null)return null;if(_===null){let ee=await Ao(),me=g.externalSourceTexts;_=ul({hub:c,tables:g.tables,loadSources:(Z,oe)=>ze(Z,oe,me),inTransaction:S,normalizerVersion:ee})}return _},{incrementRedisEpoch:w,publishToSseStream:k,readSseStreamAnchor:x}=vl({redis:i,logger:E,epochs:s,streamKey:y.redisKeys.sseStream,streamMaxLen:y.streamMaxLen}),q={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:E,settings:y,draftVisibilityTables:C,inTransaction:S,publishToSseStream:k,prepareSearchIndex:H},{visibleSourceTypeCondition:K,draftVisibleTo:z,draftLabelFlag:F,isDraftReport:I,externalSelections:$,applyExternalJoins:j,resolveHubDisplayFields:ce,readCanonicalDraftLabelId:ne,getDraftLabelId:de,resolveCreationCategoryDraftLabelId:Re,mapHubRecord:J}=Al(q),{getAttachmentsByHubIds:b,getAttachmentForUser:v,markAttachmentMissing:L,markAttachmentPresent:P}=El(q,{draftVisibleTo:z,visibleSourceTypeCondition:K}),{getUserIdByExternalId:O,getDailyReportIdsByExternalId:W,getDailyReportIdsFirstPageByExternalId:X,getDailyReportsByBusinessDateByExternalId:Y,getDailyReportDetailById:M,getDailyReportDetailByIdByExternalId:D,getDailyReportDetailsByIdsByExternalId:N,fetchDeliveredHubOutcomes:U,invalidateHubReadCaches:G,clearCache:he}=kl(q,{draftVisibleTo:z,visibleSourceTypeCondition:K,draftLabelFlag:F,externalSelections:$,applyExternalJoins:j,resolveHubDisplayFields:ce,resolveCreationCategoryDraftLabelId:Re,mapHubRecord:J,getAttachmentsByHubIds:b,readSseStreamAnchor:x,incrementRedisEpoch:w}),{assertHubMutable:Oe,setStarStatus:Ae,setReadStatus:ye}=Hl(q,{draftVisibleTo:z,incrementRedisEpoch:w}),{addComment:Se,deleteComment:qe}=Il(q,{isDraftReport:I,assertHubMutable:Oe,incrementRedisEpoch:w}),{createDailyReport:rt,updateDailyReport:re,publishDailyReport:Le,deleteDailyReport:dt}=Cl(q,{readCanonicalDraftLabelId:ne,isDraftReport:I,getDailyReportDetailById:M,assertHubMutable:Oe,incrementRedisEpoch:w}),Ct=async(ee,me)=>{let Z=new Map,oe=r.attachment;if(!oe||R===null)return Z;let Ee=await ee.select({hubId:oe.hubId,fileName:oe.fileName}).from(oe).where(Rn(oe.hubId,[...me])).orderBy(bt(oe.hubId),bt(oe.createdAt),bt(oe.id));for(let ae of Ee)Vo(Z,Number(ae.hubId),String(ae.fileName));return Z},Dt=async(ee,me,Z)=>{let oe=new Map;for(let[Ee,ae]of Z){let nt=new Map;for(let{hub:Fe}of me)Fe.sourceType===Ee&&Fe.sourceIdNum!==null&&nt.set(Fe.sourceIdNum,Fe.id);if(nt.size===0)continue;let At=await ae(ee,[...nt.keys()]);for(let[Fe,ot]of At){let Mt=nt.get(Fe);if(Mt===void 0)throw Q(`search.externalSourceTexts.${Ee} answer key`,"a source id that was asked for",Fe);if(!(Array.isArray(ot)&&ot.every(er=>typeof er=="string")))throw Q(`search.externalSourceTexts.${Ee} answer for ${Fe}`,"an array of strings",ot);oe.set(Mt,ot)}}return oe},Dn=(ee,me)=>{let Z=ce(ee),oe=[["subject",ee.hub.title],["content",Z.content],["author",Z.author],["employeeName",Z.employeeName],["updatedBy",Z.updatedBy],["category",Z.category],["creationCategory",Z.creationCategory],["customerName",Z.customerName]];for(let ae of Z.interviewers)oe.push(["interviewerName",ae.name??null],["interviewerAffiliation",ae.affiliation??null]);for(let ae of me.labelNames)oe.push(["label",ae]);for(let ae of me.attachmentNames)oe.push(["attachment",ae]);for(let ae of me.extraTexts)oe.push(["extra",ae]);let Ee=[];for(let ae of Z.externalComments)Ee.push({authorUserId:null,text:Fl(ae.name,ae.text)});for(let ae of me.postedComments)Ee.push({authorUserId:ae.userId,text:Fl(ae.userName,ae.body)});return{hubId:ee.hub.id,fields:oe,comments:Ee,filterValues:{authorName:Z.employeeName,customerName:Z.customerName}}},ze=async(ee,me,Z)=>{let oe=[];for(let Ee of oy(me,ay)){let ae=await j(ee.select({hub:gt(c),internal:gt(d),creatorName:n.displayName,...$()}).from(c)).leftJoin(d,fn(c.id,d.hubId)).leftJoin(n,fn(c.userId,n.id)).where(Rn(c.id,[...Ee])).orderBy(bt(c.id)),nt=new Map,At=await ee.select({hubId:p.hubId,name:h.name}).from(p).innerJoin(h,fn(p.labelId,h.id)).where(Rn(p.hubId,[...Ee])).orderBy(bt(p.hubId),bt(h.id));for(let Ge of At)Vo(nt,Ge.hubId,Ge.name);let Fe=new Map,ot=await ee.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,fn(u.userId,n.id)).where(Rn(u.hubId,[...Ee])).orderBy(bt(u.hubId),bt(u.createdAt),bt(u.id));for(let Ge of ot)Vo(Fe,Ge.hubId,Ge);let Mt=await Ct(ee,Ee),er=await Dt(ee,ae,Z);for(let Ge of ae){let $e=Ge.hub.id;oe.push(Dn(Ge,{labelNames:Sn(nt,$e),postedComments:Sn(Fe,$e),attachmentNames:Sn(Mt,$e),extraTexts:Sn(er,$e)}))}}return oe},ac=(ee,me,Z)=>A===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):A.search(t,{criteria:Z,viewerUserId:me,scope:ee}),Wo=y.sourceTypes,ic=async(ee,me)=>{if(A===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let Z=Wo.filter(ae=>we(ee.visible,ae)),oe=await A.facetValues(t,{column:"authorName",viewerUserId:me,scope:ee}),Ee=await A.facetValues(t,{column:"customerName",viewerUserId:me,scope:ee});return{sourceTypes:Z,authors:oe,customers:Ee}},sc=async(ee,me,Z,oe,Ee)=>{let ae=$o("markDailyReportSearchHits",Ee);if(A===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(oe.length>xe.maxDetailIds)throw Q("markDailyReportSearchHits: reportHubIds",`at most ${xe.maxDetailIds} ids`,oe.length);let nt=Nr(gr(Z));if(oe.length===0||He(ee.visible))return{wordsDigest:nt,reports:[],deferred:[]};ae.throwIfAborted();let At=Uo(ae),Fe=await U(ee,me,oe,{read:"markDailyReportSearchHits",signal:ae,slicing:At});await At.pause();let ot=Fe.flatMap($e=>$e.outcome==="ok"?[{reportHubId:$e.reportHubId,fields:gl($e.report)}]:[]),Mt=Z.combine==="union"&&Z.sets.length>=2&&ot.length>0?await A.matchedSets(t,{plan:Z,viewerUserId:me,scope:ee,ids:ot.map($e=>$e.reportHubId)}):null,er=ot.map(({reportHubId:$e,fields:cc})=>{let Yo=Mt===null?null:Mt.get($e),zo=Yo===void 0?0:Yo;return{reportHubId:$e,matchedSets:zo,alternatives:Sl(Z,zo).flatMap(uc=>uc.alternatives),fields:cc}}),Ge=await bl(er,xr,At.pause,yl(xr,At.now));return{wordsDigest:nt,reports:Ge.reports,deferred:Ge.deferred}},lc=async ee=>{let me=await H();if(me===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return me.reconcile(t,ee)};return{streamKey:y.redisKeys.sseStream,attachmentDelivery:R,titleMaxLength:T,searchLimits:g===null?null:{concurrency:g.concurrency,rateLimitPerMinute:g.rateLimitPerMinute},searchFilterSourceTypes:Wo,clearCache:he,invalidateHubReadCaches:G,getUserIdByExternalId:O,getDailyReportIdsByExternalId:W,getDailyReportIdsFirstPageByExternalId:X,readSseStreamAnchor:x,getDailyReportsByBusinessDateByExternalId:Y,getDailyReportDetailById:M,getDailyReportDetailByIdByExternalId:D,getDailyReportDetailsByIdsByExternalId:N,getDraftLabelId:de,searchDailyReports:ac,markDailyReportSearchHits:sc,listDailyReportSearchFacets:ic,reconcileSearchIndex:lc,getAttachmentsByHubIds:b,getAttachmentForUser:v,markAttachmentMissing:L,markAttachmentPresent:P,setStarStatus:Ae,setReadStatus:ye,addComment:Se,deleteComment:qe,createDailyReport:rt,updateDailyReport:re,publishDailyReport:Le,deleteDailyReport:dt}}var ly=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(be(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return be(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};import{desc as $l,sql as cy}from"drizzle-orm";import{bigint as _e,bit as Ul,date as uy,datetime2 as ke,foreignKey as tt,index as xt,int as dy,mssqlSchema as py,nvarchar as ue,primaryKey as Bt,uniqueIndex as my}from"drizzle-orm/mssql-core";function yy(e,t){let r=py(e),n=t.userTable,o=r.table("DailyReportHub",{id:_e("id",{mode:"number"}).identity().notNull(),sourceType:ue("source_type",{length:20}).notNull(),sourceId:ue("source_id",{length:100}).notNull(),sourceIdNum:_e("source_id_num",{mode:"number"}).generatedAlwaysAs(cy`TRY_CAST(source_id AS BIGINT)`),businessDate:uy("business_date"),userId:_e("user_id",{mode:"number"}),title:ue("title",{length:200}),summary:ue("summary",{length:"max"}),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull(),deletedAt:ke("deleted_at"),deletedBy:ue("deleted_by",{length:50})},u=>[Bt({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),tt({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),xt(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),xt(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),xt(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),xt(`${e}_DailyReportHub_user_id_index`).on(u.userId),xt(`${e}_DailyReportHub_business_date_id_index`).on($l(u.businessDate),$l(u.id)),xt(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:_e("hub_id",{mode:"number"}).notNull(),body:ue("body",{length:"max"}),metadata:ue("metadata",{length:"max"}),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),tt({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:_e("id",{mode:"number"}).identity().notNull(),hubId:_e("hub_id",{mode:"number"}).notNull(),userId:_e("user_id",{mode:"number"}).notNull(),body:ue("body",{length:"max"}).notNull(),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),tt({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),tt({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),xt(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:_e("id",{mode:"number"}).identity().notNull(),userId:_e("user_id",{mode:"number"}),name:ue("name",{length:50}).notNull(),color:ue("color",{length:20}),sortOrder:dy("sort_order"),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),tt({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:_e("hub_id",{mode:"number"}).notNull(),labelId:_e("label_id",{mode:"number"}).notNull(),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),tt({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),tt({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:_e("hub_id",{mode:"number"}).notNull(),userId:_e("user_id",{mode:"number"}).notNull(),isRead:Ul("is_read").default(!1).notNull(),isStarred:Ul("is_starred").default(!1).notNull(),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),tt({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),tt({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:_e("id",{mode:"number"}).identity().notNull(),hubId:_e("hub_id",{mode:"number"}).notNull(),uploadedBy:_e("uploaded_by",{mode:"number"}),sourceKey:ue("source_key",{length:200}).notNull(),fileName:ue("file_name",{length:255}).notNull(),filePath:ue("file_path",{length:"max"}).notNull(),fileType:ue("file_type",{length:100}),fileSize:_e("file_size",{mode:"number"}),objectCheckedAt:ke("object_checked_at"),objectMissingAt:ke("object_missing_at"),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),tt({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),tt({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),my(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),xt(`${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}}import{bigint as jo,binary as Bl,datetime2 as hy,int as fy,mssqlSchema as Ry,nvarchar as gn,primaryKey as Vl,varchar as Sy}from"drizzle-orm/mssql-core";function gy(e){let t=Ry(e),r=t.table("DailyReportSearchDocument",{hubId:jo("hub_id",{mode:"number"}).notNull(),searchText:gn("search_text",{length:"max"}).notNull(),sourceDigest:Bl("source_digest",{length:32}).notNull(),normalizerVersion:Sy("normalizer_version",{length:64}).notNull(),indexedAt:hy("indexed_at").notNull(),rowVersion:Bl("row_version",{length:8}).notNull(),authorName:gn("author_name",{length:mt.maxValueLength}),customerName:gn("customer_name",{length:mt.maxValueLength})},o=>[Vl({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:jo("hub_id",{mode:"number"}).notNull(),ordinal:fy("ordinal").notNull(),authorUserId:jo("author_user_id",{mode:"number"}),commentText:gn("comment_text",{length:"max"}).notNull()},o=>[Vl({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var by=5e7,Zl=2e8,Dy=1,ec=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})})}),ql=125,jl=4,Wl=16,Yl=50,zl=2,bn=Object.freeze({renderMs:Be.renderMs,nanosecondsPerBlockVisit:ql,margin:jl,maxBlockVisits:Math.floor(Be.renderMs*1e6/(ql*jl)),walkBudgetMs:Wl,nanosecondsPerWalkStep:Yl,walkMargin:zl,maxWalkSteps:Math.floor(Wl*1e6/(Yl*zl))}),Ay=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Gl=75,Kl=4,Jl="#ffffff",Ty=1,Ey={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},wy=[/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/],Ql=Object.freeze({ok:!1,reason:"failed"}),Xl=Object.freeze({ok:!1,reason:"unsupported"}),tc=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:bi(e)}),rc=(e,t)=>{switch(t){case"jpeg":{let r=lo(e);return r===null?null:tc(r)}case"png":{let r=Ti(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Ei(e,bn.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},nc=(e,t)=>{let r=Ay.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=ec,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},Iy=(e,t,r)=>{let n=rc(e,t);return n===null?null:nc(n,r)},_y=e=>e!==null&&e<=Zl,xy=(e,t)=>{if(t!=="jpeg")return rc(e,t);let r=Di(e,bn);return r===null||r.blockVisits>bn.maxBlockVisits?null:tc(r.header)},Cy=e=>{let t=e instanceof Error?e.message:"";return wy.some(r=>r.test(t))?"failed":"unsupported"},My=e=>{e.cache(!1),e.concurrency(Dy),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Ey)});let t=async(n,o,a,i,l)=>{let s=xy(n,o);if(s===null)return Xl;try{let c=e(n,{limitInputPixels:by,animated:!1});if(!_y(nc(s,await c.metadata())))return Xl;if(l.aborted)return Ql;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Jl}).webp({quality:Gl,effort:Kl}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:Cy(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?Ql:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Gl}-e${Kl}/flatten-${Jl}/v${Ty}`,render:r}};var oc=6e4,Py=e=>{let t=ie("ttlMs",e.ttlMs,1,oc),r=rr("readViewerKey",e.readViewerKey),n=rr("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=se(),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 ND(e){e.redis||be(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=In(e.redis),r=new or({defaultTtlMs:e.cacheDefaultTtlMs,maxBuckets:e.cacheMaxBuckets,maxBytes:e.cacheMaxBytes},t),n=qo({...e,cache:r,epochs:t}),o=new Ar({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=xo({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}}export{uo as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,co as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,Zl as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,bn as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,ec as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,_o as DAILY_REPORT_SSE_CATCH_UP_BATCH,Os as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,oc as DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS,Ar as DailyReportSseReader,Ze as DailyReportViewerScope,or as SqlResultCache,Bo as buildDailyReportRedisKeys,xo as createDailyReportHandlers,ND as createDailyReportServer,qo as createDailyReportService,Py as createDailyReportVisibilityCache,In as createEpochStore,My as createSharpThumbnailRenderer,Hn as dailyReportSseStreamMessageSchema,yy as defineDailyReportSchema,gy as defineDailyReportSearchSchema,Wt as encodeIdsStreamRows,St as isStreamIdLte,zn as parseClientTempId,Iy as predictSharpThumbnailWorkingSetBytes,Dr as readDailyReportSseStreamEntry,ly as transformJsonArray};
11
+ INSERT INTO ${o} (${V(o.hubId)}, ${V(o.ordinal)}, ${V(o.authorUserId)}, ${V(o.commentText)}) SELECT ${V(o.hubId)}, ${V(o.ordinal)}, ${V(o.authorUserId)}, ${V(o.commentText)} FROM OPENJSON(${i}) WITH (${V(o.hubId)} bigint, ${V(o.ordinal)} int, ${V(o.authorUserId)} bigint, ${V(o.commentText)} nvarchar(max));`},pl=(e,t)=>B`SELECT ${V(e.hubId)} AS ${B.identifier(ke.hubId)}, LOWER(CONVERT(char(64), ${V(e.sourceDigest)}, 2)) AS ${B.identifier(ke.sourceDigest)}, ${V(e.normalizerVersion)} AS ${B.identifier(ke.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${Ir(t)})`,ml=(e,t,r)=>B`SELECT TOP (${r}) ${V(e.id)} AS ${B.identifier(ke.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var yl=e=>({search:async(t,r)=>Fe(r.scope.visible)?[]:xt(await t.execute(ll(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Ut(o[tt.sourceType],tt.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${tt.sourceType} is null`);return{reportHubId:$t(o[tt.reportHubId],tt.reportHubId),businessDate:Ut(o[tt.businessDate],tt.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Fe(r.scope.visible))return new Map;let n=xt(await t.execute(cl(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[Bt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${Bt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set($t(i[Bt.reportHubId],Bt.reportHubId),l)}return a},facetValues:async(t,r)=>Fe(r.scope.visible)?[]:xt(await t.execute(ul(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Ut(o[_r.value],_r.value);if(a===null)throw new Error(`[daily-report] search: column ${_r.value} is null`);return a})});import{chunk as ln,MAX_IN_LIST as cn}from"@aiquants/mssql";import{sql as fl}from"drizzle-orm";import{createHash as wm}from"crypto";var Im=Object.freeze({authorName:"author",customerName:"customer"}),No=e=>e===null?null:Jn(e),hl=(e,t,r)=>{let n=No(r);if(n!==null&&n.length>yt.maxValueLength){let o=yt.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${Im[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},xr=e=>e===null?"n;":`s${e.length}:${e}`,Cr="utf16le",_m=e=>{let t=wm("sha256");t.update(`F${e.fields.length};`,Cr);for(let[r,n]of e.fields)t.update(xr(r)+xr(n),Cr);return t.update(`C${e.comments.length};`,Cr),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${xr(r.text)}`,Cr)}),t.update(`P;${xr(No(e.filterValues.authorName))}${xr(No(e.filterValues.customerName))}`,Cr),t.digest("hex")},Oo=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=rn(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=rn(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:As(r),comments:n,sourceDigest:_m(e),forcedCuts:t,authorName:hl(e.hubId,"authorName",e.filterValues.authorName),customerName:hl(e.hubId,"customerName",e.filterValues.customerName)}};var Rl=e=>{let t=async(s,c)=>{let d=[];for(let u of ln(c,cn))for(let h of xt(await s.execute(il(e.hub,u))))d.push($t(h[ke.hubId],ke.hubId));return d},r=async(s,c)=>{for(let d of ln(c,cn))await s.execute(dl(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of ln(c,cn))for(let h of xt(await s.execute(pl(e.tables.document,u))))d.set($t(h[ke.hubId],ke.hubId),{sourceDigest:Ut(h[ke.sourceDigest],ke.sourceDigest),normalizerVersion:Ut(h[ke.normalizerVersion],ke.normalizerVersion)});return d},o=async(s,c,d)=>xt(await s.execute(ml(e.hub,c,d))).map(u=>$t(u[ke.hubId],ke.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(Oo);u.length>0&&await r(s,u)},i=s=>e.inTransaction(async c=>{await c.execute(fl`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),h=(await e.loadSources(c,d)).map(Oo),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(fl`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;ie("reconcileSearchIndex: batchSize",d,1,cn);let y=se(),R=u===void 0?null:ln([...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 E=await i(D);p={scanned:p.scanned+E.scanned,written:p.written+E.written,skipped:p.skipped+E.scanned-E.written,forcedCuts:p.forcedCuts+E.forcedCuts,lastHubId:D[D.length-1]},m?.(p)}return{...p,elapsedMs:se()-y}}}};import{holdsMultiUnitCluster as xm}from"@aiquants/fuzzy-search/normalize";var Ho=255,un=Object.values(Ht).sort((e,t)=>e-t),Cm=new Intl.Segmenter("und",{granularity:"grapheme"}),Re=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),ut=5e5,dn=Math.floor(ut/Re.linear),Mm=Math.floor(ut/Re.segment),Sl=Math.floor(ut/Re.sweep),bl=Math.floor(ut/Re.scan),Mr=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),Dl=(e,t)=>{let r=0,n=t(),o=ut,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+ut,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=ut,a=!1}}},tb=Object.freeze({fits:()=>!0,charge:()=>{}}),Tl=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 km=(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},Pm=(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*vm(e,t,r,n){let o=!1;for(let c=t;c<r&&!o;c+=dn){let d=Math.min(r,c+dn),u=(d-c)*Re.linear;n.fits(u)||(yield),o=xm(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=Cm.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(Mm,s.value.segment.length);n.fits(c*Re.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*Re.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var Lm=256,Nm=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]},Om=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=Nm(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(Lm/o))},windowStarts:a}})},pn=(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)},gl=(e,t,r)=>{let n=pn(e,t);return e.pieces[n>=0?n:pn(e,r==="start"?t-1:t+1)]},Al=(e,t)=>{let r=pn(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=pn(e,t);if(r<0)return Al(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},Hm=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),Fm=Object.freeze({kind:"done"}),Fo=Object.freeze({kind:"slice"}),$m=Object.freeze({kind:"clusters"}),Um=(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(Re.run))return Fo;let m=gl(e,n.closedStart,"start"),y=gl(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 $m;let R=t(e.offset+Al(e,n.closedStart)),p=t(e.offset+El(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(Re.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(ut))return Fo;let{period:m,continuation:y}=c,R=n.periodicEnd,p=Math.min(i.length,R+Math.max(bl,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)*Re.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 Fm;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(ut))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)*Re.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*Re.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(ut/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*Bm(e,t,r,n,o){if(t.length===0)return;let a=yield*$o(Es(e),Re.strip,n),i=[],l=[];yield*$o(ws(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),Re.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(Re.line)||(yield),n.charge(Re.line);let d=i[c],u=a.text.slice(d,l[c]),h=yield*$o(Is(u,r),Re.plan,n),m=[],y="";for(let p of h.chunks){let f="",D=[];for(let E of p){let S=(E.end-E.start)*Re.normalize;n.fits(S)||(yield);let g=Eo(E.start===0&&E.end===u.length?u:u.slice(E.start,E.end),r).text;n.charge(S),g.length>0&&D.push({start:E.start,end:E.end,text:g,chunkStart:f.length}),f+=g}if(f.length!==0){y.length>0&&(y+=" ");for(let E of D)m.push({start:E.start,end:E.end,text:E.text,plainStart:y.length+E.chunkStart,mapped:null});y+=f}}if(y.length===0)continue;let R={offset:d,plain:y,pieces:m,isCut:!Pm(h,u),lastPiece:0,clusters:void 0};for(let p of t){let f=Hm();for(;;){let D=Um(R,s,p,f,n,o);if(D.kind==="done")break;if(D.kind==="slice"){yield;continue}if(D.kind==="clusters"){R.clusters=yield*vm(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:E}=D,S=(E.end-E.start)*Re.map;n.fits(S)||(yield);let g=u.slice(E.start,E.end);E.mapped=km(Ts(g,Ao(g,r)),E.text),n.charge(S)}}}}function*Vm(e,t,r,n){let o=new Int32Array(un.length),a=0,i=Ho;for(let l=0;l<=e;l+=Sl){let s=Math.min(e+1,l+Sl),c=(s-l)*Re.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=Ho;for(let h=un.length-1;h>=0;h--){let m=un[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*qm(e,t,r,n,o){let a=null;return yield*Bm(e,t,r,n,(l,s,c)=>{a===null&&(a=un.map(()=>new Int32Array(e.length+1))),a[c][l]++,a[c][s]--}),a===null?!0:yield*Vm(e.length,a,n,o)}var jm=(e,t,r,n)=>{let o=Om(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return Tl(function*(){return(yield*qm(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 La)r(mt.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(mt.interviewer(o,"name"),n.name),r(mt.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(mt.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(mt.comment(qn(o),"author"),n.name),r(mt.comment(qn(o),"content"),n.text)});for(let n of e.postedComments)r(mt.comment(n.id,"author"),n.userName),r(mt.comment(n.id,"content"),n.content);return t};function*Wm(e,t){let r=Yn;for(let n=0;n<e.length;n+=dn){let o=Math.min(e.length,n+dn),a=(o-n)*Re.linear;t.fits(a)||(yield),r=zn(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:m}of c.fields){if(!d&&o+m.length>t.maxUnits)return null;let y=await i(Tl(Wm(m,n))),R=await i(jm(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:[]}};import{and as Km,asc as Ml,eq as yn,inArray as Jm,isNull as Qm}from"drizzle-orm";import{and as xl,asc as Ym,eq as mn,getColumns as zm,sql as Gm}from"drizzle-orm";var bt=e=>zm(e),_e=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},Cl=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=w=>br(i.sourceType,w),h=(w,v)=>sn(a,w,c,v),m=Gm`CASE WHEN ${an(a,c)} THEN 1 ELSE 0 END`,y=async w=>{let[v]=await t.select({id:i.id}).top(1).from(i).where(xl(mn(i.id,w),an(a,c)));return v!==void 0},R=w=>w==null||w===""?null:/^\d+$/.test(w)?n(Number(w)):w,p=()=>{let w={};for(let v of s)w[`ext_${v.sourceType}`]=bt(v.table);return w},f=w=>{let v=w;for(let _ of s)v=v.leftJoin(_.table,xl(mn(i.sourceType,_.sourceType),mn(i.sourceIdNum,_.idColumn)));return v},D=w=>{let{hub:v,internal:_}=w,q=v.summary,J=[],G=null,F=null,I=null,U=null,W=null,ce=null,ne=[],de=s.find(Q=>Q.sourceType===v.sourceType),Se=de?w[`ext_${de.sourceType}`]:void 0;if(de&&Se){let Q=de.mapRow(Se);Q.content!==void 0&&(q=Q.content),Q.employeeName!==void 0&&(ce=Q.employeeName),Q.category!==void 0&&(G=Q.category),Q.creationCategory!==void 0&&(F=Q.creationCategory),Q.visitTimeFrom!==void 0&&(I=Q.visitTimeFrom),Q.visitTimeTo!==void 0&&(U=Q.visitTimeTo),Q.customerName!==void 0&&(W=Q.customerName),Q.interviewers!==void 0&&(J=Q.interviewers),Q.externalComments!==void 0&&(ne=Q.externalComments)}else v.sourceType===je&&_&&(q=_.body);return{content:q,author:w.creatorName??R(v.createdBy)??"",employeeName:ce??w.creatorName??R(v.createdBy),updatedBy:R(v.updatedBy),category:G,creationCategory:F,visitTimeFrom:I,visitTimeTo:U,customerName:W,interviewers:J,externalComments:ne}},E=w=>{if(w===1)return!0;if(w===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${vt(w)}`)},S=w=>w.creationCategory!==null&&c.includes(w.creationCategory),g=(w,v)=>E(w.hasDraftLabel)?!0:S(v),C=async w=>{let[v]=await w.select({id:l.id}).top(1).from(l).where(mn(l.name,d)).orderBy(Ym(l.id));return v===void 0?null:v.id},T=()=>C(t);return{visibleSourceTypeCondition:u,draftVisibleTo:h,draftLabelFlag:m,isDraftReport:y,externalSelections:p,applyExternalJoins:f,resolveHubDisplayFields:D,readCanonicalDraftLabelId:C,getDraftLabelId:T,resolveCreationCategoryDraftLabelId:w=>w.some(S)?T():Promise.resolve(null),mapHubRecord:(w,v,_,q,J)=>{let{hub:G}=v,F=v.labels.map(W=>({id:W.id,name:W.name,color:W.color})),I=v.postedCommentRows,U=Ie(w.commentable,G.sourceType);return q!==null&&S(_)&&!F.some(W=>W.id===q)&&F.push({id:q,name:d,color:null}),{reportHubId:G.id,date:_e(G.businessDate,"YYYY-MM-DD"),author:_.author,userId:G.userId?n(G.userId):"",sourceType:G.sourceType,createdAt:_e(G.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:_e(G.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:_.updatedBy,employeeName:_.employeeName,category:_.category,creationCategory:_.creationCategory,visitTimeFrom:_.visitTimeFrom,visitTimeTo:_.visitTimeTo,customerName:_.customerName,interviewers:_.interviewers,subject:G.title,content:_.content,externalComments:U?_.externalComments:[],isRead:v.isRead??!1,isStarred:v.isStarred??!1,readContentDigest:v.readContentDigest??null,isDraft:g(v,_),labels:F,postedComments:I.filter(W=>ps({authorUserId:W.userId},G.sourceType,J,w)).map(W=>({...W,userId:n(W.userId),isMine:J?W.userId===J:!1})),attachments:v.attachments}}}};var kl=(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,E=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(Jm(p.hubId,y)).orderBy(Ml(p.createdAt),Ml(p.id));for(let S of E){let g=S.fileType?String(S.fileType):null,C=S.fileSize!=null?Number(S.fileSize):null,T=c(S.objectCheckedAt,S.objectMissingAt),x={id:f.encode(Number(S.id)),fileName:String(S.fileName),fileType:g,fileSize:C,createdAt:_e(S.createdAt,"YYYY-MM-DD HH:mm:ss"),state:T,hasThumbnail:D&&T!=="absent"&&jr({fileType:g,fileSize:C},s.maxBytes)},O=R.get(Number(S.hubId));O?O.push(x):R.set(Number(S.hubId),[x])}return R},getAttachmentForUser:async(y,R,p)=>{let f=o.attachment;return!f||Fe(y.visible)?null:(await n.select({fileName:f.fileName,filePath:f.filePath,fileType:f.fileType,fileSize:f.fileSize}).top(1).from(f).innerJoin(l,yn(l.id,f.hubId)).where(Km(yn(f.id,R),Qm(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(yn(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(yn(R.id,y))}catch(f){a.error("markAttachmentPresent failed",f)}}}};import{eq as Uo}from"drizzle-orm";import{and as Xm,eq as Pl,isNull as Zm}from"drizzle-orm";var er=async(e,t,r,n)=>{if((await e.update(t).set({deletedAt:null}).output().where(Xm(Pl(t.id,r),Zm(t.deletedAt),n===null?void 0:Pl(t.userId,n)))).length===0)throw new Error("Not Found")};var vl=(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,C,T,x,O)=>{let w=await r(S,C,g);if(!Ie(S.commentable,w.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(w.sourceType.toLowerCase()!==je.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let v=await p(C,w.userId),_=await d(),q=await c(async I=>{await er(I,y,C,null);let[U]=await I.insert(R).output().values({hubId:C,userId:g,body:T,createdAt:new Date,createdBy:String(g),updatedAt:new Date,updatedBy:String(g)});return _!==null&&await _.writeHubs(I,[C]),U}),[J]=await o.select({displayName:i.displayName}).top(1).from(i).where(Uo(i.id,g)),G=J?.displayName??"";if(x){let I=Ve(x);I&&(s.invalidatePrefix(Xt(I)),await n(`${h}${I}`))}s.invalidatePrefix(Ge(C)),await n(`${m}${C}`);let F={id:q.id,userId:l(q.userId),userName:G,content:q.body,createdAt:_e(q.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(Ln.parse({type:"comment-add",reportHubId:C,comment:F,clientTempId:O,recipientRawUserId:v,sourceType:w.sourceType}),"addComment"),F},D=async(S,g)=>await S.select().top(1).from(R).where(Uo(R.id,g));return{addComment:f,deleteComment:async(S,g,C,T,x,O)=>{let w=await D(o,T);if(w.length===0)throw new Error("Not Found");if(w[0].hubId!==C)throw new Error("Not Found");let v=await r(S,w[0].hubId,g);if(w[0].userId!==g)throw new Error("Unauthorized");let _=await p(C,v.userId),q=await d();if(await c(async J=>{await er(J,y,C,null),await J.delete(R).where(Uo(R.id,T)),q!==null&&await q.writeHubs(J,[C])}),x){let J=Ve(x);J&&(s.invalidatePrefix(Xt(J)),await n(`${h}${J}`))}s.invalidatePrefix(Ge(C)),await n(`${m}${C}`),await u(Nn.parse({type:"comment-delete",reportHubId:C,commentId:T,clientTempId:O,recipientRawUserId:_,sourceType:v.sourceType}),"deleteComment")}}};import{and as Nl,eq as Vt,isNull as ey}from"drizzle-orm";var Ll=e=>e===je;var Ol=e=>e===""?null:e,Hl=(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:E,hubLabel:S,userStatus:g}=l,{canonicalDraftLabelName:C,draftLabelNames:T}=m,x=async(F,I,U,W)=>{if(!Pr(U))throw K("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",U);if(!Ie(F.visible,je))throw new Error("Forbidden");c.info("createDailyReport called",{userId:I,businessDate:U});let ce=await u();try{let ne=await d(async b=>{c.info("Starting transaction");let N=await t(b);if(N===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(C)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let L=`internal-temp-${Date.now()}-${Math.random()}`,[P]=await b.insert(D).output().values({sourceType:je,sourceId:L,businessDate:new Date(`${U}T00:00:00Z`),userId:I,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(I),updatedAt:new Date,updatedBy:String(I)});return await b.update(D).set({sourceId:String(P.id)}).where(Vt(D.id,P.id)),c.info("Hub created",P),await b.insert(E).values({hubId:P.id,body:"",createdAt:new Date,createdBy:String(I),updatedAt:new Date,updatedBy:String(I)}),c.info("Internal created"),await b.insert(S).values({hubId:P.id,labelId:N,createdAt:new Date,createdBy:String(I)}),c.info("Label assigned"),await b.insert(g).values({hubId:P.id,userId:I,isRead:!0,isStarred:!1,createdAt:new Date,createdBy:String(I),updatedAt:new Date,updatedBy:String(I),readContentDigest:null}),ce!==null&&await ce.writeHubs(b,[P.id]),P.id});s.invalidatePrefix(Zt(U,I)),s.invalidatePrefix(Co(I)),await a(R),await a(`${p}${U}`);let de=await n(et.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),ne,I,{forceRefresh:!0});if(de===null)throw new Error(`[daily-report] createDailyReport: report ${ne} was committed but its detail read returned nothing`);let Se=await r(de.reportHubId);await h(Fn.parse({type:"report-create",reportHubId:de.reportHubId,report:de,clientTempId:W,recipientRawUserId:Se?I:void 0,actorRawUserId:I}),"createDailyReport");let Q=await n(F,ne,I,{forceRefresh:!0});if(Q===null)throw new Error(`[daily-report] createDailyReport: the actor's scope cannot read report ${ne} it just created`);return Q}catch(ne){throw c.error("Error in createDailyReport",ne),ne}},O=async(F,I)=>await F.select().top(1).from(D).where(Vt(D.id,I)),w=async(F,I,U)=>{await o(F,I,U);let[W]=await O(i,I);if(W===void 0||W.deletedAt)throw new Error("Not Found");if(!Ll(W.sourceType))throw new Error("Forbidden");if(W.userId!==U)throw new Error("Unauthorized");return W},v=async(F,I,U)=>{await F.update(D).set(U).where(Vt(D.id,I))},_=async(F,I,U)=>{await F.update(E).set(U).where(Vt(E.hubId,I))};return{createDailyReport:x,updateDailyReport:async(F,I,U,W,ce)=>{let ne=await w(F,I,U),de=await u();await d(async b=>{await er(b,D,I,U),W.title!==void 0&&await v(b,I,{title:Ol(W.title),updatedAt:new Date,updatedBy:String(U)}),W.content!==void 0&&await _(b,I,{body:Ol(W.content),updatedAt:new Date,updatedBy:String(U)}),de!==null&&await de.writeHubs(b,[I])}),s.invalidatePrefix(Ge(I)),await a(`${f}${I}`);let Se=Ve(_e(ne.businessDate,"YYYY-MM-DD"));Se&&(s.invalidatePrefix(Xt(Se)),await a(`${p}${Se}`));let Q=await n(et.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),I,U,{forceRefresh:!0});if(Q){let b=await r(I);await h($n.parse({type:"report-update",reportHubId:Q.reportHubId,report:Q,clientTempId:ce,recipientRawUserId:b?U:void 0,actorRawUserId:U}),"updateDailyReport")}},publishDailyReport:async(F,I,U,W)=>{let ce=await w(F,I,U),ne=await u();if(await d(async b=>{await er(b,D,I,U),await b.delete(S).where(Nl(Vt(S.hubId,I),ol(y,T))),ne!==null&&await ne.writeHubs(b,[I])}),s.invalidatePrefix(Ge(I)),s.invalidatePrefix(_t),await a(R),ce.businessDate){let b=Ve(_e(ce.businessDate,"YYYY-MM-DD"));b&&await a(`${p}${b}`)}let de=Ve(_e(ce.businessDate,"YYYY-MM-DD"));de&&s.invalidatePrefix(Zt(de,U));let Se=await n(et.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),I,U,{forceRefresh:!0});if(Se===null)return null;let Q=await r(I);return await h(Un.parse({type:"report-publish",reportHubId:Se.reportHubId,report:Se,clientTempId:W,recipientRawUserId:Q?U:void 0,actorRawUserId:U}),"publishDailyReport"),await n(F,I,U,{forceRefresh:!0})},deleteDailyReport:async(F,I,U,W)=>{let ce=await w(F,I,U);if(await d(async ne=>{if((await ne.update(D).set({deletedAt:new Date,deletedBy:String(U),updatedAt:new Date,updatedBy:String(U)}).output().where(Nl(Vt(D.id,I),Vt(D.userId,U),ey(D.deletedAt)))).length===0)throw new Error("Not Found")}),s.invalidatePrefix(Ge(I)),s.invalidatePrefix(_t),await a(R),ce.businessDate){let ne=Ve(_e(ce.businessDate,"YYYY-MM-DD"));ne&&await a(`${p}${ne}`)}await h(Nr.parse({type:"report-delete",reportHubId:I,clientTempId:W,sourceType:ce.sourceType}),"deleteDailyReport")}}};import{and as tr,asc as $l,desc as kr,eq as Pe,inArray as qo,isNull as fn,sql as ay}from"drizzle-orm";import{createHash as ty}from"crypto";var dt="utf16le",ry=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hn=(e,t)=>{if(typeof t=="string"){e.update(`s${t.length}:`,dt),e.update(t,dt);return}if(t==null){e.update("n;",dt);return}if(typeof t=="number"){let n=String(t);e.update(`i${n.length}:${n}`,dt);return}if(typeof t=="boolean"){e.update(t?"t;":"f;",dt);return}let r=JSON.stringify(t);e.update(`j${r.length}:${r}`,dt)},Fl=(e,t,r)=>{if(!Array.isArray(t)){e.update("l",dt),hn(e,t);return}e.update(`a${t.length};`,dt);for(let n of t)if(ry(n)){e.update("o",dt);for(let o of r)hn(e,n[o])}else e.update("v",dt),hn(e,n)},ny=["name","affiliation"],oy=["fileName","fileSize","createdAt"],Bo=e=>{let t=ty("sha256");for(let r of[e.subject,e.content,e.date,e.category,e.creationCategory,e.visitTimeFrom,e.visitTimeTo,e.customerName])hn(t,r);return Fl(t,e.interviewers,ny),Fl(t,e.attachments,oy),t.digest("hex")},Vo=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:Bo(u)}};var Ul=Or([]),iy=6e4,Wo=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw Ye(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw K(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw Ye(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw K(`${e}: options.signal`,r,n);return n},Yo=e=>{let t=async()=>{await new Promise(r=>setImmediate(r)),e.throwIfAborted()};return{sliceMs:Mr.sliceMs,now:se,pause:t}},jo=e=>{try{return{ok:!0,value:e()}}catch(t){return{ok:!1,cause:t}}},sy=e=>jo(()=>{let t=JSON.parse(JSON.stringify(e)),r=pr.safeParse({...t,contentDigest:Bo(t)});if(!r.success)throw new Error(`[daily-report] the detail does not match the delivered detail schema (${Ha(r.error)})`);return r.data}),Bl=(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:E}=e,{idsEpoch:S,dateEpochPrefix:g,detailEpochPrefix:C}=e.settings.redisKeys,{hub:T,internal:x,comment:O,label:w,hubLabel:v,userStatus:_}=m,q=E.idsTtlMs,J=E.businessDateTtlMs,G=async(M,k)=>(await h.select({reportHubId:T.id,businessDate:T.businessDate,sourceType:T.sourceType}).from(T).where(tr(fn(T.deletedAt),t(k,"author-or-authorless"),r(M.visible))).orderBy(kr(T.businessDate),kr(T.id))).map($=>({...$,businessDate:_e($.businessDate,"YYYY-MM-DD")})),F=async(M,k,A)=>{let $=await U(k);return $?Fe(M.visible)?[]:(await h.select({reportHubId:T.id,businessDate:T.businessDate,sourceType:T.sourceType}).top(A).from(T).where(tr(fn(T.deletedAt),t($,"author-or-authorless"),r(M.visible))).orderBy(kr(T.businessDate),kr(T.id))).map(fe=>({...fe,businessDate:_e(fe.businessDate,"YYYY-MM-DD")})):[]},I=new Map,U=async M=>{if(!E.disableUserIdCache&&I.has(M))return I.get(M)??null;let k=await R(M);return k!==null&&!E.disableUserIdCache&&I.set(M,k),k},W=async(M,k,{forceRefresh:A=!1,snapshot:$=!1,ttlMsOverride:j,onFetchStart:fe,admission:He}={})=>{let Te=await U(k);if(!Te)return{items:[],streamAnchor:null,snapshot:Ul};if(Fe(M.visible))return{items:[],streamAnchor:await d(),snapshot:Ul};let he=Ls(Te,Qr(M)),[ge]=await p.getOrFetch({cacheKey:he,fetcher:async()=>{let We=await d(),nt=await G(M,Te);if(!Ma(nt)){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 re=[...nt].sort(Vn);return[{items:re,streamAnchor:We,snapshot:Or(re)}]}return[{items:nt,streamAnchor:We,snapshot:Or(nt)}]},onFetchStart:fe,forceRefresh:A,snapshot:$,admission:He,ttlMsOverride:j??q,epochKey:S,refreshAheadRatio:.5});if(ge===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return ge},ce=async(M,k,A)=>{let $=await a(h.select({hub:bt(T),internal:bt(x),isRead:_.isRead,isStarred:_.isStarred,readContentDigest:_.readContentDigest,creatorName:y.displayName,hasDraftLabel:n,...o()}).from(T)).leftJoin(x,Pe(T.id,x.hubId)).leftJoin(_,tr(Pe(T.id,_.hubId),Pe(_.userId,k))).leftJoin(y,Pe(T.userId,y.id)).where(tr(A,fn(T.deletedAt),t(k,"author"),r(M.visible))).orderBy(kr(T.id));if($.length===0)return[];let j=$.map(re=>re.hub.id),fe=await h.select({hubId:v.hubId,id:w.id,name:w.name,color:w.color}).from(v).innerJoin(w,Pe(v.labelId,w.id)).where(qo(v.hubId,j)),He=await h.select({hubId:O.hubId,id:O.id,body:O.body,createdAt:O.createdAt,userId:O.userId,userName:y.displayName}).from(O).leftJoin(y,Pe(O.userId,y.id)).where(qo(O.hubId,j)).orderBy($l(O.createdAt)),Te=await c(j),he=new Map,ge=new Map;for(let re of fe){let Le=he.get(re.hubId);Le||(Le=[],he.set(re.hubId,Le)),Le.push({id:re.id,name:re.name,color:re.color})}for(let re of He){let Le=ge.get(re.hubId);Le||(Le=[],ge.set(re.hubId,Le)),Le.push({id:re.id,content:re.body,createdAt:_e(re.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:re.userId,userName:re.userName||""})}let We=$.map(re=>jo(()=>i(re))),nt=await l(We.flatMap(re=>re.ok?[re.value]:[]));return $.map((re,Le)=>{let pt=re.hub.id,kt=We[Le],Tt=kt.ok?jo(()=>s(M,{...re,attachments:Te.get(pt)??[],labels:he.get(pt)||[],postedCommentRows:ge.get(pt)||[]},kt.value,nt,k)):kt;return Tt.ok?{reportHubId:pt,outcome:"ok",report:Tt.value}:{reportHubId:pt,outcome:"failed",cause:Tt.cause}})},ne=async(M,k,A)=>(await ce(M,k,A)).map($=>{if($.outcome==="failed")throw $.cause;return Vo($.report)}),de=M=>Me({windowMs:iy,tallies:["failed"],writeSuppressed:(k,{count:A,since:$})=>{D.warn(`failed_report_suppressed count=${A} since=${$} read=${M} report=${k}`)}}),Se={markDailyReportSearchHits:de("markDailyReportSearchHits"),getDailyReportDetailsByIdsByExternalId:de("getDailyReportDetailsByIdsByExternalId")},Q=(M,k,A)=>{Se[M].record(k,"failed",()=>D.error(`${M}: report ${k} passed the visibility predicate but its own assembly failed`,A))},b=(M,k)=>{let A=k.outcome==="ok"?sy(k.report):{ok:!1,cause:k.cause};return A.ok?{reportHubId:k.reportHubId,outcome:"ok",report:A.value}:(Q(M,k.reportHubId,A.cause),{reportHubId:k.reportHubId,outcome:"failed"})},N=async(M,k,A,{read:$,signal:j,slicing:fe})=>{let He=await ce(M,k,qo(T.id,[...A]));j.throwIfAborted();let Te=[],he=fe.now();for(let ge of He)Te.length>0&&fe.now()-he>=fe.sliceMs&&(await fe.pause(),he=fe.now()),Te.push(b($,ge));return Te},L=async(M,k,A,{forceRefresh:$=!1,snapshot:j=!1,ttlMsOverride:fe,admission:He}={})=>{let Te=await U(A);if(!Te)return[];let he=Ve(k);if(!he)return[];if(Fe(M.visible))return[];let ge=Ns(he,Te,Qr(M));return p.getOrFetch({cacheKey:ge,fetcher:()=>ne(M,Te,Pe(T.businessDate,ay`${he}`)),forceRefresh:$,snapshot:j,admission:He,ttlMsOverride:fe??J,epochKey:`${g}${he}`})},P=async(M,k,A,{forceRefresh:$=!1,snapshot:j=!1,ttlMsOverride:fe,admission:He}={})=>{if(Fe(M.visible))return null;let Te=Os(k,A,Qr(M));return(await p.getOrFetch({cacheKey:Te,fetcher:async()=>{let ge=await a(h.select({hub:bt(T),internal:bt(x),isRead:_.isRead,isStarred:_.isStarred,readContentDigest:_.readContentDigest,creatorName:y.displayName,hasDraftLabel:n,...o()}).from(T)).leftJoin(x,Pe(T.id,x.hubId)).leftJoin(_,tr(Pe(T.id,_.hubId),Pe(_.userId,A))).leftJoin(y,Pe(T.userId,y.id)).where(tr(Pe(T.id,k),fn(T.deletedAt),t(A,"author"),r(M.visible)));if(ge.length===0)return[];let We=ge[0].hub.id,nt=await h.select({id:w.id,name:w.name,color:w.color}).from(v).innerJoin(w,Pe(v.labelId,w.id)).where(Pe(v.hubId,We)),re=await h.select({id:O.id,body:O.body,createdAt:O.createdAt,userId:O.userId,userName:y.displayName}).from(O).leftJoin(y,Pe(O.userId,y.id)).where(Pe(O.hubId,We)).orderBy($l(O.createdAt)),Le=await c([We]),pt=nt.map(Ke=>({id:Ke.id,name:Ke.name,color:Ke.color})),kt=re.map(Ke=>({id:Ke.id,content:Ke.body,createdAt:_e(Ke.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Ke.userId,userName:Ke.userName||""})),Tt=i(ge[0]),En=await l([Tt]);return[Vo(s(M,{...ge[0],attachments:Le.get(We)??[],labels:pt,postedCommentRows:kt},Tt,En,A))]},forceRefresh:$,snapshot:j,admission:He,ttlMsOverride:fe??J,epochKey:`${C}${k}`}))[0]??null};return{getUserIdByExternalId:U,getDailyReportIdsByExternalId:W,getDailyReportIdsFirstPageByExternalId:F,getDailyReportsByBusinessDateByExternalId:L,getDailyReportDetailById:P,getDailyReportDetailByIdByExternalId:async(M,k,A,$={})=>{let j=await U(A);return j?P(M,k,j,$):null},getDailyReportDetailsByIdsByExternalId:async(M,k,A,$)=>{let j=Wo("getDailyReportDetailsByIdsByExternalId",$);if(k.length>Ce.maxDetailIds)throw K("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${Ce.maxDetailIds} ids`,k.length);let fe=await U(A);if(!fe||k.length===0||Fe(M.visible))return k.map(yr);j.throwIfAborted();let He=await N(M,fe,k,{read:"getDailyReportDetailsByIdsByExternalId",signal:j,slicing:Yo(j)}),Te=new Map(He.map(he=>[he.reportHubId,he]));return k.map(he=>{let ge=Te.get(he);return ge===void 0?yr(he):ge})},fetchDeliveredHubOutcomes:N,invalidateHubReadCaches:async(M,k)=>{p.invalidatePrefix(_t),await u(S);for(let A of new Set(M))p.invalidatePrefix(Ge(A)),await u(`${C}${A}`);for(let A of new Set(k)){let $=Ve(A);$&&await u(`${g}${$}`)}},clearCache:async()=>{p.clearAll(),I.clear(),f&&await u(S),D.info("Server-side DB/SQL caches cleared successfully.")}}};var ly="v5",cy=/^(?!:)[^\s\p{Cc}]+(?<!:)$/u,zo=e=>{if(typeof e!="string"||!cy.test(e))throw K("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:${ly}`,idsEpoch:`${e}:ids:epoch`,dateEpochPrefix:`${e}:date-epoch:`,detailEpochPrefix:`${e}:detail-epoch:`})};var Rn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,redisKeyPrefix:"daily-report",streamMaxLen:1e4}),uy=e=>{let{length:t}=e;if(t===void 0)throw K("tables.hub.title","a character column with a declared length",t);return ie("tables.hub.title.length",t,1)},dy=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 K("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},py=e=>{let t=new Map([[je.toLowerCase(),`the internal source type ${JSON.stringify(je)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw K(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([je,...e.map(r=>r.sourceType)])},my=e=>{let t=e===void 0?void 0:e.getSQLType();if(t!=="char(64)")throw K("tables.userStatus.readContentDigest","a char(64) column (the version the viewer marked read, 64 lowercase hex digits)",t)},Vl=e=>{let t=e.externalSources??[],r=dy(e.draftLabelNames);if(Yr(e),Object.hasOwn(e,"streamKey"))throw Ye("redisKeyPrefix","given in place of the removed key streamKey");let n=Yi(e.attachments),o=uy(e.tables.hub.title);go(e.tables.hub.sourceType),my(e.tables.userStatus.readContentDigest);let a=Ne("idsTtlMs",e.idsTtlMs,1,Rn.idsTtlMs),i=Ne("businessDateTtlMs",e.businessDateTtlMs,1,Rn.businessDateTtlMs),l=Ne("streamMaxLen",e.streamMaxLen,1,Rn.streamMaxLen),s=zo(e.redisKeyPrefix===void 0?Rn.redisKeyPrefix:e.redisKeyPrefix);return Object.freeze({externalSources:t,sourceTypes:py(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamMaxLen:l,redisKeys:s,disableUserIdCache:!!e.disableUserIdCache})};var ql=({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=se();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let y=se()-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?wt:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});import{and as hy,eq as fy,sql as ye}from"drizzle-orm";var Sn=["hubId","userId","isRead","isStarred","createdAt","createdBy","updatedAt","updatedBy","readContentDigest"],Ry={isRead:{statusType:"read",callerName:"setReadStatus"},isStarred:{statusType:"star",callerName:"setStarStatus"}},$e=e=>ye`${ye.identifier(e.name)}`,Sy=(e,t)=>{let{reportHubId:r,userId:n,value:o,at:a}=t,i=String(n),l=$e(e[t.flag]),s=$e(e.readContentDigest),c=t.flag==="isRead"?t.readContentDigest:null,d=t.flag==="isRead"?ye`t.${l} = ${o} AND (t.${s} = ${c} OR (t.${s} IS NULL AND ${c} IS NULL))`:ye`t.${l} = ${o}`,u=(f,D)=>ye`t.${$e(f)} = CASE WHEN ${d} THEN t.${$e(f)} ELSE ${D} END`,h={hubId:ye`s.${$e(e.hubId)}`,userId:ye`s.${$e(e.userId)}`,isRead:ye`${t.flag==="isRead"?o:!1}`,isStarred:ye`${t.flag==="isStarred"?o:!1}`,createdAt:ye`${a}`,createdBy:ye`${i}`,updatedAt:ye`${a}`,updatedBy:ye`${i}`,readContentDigest:ye`${c}`},m=ye.join(Sn.map(f=>$e(e[f])),ye`, `),y=ye.join(Sn.map(f=>h[f]),ye`, `),R=ye.join(Sn.map(f=>ye`inserted.${$e(e[f])} AS ${ye.identifier(f)}`),ye`, `),p=t.flag==="isRead"?ye`, t.${s} = ${c}`:ye``;return ye`MERGE ${e} WITH (HOLDLOCK) AS t USING (SELECT ${r} AS ${$e(e.hubId)}, ${n} AS ${$e(e.userId)}) AS s ON t.${$e(e.hubId)} = s.${$e(e.hubId)} AND t.${$e(e.userId)} = s.${$e(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};`},jl=(e,t)=>(typeof e=="number"||typeof e=="string")&&String(e)===String(t),Wl=e=>e instanceof Date||typeof e=="string",gy=e=>{if(!Array.isArray(e))return`recordset ${vt(e)}`;if(e.length!==1)return`${e.length} rows`;let[t]=e;return typeof t!="object"||t===null?`a row of ${vt(t)}`:Sn.map(r=>`${r}=${vt(t[r])}`).join(", ")},by=(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||!jl(a.hubId,t)||!jl(a.userId,r)||typeof a.isRead!="boolean"||typeof a.isStarred!="boolean"||!Wl(a.createdAt)||!Wl(a.updatedAt)||typeof a.createdBy!="string"||typeof a.updatedBy!="string"||!(a.readContentDigest===null||Lt(a.readContentDigest)))throw new Error(`[daily-report] user status: the upsert must output the one status row of report ${t} and user ${r}; got ${gy(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}},Yl=(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(hy(fy(c.id,p),t(f,"author")));return D??null},h=async(p,f,D)=>{let E=await u(f,D);if(!E||E.deletedAt||!Ie(p.visible,E.sourceType))throw new Error("Not Found");return{sourceType:E.sourceType,userId:E.userId}},m=async(p,f,D,E)=>{let{reportHubId:S,userId:g}=D;await h(p,S,g);let C=by(await n.execute(Sy(d,D)),D);if(f){let O=Ve(f);O&&(a.invalidatePrefix(Zt(O,g)),await r(`${l}${O}`))}a.invalidatePrefix(Mo(S,g)),await r(`${s}${S}`);let{statusType:T,callerName:x}=Ry[D.flag];return await i(vn.parse({type:"status-update",reportHubId:S,recipientRawUserId:g,statusType:T,value:D.value,readContentDigest:C.readContentDigest,clientTempId:E}),x),C};return{assertHubMutable:h,setStarStatus:(p,f,D,E,S,g)=>m(p,E,{flag:"isStarred",reportHubId:D,userId:f,value:S,at:new Date},g),setReadStatus:(p,f,D,E,S,g)=>S.isRead&&!Lt(S.contentDigest)?Promise.reject(K("setReadStatus: contentDigest","64 lowercase hex digits",S.contentDigest)):m(p,E,{flag:"isRead",reportHubId:D,userId:f,value:S.isRead,readContentDigest:S.isRead?S.contentDigest:null,at:new Date},g)}};var Ey=Object.freeze([]),Go=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},Dn=(e,t)=>e.get(t)??Ey,zl=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(en);function Ko(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=Vl(e),{externalSources:R,draftLabelNames:p,attachmentDelivery:f,titleMaxLength:D}=y,E=De(e.logger,1,"Service"),S=te=>Ay(me=>t.transaction(Z=>me(()=>te(Z))),e.transactionRetry),g=e.search===void 0?null:rl(e.search,R.map(te=>te.sourceType)),C={hub:c,hubLabel:m,label:h},T=g===null?null:yl({tables:{...C,search:g.tables},draftLabelNames:p});g!==null&&Io();let x=null,O=async()=>{if(g===null)return null;if(x===null){let te=await Io(),me=g.externalSourceTexts;x=Rl({hub:c,tables:g.tables,loadSources:(Z,oe)=>Ke(Z,oe,me),inTransaction:S,normalizerVersion:te})}return x},{incrementRedisEpoch:w,publishToSseStream:v,readSseStreamAnchor:_}=ql({redis:i,logger:E,epochs:s,streamKey:y.redisKeys.sseStream,streamMaxLen:y.streamMaxLen}),q={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:E,settings:y,draftVisibilityTables:C,inTransaction:S,publishToSseStream:v,prepareSearchIndex:O},{visibleSourceTypeCondition:J,draftVisibleTo:G,draftLabelFlag:F,isDraftReport:I,externalSelections:U,applyExternalJoins:W,resolveHubDisplayFields:ce,readCanonicalDraftLabelId:ne,getDraftLabelId:de,resolveCreationCategoryDraftLabelId:Se,mapHubRecord:Q}=Cl(q),{getAttachmentsByHubIds:b,getAttachmentForUser:N,markAttachmentMissing:L,markAttachmentPresent:P}=kl(q,{draftVisibleTo:G,visibleSourceTypeCondition:J}),{getUserIdByExternalId:H,getDailyReportIdsByExternalId:Y,getDailyReportIdsFirstPageByExternalId:X,getDailyReportsByBusinessDateByExternalId:z,getDailyReportDetailById:M,getDailyReportDetailByIdByExternalId:k,getDailyReportDetailsByIdsByExternalId:A,fetchDeliveredHubOutcomes:$,invalidateHubReadCaches:j,clearCache:fe}=Bl(q,{draftVisibleTo:G,visibleSourceTypeCondition:J,draftLabelFlag:F,externalSelections:U,applyExternalJoins:W,resolveHubDisplayFields:ce,resolveCreationCategoryDraftLabelId:Se,mapHubRecord:Q,getAttachmentsByHubIds:b,readSseStreamAnchor:_,incrementRedisEpoch:w}),{assertHubMutable:He,setStarStatus:Te,setReadStatus:he}=Yl(q,{draftVisibleTo:G,incrementRedisEpoch:w}),{addComment:ge,deleteComment:We}=vl(q,{isDraftReport:I,assertHubMutable:He,incrementRedisEpoch:w}),{createDailyReport:nt,updateDailyReport:re,publishDailyReport:Le,deleteDailyReport:pt}=Hl(q,{readCanonicalDraftLabelId:ne,isDraftReport:I,getDailyReportDetailById:M,assertHubMutable:He,incrementRedisEpoch:w}),kt=async(te,me)=>{let Z=new Map,oe=r.attachment;if(!oe||f===null)return Z;let Ee=await te.select({hubId:oe.hubId,fileName:oe.fileName}).from(oe).where(bn(oe.hubId,[...me])).orderBy(Dt(oe.hubId),Dt(oe.createdAt),Dt(oe.id));for(let ae of Ee)Go(Z,Number(ae.hubId),String(ae.fileName));return Z},Tt=async(te,me,Z)=>{let oe=new Map;for(let[Ee,ae]of Z){let ot=new Map;for(let{hub:Ue}of me)Ue.sourceType===Ee&&Ue.sourceIdNum!==null&&ot.set(Ue.sourceIdNum,Ue.id);if(ot.size===0)continue;let At=await ae(te,[...ot.keys()]);for(let[Ue,at]of At){let Pt=ot.get(Ue);if(Pt===void 0)throw K(`search.externalSourceTexts.${Ee} answer key`,"a source id that was asked for",Ue);if(!(Array.isArray(at)&&at.every(rr=>typeof rr=="string")))throw K(`search.externalSourceTexts.${Ee} answer for ${Ue}`,"an array of strings",at);oe.set(Pt,at)}}return oe},En=(te,me)=>{let Z=ce(te),oe=[["subject",te.hub.title],["content",Z.content],["author",Z.author],["employeeName",Z.employeeName],["updatedBy",Z.updatedBy],["category",Z.category],["creationCategory",Z.creationCategory],["customerName",Z.customerName]];for(let ae of Z.interviewers)oe.push(["interviewerName",ae.name??null],["interviewerAffiliation",ae.affiliation??null]);for(let ae of me.labelNames)oe.push(["label",ae]);for(let ae of me.attachmentNames)oe.push(["attachment",ae]);for(let ae of me.extraTexts)oe.push(["extra",ae]);let Ee=[];for(let ae of Z.externalComments)Ee.push({authorUserId:null,text:zl(ae.name,ae.text)});for(let ae of me.postedComments)Ee.push({authorUserId:ae.userId,text:zl(ae.userName,ae.body)});return{hubId:te.hub.id,fields:oe,comments:Ee,filterValues:{authorName:Z.employeeName,customerName:Z.customerName}}},Ke=async(te,me,Z)=>{let oe=[];for(let Ee of Dy(me,Ty)){let ae=await W(te.select({hub:bt(c),internal:bt(d),creatorName:n.displayName,...U()}).from(c)).leftJoin(d,gn(c.id,d.hubId)).leftJoin(n,gn(c.userId,n.id)).where(bn(c.id,[...Ee])).orderBy(Dt(c.id)),ot=new Map,At=await te.select({hubId:m.hubId,name:h.name}).from(m).innerJoin(h,gn(m.labelId,h.id)).where(bn(m.hubId,[...Ee])).orderBy(Dt(m.hubId),Dt(h.id));for(let Je of At)Go(ot,Je.hubId,Je.name);let Ue=new Map,at=await te.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,gn(u.userId,n.id)).where(bn(u.hubId,[...Ee])).orderBy(Dt(u.hubId),Dt(u.createdAt),Dt(u.id));for(let Je of at)Go(Ue,Je.hubId,Je);let Pt=await kt(te,Ee),rr=await Tt(te,ae,Z);for(let Je of ae){let Be=Je.hub.id;oe.push(En(Je,{labelNames:Dn(ot,Be),postedComments:Dn(Ue,Be),attachmentNames:Dn(Pt,Be),extraTexts:Dn(rr,Be)}))}}return oe},yc=(te,me,Z)=>T===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):T.search(t,{criteria:Z,viewerUserId:me,scope:te}),Qo=y.sourceTypes,hc=async(te,me)=>{if(T===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let Z=Qo.filter(ae=>Ie(te.visible,ae)),oe=await T.facetValues(t,{column:"authorName",viewerUserId:me,scope:te}),Ee=await T.facetValues(t,{column:"customerName",viewerUserId:me,scope:te});return{sourceTypes:Z,authors:oe,customers:Ee}},fc=async(te,me,Z,oe,Ee)=>{let ae=Wo("markDailyReportSearchHits",Ee);if(T===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(oe.length>Ce.maxDetailIds)throw K("markDailyReportSearchHits: reportHubIds",`at most ${Ce.maxDetailIds} ids`,oe.length);let ot=Hr(Dr(Z));if(oe.length===0||Fe(te.visible))return{wordsDigest:ot,reports:[],deferred:[]};ae.throwIfAborted();let At=Yo(ae),Ue=await $(te,me,oe,{read:"markDailyReportSearchHits",signal:ae,slicing:At});await At.pause();let at=Ue.flatMap(Be=>Be.outcome==="ok"?[{reportHubId:Be.reportHubId,fields:Il(Be.report)}]:[]),Pt=Z.combine==="union"&&Z.sets.length>=2&&at.length>0?await T.matchedSets(t,{plan:Z,viewerUserId:me,scope:te,ids:at.map(Be=>Be.reportHubId)}):null,rr=at.map(({reportHubId:Be,fields:Sc})=>{let Xo=Pt===null?null:Pt.get(Be),Zo=Xo===void 0?0:Xo;return{reportHubId:Be,matchedSets:Zo,alternatives:wl(Z,Zo).flatMap(gc=>gc.alternatives),fields:Sc}}),Je=await _l(rr,Mr,At.pause,Dl(Mr,At.now));return{wordsDigest:ot,reports:Je.reports,deferred:Je.deferred}},Rc=async te=>{let me=await O();if(me===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return me.reconcile(t,te)};return{streamKey:y.redisKeys.sseStream,attachmentDelivery:f,titleMaxLength:D,searchLimits:g===null?null:{concurrency:g.concurrency,rateLimitPerMinute:g.rateLimitPerMinute},searchFilterSourceTypes:Qo,clearCache:fe,invalidateHubReadCaches:j,getUserIdByExternalId:H,getDailyReportIdsByExternalId:Y,getDailyReportIdsFirstPageByExternalId:X,readSseStreamAnchor:_,getDailyReportsByBusinessDateByExternalId:z,getDailyReportDetailById:M,getDailyReportDetailByIdByExternalId:k,getDailyReportDetailsByIdsByExternalId:A,getDraftLabelId:de,searchDailyReports:yc,markDailyReportSearchHits:fc,listDailyReportSearchFacets:hc,reconcileSearchIndex:Rc,getAttachmentsByHubIds:b,getAttachmentForUser:N,markAttachmentMissing:L,markAttachmentPresent:P,setStarStatus:Te,setReadStatus:he,addComment:ge,deleteComment:We,createDailyReport:nt,updateDailyReport:re,publishDailyReport:Le,deleteDailyReport:pt}}var wy=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(De(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return De(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};import{desc as Gl,sql as Iy}from"drizzle-orm";import{bigint as xe,bit as Kl,char as _y,date as xy,datetime2 as ve,foreignKey as rt,index as Mt,int as Cy,mssqlSchema as My,nvarchar as ue,primaryKey as qt,uniqueIndex as ky}from"drizzle-orm/mssql-core";function Py(e,t){let r=My(e),n=t.userTable,o=r.table("DailyReportHub",{id:xe("id",{mode:"number"}).identity().notNull(),sourceType:ue("source_type",{length:20}).notNull(),sourceId:ue("source_id",{length:100}).notNull(),sourceIdNum:xe("source_id_num",{mode:"number"}).generatedAlwaysAs(Iy`TRY_CAST(source_id AS BIGINT)`),businessDate:xy("business_date"),userId:xe("user_id",{mode:"number"}),title:ue("title",{length:200}),summary:ue("summary",{length:"max"}),createdAt:ve("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ve("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull(),deletedAt:ve("deleted_at"),deletedBy:ue("deleted_by",{length:50})},u=>[qt({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),rt({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),Mt(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),Mt(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),Mt(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),Mt(`${e}_DailyReportHub_user_id_index`).on(u.userId),Mt(`${e}_DailyReportHub_business_date_id_index`).on(Gl(u.businessDate),Gl(u.id)),Mt(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:xe("hub_id",{mode:"number"}).notNull(),body:ue("body",{length:"max"}),metadata:ue("metadata",{length:"max"}),createdAt:ve("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ve("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[qt({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),rt({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:xe("id",{mode:"number"}).identity().notNull(),hubId:xe("hub_id",{mode:"number"}).notNull(),userId:xe("user_id",{mode:"number"}).notNull(),body:ue("body",{length:"max"}).notNull(),createdAt:ve("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ve("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[qt({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),rt({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),rt({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),Mt(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:xe("id",{mode:"number"}).identity().notNull(),userId:xe("user_id",{mode:"number"}),name:ue("name",{length:50}).notNull(),color:ue("color",{length:20}),sortOrder:Cy("sort_order"),createdAt:ve("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ve("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[qt({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),rt({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:xe("hub_id",{mode:"number"}).notNull(),labelId:xe("label_id",{mode:"number"}).notNull(),createdAt:ve("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull()},u=>[qt({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),rt({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),rt({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:xe("hub_id",{mode:"number"}).notNull(),userId:xe("user_id",{mode:"number"}).notNull(),isRead:Kl("is_read").default(!1).notNull(),isStarred:Kl("is_starred").default(!1).notNull(),createdAt:ve("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ve("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull(),readContentDigest:_y("read_content_digest",{length:64})},u=>[qt({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),rt({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),rt({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:xe("id",{mode:"number"}).identity().notNull(),hubId:xe("hub_id",{mode:"number"}).notNull(),uploadedBy:xe("uploaded_by",{mode:"number"}),sourceKey:ue("source_key",{length:200}).notNull(),fileName:ue("file_name",{length:255}).notNull(),filePath:ue("file_path",{length:"max"}).notNull(),fileType:ue("file_type",{length:100}),fileSize:xe("file_size",{mode:"number"}),objectCheckedAt:ve("object_checked_at"),objectMissingAt:ve("object_missing_at"),createdAt:ve("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ve("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[qt({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),rt({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),rt({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),ky(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),Mt(`${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}}import{bigint as Jo,binary as Jl,datetime2 as vy,int as Ly,mssqlSchema as Ny,nvarchar as Tn,primaryKey as Ql,varchar as Oy}from"drizzle-orm/mssql-core";function Hy(e){let t=Ny(e),r=t.table("DailyReportSearchDocument",{hubId:Jo("hub_id",{mode:"number"}).notNull(),searchText:Tn("search_text",{length:"max"}).notNull(),sourceDigest:Jl("source_digest",{length:32}).notNull(),normalizerVersion:Oy("normalizer_version",{length:64}).notNull(),indexedAt:vy("indexed_at").notNull(),rowVersion:Jl("row_version",{length:8}).notNull(),authorName:Tn("author_name",{length:yt.maxValueLength}),customerName:Tn("customer_name",{length:yt.maxValueLength})},o=>[Ql({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:Jo("hub_id",{mode:"number"}).notNull(),ordinal:Ly("ordinal").notNull(),authorUserId:Jo("author_user_id",{mode:"number"}),commentText:Tn("comment_text",{length:"max"}).notNull()},o=>[Ql({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var Fy=5e7,lc=2e8,$y=1,cc=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})})}),Xl=125,Zl=4,ec=16,tc=50,rc=2,An=Object.freeze({renderMs:qe.renderMs,nanosecondsPerBlockVisit:Xl,margin:Zl,maxBlockVisits:Math.floor(qe.renderMs*1e6/(Xl*Zl)),walkBudgetMs:ec,nanosecondsPerWalkStep:tc,walkMargin:rc,maxWalkSteps:Math.floor(ec*1e6/(tc*rc))}),Uy=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),nc=75,oc=4,ac="#ffffff",By=1,Vy={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},qy=[/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/],ic=Object.freeze({ok:!1,reason:"failed"}),sc=Object.freeze({ok:!1,reason:"unsupported"}),uc=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:_i(e)}),dc=(e,t)=>{switch(t){case"jpeg":{let r=mo(e);return r===null?null:uc(r)}case"png":{let r=Mi(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=ki(e,An.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},pc=(e,t)=>{let r=Uy.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=cc,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},jy=(e,t,r)=>{let n=dc(e,t);return n===null?null:pc(n,r)},Wy=e=>e!==null&&e<=lc,Yy=(e,t)=>{if(t!=="jpeg")return dc(e,t);let r=xi(e,An);return r===null||r.blockVisits>An.maxBlockVisits?null:uc(r.header)},zy=e=>{let t=e instanceof Error?e.message:"";return qy.some(r=>r.test(t))?"failed":"unsupported"},Gy=e=>{e.cache(!1),e.concurrency($y),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Vy)});let t=async(n,o,a,i,l)=>{let s=Yy(n,o);if(s===null)return sc;try{let c=e(n,{limitInputPixels:Fy,animated:!1});if(!Wy(pc(s,await c.metadata())))return sc;if(l.aborted)return ic;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:ac}).webp({quality:nc,effort:oc}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:zy(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?ic:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${nc}-e${oc}/flatten-${ac}/v${By}`,render:r}};var mc=6e4,Ky=e=>{let t=ie("ttlMs",e.ttlMs,1,mc),r=or("readViewerKey",e.readViewerKey),n=or("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=se(),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 uT(e){e.redis||De(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=Cn(e.redis),r=new ir({defaultTtlMs:e.cacheDefaultTtlMs,maxBuckets:e.cacheMaxBuckets,maxBytes:e.cacheMaxBytes},t),n=Ko({...e,cache:r,epochs:t}),o=new Er({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Po({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}}export{ho as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,yo as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,lc as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,An as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,cc as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,ko as DAILY_REPORT_SSE_CATCH_UP_BATCH,qs as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,mc as DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS,Er as DailyReportSseReader,et as DailyReportViewerScope,ir as SqlResultCache,zo as buildDailyReportRedisKeys,Po as createDailyReportHandlers,uT as createDailyReportServer,Ko as createDailyReportService,Ky as createDailyReportVisibilityCache,Cn as createEpochStore,Gy as createSharpThumbnailRenderer,Bn as dailyReportSseStreamMessageSchema,Py as defineDailyReportSchema,Hy as defineDailyReportSearchSchema,zt as encodeIdsStreamRows,gt as isStreamIdLte,Qn as parseClientTempId,jy as predictSharpThumbnailWorkingSetBytes,Ar as readDailyReportSseStreamEntry,wy as transformJsonArray};
15
15
  /* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */