@aiquants/daily-report 0.51.1 → 0.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -1
- package/README.md +17 -7
- package/dist/client.js +5 -5
- package/dist/client.mjs +5 -5
- package/dist/server.js +8 -8
- package/dist/server.mjs +6 -6
- package/dist/styles/daily-report.standalone.css +1 -1
- package/package.json +5 -5
package/dist/server.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
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","SessionGate"]),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(`
|
|
1
|
+
var Zo=e=>{throw TypeError(e)};var ea=(e,t,r)=>t.has(e)||Zo("Cannot "+r);var nr=(e,t,r)=>(ea(e,t,"read from private field"),r?r.call(e):t.get(e)),wn=(e,t,r)=>t.has(e)?Zo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),In=(e,t,r,n)=>(ea(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 ta=e=>e<10?`0${e}`:`${e}`,Cc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=ta(e.getMonth()+1),n=ta(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),aa=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,Et=(e,t)=>({code:"invalid_type",expected:e,received:aa(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},ra=(e,t,r)=>{let n={};for(let o=0;o<r;o+=1){let a=t[o];a in e&&(n[a]=e[a])}return n},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=ra(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?Nt:a!==null?a:Pc(n)===l?n:ra(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)),na=(e,t,r)=>e===null||typeof e=="string"?e:ze(t,r,Et("string",e)),oa=(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)),ia=(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:ia(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},sa={present:!0,absent:!0,unknown:!0},la=Object.keys(sa),Nc=la.map(e=>`'${e}'`).join(" | "),Oc=(e,t,r)=>typeof e!="string"?ze(t,r,{code:"invalid_type",expected:Nc,received:aa(e)}):Object.hasOwn(sa,e)?e:ze(t,r,{code:"invalid_enum_value",received:e,options:[...la]}),ca=Wt({name:pe,affiliation:pe}),ua=Wt({name:pe,text:pe,color:pe}),da=Wt({id:kn,name:pe,color:pe}),pa=Wt({id:kn,userId:pe,userName:pe,content:pe,createdAt:pe,isMine:cr}),Hc=Wt({id:oa,fileName:oa,fileType:na,fileSize:vc,createdAt:na,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(ca)),subject:pe,content:pe,externalComments:lr(sr(ua)),isRead:cr,isStarred:cr,contentDigest:ia,readContentDigest:Lc,isDraft:cr,labels:lr(sr(da)),postedComments:lr(sr(pa)),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}},ma=e=>ur(Fc,e),ya=e=>ur(ca,e),ha=e=>ur(ua,e),fa=e=>ur(da,e),Ra=e=>ur(pa,e);var Sa=15e3,ga="lastEventId",$c=/^\d{1,15}-\d{1,15}$/,ba=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}),fh=dr(ya),Rh=dr(ha),Sh=dr(fa),Uc=dr(Ra),pr=dr(ma),mr=ee.string().regex(vr),Da=ee.object({type:ee.literal("connected")}),Ta=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(),Aa=ee.object({type:ee.literal("comment-add"),reportHubId:Oe,comment:Uc,clientTempId:mr,sourceType:Pn}),Ea=ee.object({type:ee.literal("comment-delete"),reportHubId:Oe,commentId:Oe,clientTempId:mr,sourceType:Pn}),Lr={recipientRawUserId:Oe.optional()},vn=Ta.extend(Lr),Ln=Aa.extend(Lr),Nn=Ea.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}),gh=ee.discriminatedUnion("type",[Da,Ta,Aa,Ea,Bc,Vc,qc,Nr]),Bn=ee.discriminatedUnion("type",[Da,vn,Ln,Nn,Fn,$n,Un,Nr]);var wa="ids-columns";var jc=/^[0-9a-f]{1,16}$/,Ia=e=>it(e.reportHubId)&&(e.businessDate===null||Pr(e.businessDate)),_a=e=>typeof e=="string"&&jc.test(e),Ah=Object.freeze({kind:"absent"}),Eh=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+(?=.)/,"")},xa=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Wc=(e,t,r,n)=>xa(e,t,r,n)<0,Vn=(e,t)=>xa(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Ca=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},Ma=(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:wa,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 ka=(e,t,r=console)=>{let n=o=>typeof o=="string"?[`${t} ${o}`]:[t,o];return{debug:(o,...a)=>{e<=0&&r.debug(...n(o),...a)},info:(o,...a)=>{e<=1&&r.info(...n(o),...a)},warn:(o,...a)=>{e<=2&&r.warn(...n(o),...a)},error:(o,...a)=>{e<=3&&r.error(...n(o),...a)}}},xh=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection","SessionGate"]),Pa=e=>`[DailyReport${e}]`,De=(e,t,r)=>e===void 0?ka(t,Pa(r)):ka(0,Pa(r),e);import{z as Ot}from"zod/v3";var yr=e=>({reportHubId:e,outcome:"not_found"}),vh=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 va=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},La=e=>zn(Yn,e,0,e.length),Jc=String.fromCodePoint(3),Qc=String.fromCodePoint(2),Xc=String.fromCodePoint(1),Hr=e=>La(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Jc)).join(Qc)).join(Xc));var Na=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 $h=2*(1+Gn);import{z as qh}from"zod/v3";var Oa=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 Kh=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},Ha=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 Fa=e=>e.trim().length===0;var Qn=e=>e!==null&&vr.test(e)?e:null,Xn=e=>Na(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},$a=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},Ua=(e,t)=>{let r={authors:e.getAll(be.searchAuthor),sourceTypes:e.getAll(be.searchSourceType),customers:e.getAll(be.searchCustomer)},n=Ha(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:$a(r.authors),customers:$a(r.customers)}}},Ba=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var qa=Object.freeze({status:400,error:"Invalid form"}),ja=e=>({status:413,error:"Form too large",measuredBy:e}),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:ja("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?ja("counted"):qa}}let l=Ba(i);return l===null?{refusal:qa}:{fields:l}},Ya=(e,t)=>{let r=e.get(t);if(r===null)return{error:`${t} required`};let n=Wn(r);return n===null?{error:`Invalid ${t}`}:{value:n}},au=(e,t)=>{let r=Ya(e,we.isStarred);return"error"in r?r:{command:{...t,intent:"toggleStar",value:r.value}}},iu=(e,t)=>{let r=Ya(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`}},za=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(za,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"}:za[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Ga=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",Wa=["declared","counted"],Ka=e=>{let t=Me({windowMs:cu,tallies:Wa,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Wa.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(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"]}}),Ja=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})}),Qa=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&&Qa(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")}"`,Xa=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},Za=(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",ei=["api","action","sse","attachment"],ti=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...st}}),gu=()=>ti(403,lo),Ur=()=>ti(404,Su),fr=Object.freeze({...Ru,frameworkDataRefusal:()=>null,crossSiteRejection:gu}),ri=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)},ni=e=>{let t=Me({windowMs:bu,tallies:ei,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${ei.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 oi=(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})},ai=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,ii=e=>encodeURIComponent(e.replace(xu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),si=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"},li={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Vr=e=>typeof e=="string"&&Object.hasOwn(li,e),qr=e=>li[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,ci=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 ${ci} ms`)),a()},ci)};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})},ui=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="${si(E.fileName)}"; filename*=UTF-8''${ii(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&&ai.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}),Uf=qe.queueWaitMs+qe.readMs+qe.renderMs+qe.transferMarginMs;import{Buffer as Ou}from"buffer";var mi=new Set([194,198,202,206]),Hu=new Set([192,193,194,195]),yi=216,Fu=217,hi=218,$u=4,Uu=64,Bu=2,di=8,pi=28,It=12,po=8,Vu=20,fi=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},Ri=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Si=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),gi=e=>(e.stepsLeft-=1,e.stepsLeft>=0),bi=e=>e[0]===255&&e[1]===yi,Di=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!gi(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===yi)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(!gi(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}},Ti=(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}},Ai=(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])},Ei=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:mi.has(e.marker)||t<e.components.length}),mo=e=>{if(!bi(e))return null;let t=Si(e.byteLength),r=null;for(let n=2;;){if(Di(e,n,t)!=="segment")return null;if(Ri(t.marker)){if(r!==null||(r=Ti(e,t),r===null))return null}else if(t.marker===hi){if(r===null)return null;let o=Ai(e,t);return o===null?null:Ei(r,o.length)}n=t.end}},wi=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*di)),i=Math.ceil(e.height*o/(r*di));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},Ii=e=>e.multiScan?wi(e).reduce((r,n)=>r+n,0)*Uu*Bu:0,Wu=896,_i=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!bi(e))return null;let n=Ou.from(e.buffer,e.byteOffset,e.byteLength),o=Si(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let h=Di(e,u,o);if(h===null)return null;if(h==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,Ri(o.marker)){if(a!==null||!Hu.has(o.marker)||(a=Ti(e,o),a===null))return null;let m=wi(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*(mi.has(a.marker)?Wu:1)}else if(o.marker===hi){if(a===null||d===s)return null;let m=Ai(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=Ei(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}}},xi=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<fi?null:{width:Kt(e,24,3)+1,height:Kt(e,27,3)+1}:null},Ci=e=>{if(xi(e)===null||e.byteLength<=pi)return null;switch(e[pi]){case 0:return!1;case 1:return!0;default:return null}},Mi=(e,t)=>{if(ct(e,It,"VP8 "))return"lossy";if(ct(e,It,"VP8L"))return"lossless";if(!ct(e,It,"VP8X")||e.byteLength<fi)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},ki={png:xi,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},Pi=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:Xa([t])}},vi=(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=ki[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Li=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"},Ni=(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=vi(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)}}},Oi=()=>{},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)}),Hi=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(Oi,Oi);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=Ni(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=Ni(J.value,m.box);return"entry"in G?x(G.entry):G.failure}finally{f===null?p():f.then(p,p)}}};var Fi=()=>{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 Bi=10,ad=1/Bi,$i=1-ad,id=1024,sd=64,ld=8,Ui="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"}},Vi=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*Bi),h=lt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:sd,maxPerOwner:ld,maxWaitMs:qe.queueWaitMs}}),m=Li({maxBytes:l.cacheBytes,maxEntries:id}),y=Fi(),R=Hi({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":Ui,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)?Pi({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":Ui,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,$i),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,$i),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}),qi=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}),ji=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:oi(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:ui({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Vi({...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)})},Wi=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 zi=8,Ad=8*zi,Ed=128,wd=2,Gi=wd*Ed,Id=4*Gi,_d=6e4,xd=6e4,Cd="Too many reads",Yi=Object.freeze(Object.keys(Ft).filter(e=>Ft[e].admission.includes("miss-gate"))),Ki=e=>{let t=lt({limit:Ad,maxHeldPerOwner:zi,queue:{max:Id,maxPerOwner:Gi,maxWaitMs:_d}}),r=Me({windowMs:xd,tallies:Yi,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Yi.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 Ji=e=>{let t=e.get(be.cursorReportHubId),r=e.get(be.cursorBusinessDate),n=e.get(be.cursorSnapshot),o=_a(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(!Ia(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,Qi=()=>{},Ld=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Xi=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 Qi;if(a.aborted){if(t.canAcquire(n))return Qi}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,ns=4e3,Nd="stream interrupted by server error",Od="Too many streams",Hd=15e3,os=Symbol("ids-stream-heartbeat"),Zi=()=>{},es=e=>e.return(void 0).then(Zi,Zi),Fd=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(os),Hd)}),stop:()=>clearTimeout(e)}};async function*ts(e,t,r,n){let o=t?Ma(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:ns),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 as=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},rs=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await es(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===os){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
2
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
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(),
|
|
5
|
-
`,bo=4e3,ep=1,
|
|
4
|
+
`)),d.close()}catch{}}},cancel(){l=!0,o(),es(t)}});return new Response(c,{status:200,headers:as(e)})},is=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 rs(d,ts(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*ts(g.items,null,C?ns:Kr,{snapshot:g.snapshot,streamAnchor:g.streamAnchor})})();return rs(d,E,u,r,h)};return async(l,s,c,d,u,h)=>{let m=Ji(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:as(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",ss=e=>e.trim().toLowerCase();var Ud="",Bd=64,Vd=e=>e.toLowerCase(),ls=e=>{let t=new Set;if(!Array.isArray(e))return t;for(let r of e){if(typeof r!="string")continue;let n=ss(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=ls(r?t.read:t);if(!r||t.comment===void 0)return new gr(n,n);let o=new Set;for(let a of ls(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"]),us=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=cs(e.visible),r=cs(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function cs(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 ds=(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 ps}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,fs=new Set([8203,8288,65279,173]),tp=new RegExp(`[${String.fromCodePoint(...fs)}]`,"gu"),Rs=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),Ss=/(\s+)/u,rp=/^\s+$/u,np=new RegExp(Ss.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,ms=/(?=\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})`)},gs=e=>{if(!ms.test(e))return[];let t=Xr(e);if(!ms.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},bs=(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&&!bs(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(Ss)){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(Rs))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},Ds=(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}},Ts=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}}},ys=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);fs.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+=ys)r.push(Reflect.apply(String.fromCharCode,null,c.subarray(d-s,Math.min(o,d+ys)-s)))}i=l}return a?{text:r.join(""),rawIndex:n.subarray(0,o)}:{text:e,rawIndex:null}}var As=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(Rs)){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 Es=(e,t)=>{let r={units:0};return wo(r,Sp(e,t,r))};function*hs(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,bs(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*hs(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*hs(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 ws=(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
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&>(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)}
|
|
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 ps(),e.update("\0"),e.update(Do(bp(t)));return await ps(),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,Is=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=[...Is(e).map(n=>({text:n,tier:Ht.word})),...t.flatMap(n=>Is(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,gs(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 mS=Object.freeze({sourceTypes:null,authors:null,customers:null}),Pp=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,_s=(e,t,r)=>{if(Fa(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 xs=6e4,vp=1,Lp=3200,Cs=2e3,Np=Object.freeze({search:Lp,reports:Cs,"search-marks":Cs,"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:xs,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:xs,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}},Ms=new WeakMap,ks=(e,t,r)=>{let n=Ms.get(e);n===void 0&&(n=new Map,Ms.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})},Ps=(e,t,r)=>{let{parsed:n}=e;if(n.type!=="report-create"&&n.type!=="report-update"&&n.type!=="report-publish")return ks(e,"every-viewer",()=>JSON.stringify(Hp(n)));let o=n.actorRawUserId===t;return ks(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}:`,vs=(e,t)=>xo(Co(e),t),Xt=e=>`daily-report:date:${e}:user:`,Zt=(e,t)=>`${Xt(e)}${t}:`,Ls=(e,t,r)=>xo(Zt(e,t),r),Ge=e=>`daily-report:detail:${e}:user:`,Mo=(e,t)=>`${Ge(e)}${t}:`,Ns=(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",Os=["initial","refresh"],Hs=Object.freeze({ok:!1}),jp=e=>e===null?"null":Array.isArray(e)?"array":typeof e,Fs=(e,t)=>{let r=Me({windowMs:qp,tallies:Os,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{t.error(`visibility_unavailable_suppressed count=${o} since=${a} cause=${n} reasons=${Os.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)),Hs}let i=us(a);return i===null?(r.record("port_contract",o,()=>t.error(`visibility unavailable cause=port_contract reason=${o} answer=${jp(a)}`)),Hs):{ok:!0,scope:i}}},$s=(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 Bs=Object.freeze({...fr,route:"sse",frameworkDataRefusal:Ur}),Us=864e5,Jp={baseMs:2e3,jitterMs:8e3},Vs=6e4,ko=$r,qs=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:qs})},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:Ps(n,r.internalUserId,Zp(o,r.commentableSet))})},js=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:s}=e,c=async(d,u)=>{let{request:h,internalUserId:m,cursor:y}=u,R=u.initialScope.visible,p=u.initialScope.commentable,f=0,D=setInterval(()=>{let _=++f;n(h,"refresh").then(q=>{if(_===f){if(!q.ok){d.close();return}R=q.scope.visible,p=q.scope.commentable}})},Vs);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&>(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:qs}),Gp(d,{intervalMs:Sa,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(Us),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:Us,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,ga);if(D!==null&&!ba(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 Ws=(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}),Js=6e4,Qs=5,im=Qs*Math.ceil(Js/500),sm=2,lm=6,cm=6e4,um=Qs*sm*lm,dm=2,pm=10,mm=2,ym=10,Ys=(e,t)=>Math.max(e,Fr)*t,Xs=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},hm=Object.freeze({etag:(e,t,r)=>Za(e,t,r,200),"no-store":(e,t,r)=>ao(t,r,200)}),fm=e=>io(e.body==="json"?hm[e.cache]:null),zs=io(null),Gs=(e,t,r,n)=>Xs(e(t,r,{error:{message:n.message}},n.status),n.headers),Ks=(e,t,r)=>Xs(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=Fs(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=Xi(D),C=Ki(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:Gs(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?Ks(z,H,P):Gs(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 Ks(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:Ys(r.searchLimits.concurrency,dm),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*pm,route:le.reports,logger:p}),q=r.searchLimits===null?null:Tr({concurrency:Ys(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]:is({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=Ua(b.searchParams,r.searchFilterSourceTypes);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:P.reason}}};let H=_s(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 zs(b,H,{error:{message:"Unauthorized"}},401);let Y=N.endpoint;if(!eo(Y))return zs(b,H,{error:{message:"Unknown endpoint"}},404);let X=Ft[Y],z=fm(X),M=Ja[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):$s(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=Ka(R),U=ft({reason:"rate_limit",limitPerWindow:im,windowMs:Js,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)=>Ws(z,{...M,setCookie:P}),Y=(z,M,k)=>Ws(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 Ga(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=js({authenticate:t,service:r,resolveViewerScope:u,redis:o,sseReader:a,streamKey:i,streamSlots:g,logger:h}),de=ji({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:u,logger:m}),Se=ni(y),Q=(b,N)=>async L=>{let P=ri(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(Bs,ne)},attachment:{loader:Q(qi,de)}}}import{chunk as Ty,MAX_IN_LIST as Ay,runWithTransactionRetry as Ey}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},Zs=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw _n(e,n,r)},el=(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])},tl=(e,t)=>{if(!vo(e))throw K("search","a plain object",e);Zs("search key",e,Rm);let{tables:r}=e;if(!vo(r))throw K("search.tables","a plain object with document and comment",r);Zs("search.tables key",r,Sm),el("search.tables.document",r.document,gm),el("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 rl=e=>{if(e.length===0)throw new Error("[daily-report] draft rule: draftLabelNames must hold at least one name (a rule without names would show every draft to every viewer)");return 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 (${rl(t)}))`},nl=(e,t)=>{let{hubLabel:r,label:n}=e;return Ct`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${rl(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}]`),ol=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`, `),al=(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=>ol(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}))`},il=(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},sl=(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=>il(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`},ll=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=B.join(t.sets.map((s,c)=>B`(CASE WHEN ${il(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 `)}`},cl=(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}`},ul=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(s=>({[n.hubId.name]:s.hubId,[n.searchText.name]:s.searchText,[n.sourceDigest.name]:s.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:s.authorName,[n.customerName.name]:s.customerName}))),i=JSON.stringify(t.flatMap(s=>s.comments.map(c=>({[o.hubId.name]:s.hubId,[o.ordinal.name]:c.ordinal,[o.authorUserId.name]:c.authorUserId,[o.commentText.name]:c.commentText})))),l=JSON.stringify(t.map(s=>s.hubId));return 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));`},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)}
|
|
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));`},dl=(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)})`,pl=(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 ml=e=>({search:async(t,r)=>Fe(r.scope.visible)?[]:xt(await t.execute(sl(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(ll(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames,r.ids))),o=2**r.plan.sets.length-1,a=new Map;for(let i of n){let l=i[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(cl(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 hl}from"drizzle-orm";import{createHash as wm}from"crypto";var Im=Object.freeze({authorName:"author",customerName:"customer"}),No=e=>e===null?null:Jn(e),yl=(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:Ts(r),comments:n,sourceDigest:_m(e),forcedCuts:t,authorName:yl(e.hubId,"authorName",e.filterValues.authorName),customerName:yl(e.hubId,"customerName",e.filterValues.customerName)}};var fl=e=>{let t=async(s,c)=>{let d=[];for(let u of ln(c,cn))for(let h of xt(await s.execute(al(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(ul(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(dl(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(pl(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(hl`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(hl`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),Rl=Math.floor(ut/Re.sweep),gl=Math.floor(ut/Re.scan),Mr=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),bl=(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}}},rb=Object.freeze({fits:()=>!0,charge:()=>{}}),Dl=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(gl-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)},Sl=(e,t,r)=>{let n=pn(e,t);return e.pieces[n>=0?n:pn(e,r==="start"?t-1:t+1)]},Tl=(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.start[t-n.plainStart]},Al=(e,t)=>{let r=pn(e,t);if(r<0)return Tl(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=Sl(e,n.closedStart,"start"),y=Sl(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+Tl(e,n.closedStart)),p=t(e.offset+Al(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(gl,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(As(e),Re.strip,n),i=[],l=[];yield*$o(Es(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(ws(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(Ds(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+=Rl){let s=Math.min(e+1,l+Rl),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 Dl(function*(){return(yield*qm(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var El=(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)},wl=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of va)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 Il=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(Dl(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{inJsonList as Km}from"@aiquants/mssql/drizzle";import{and as Jm,asc as Cl,eq as yn,isNull as Qm}from"drizzle-orm";import{and as _l,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}`},xl=e=>{let{db:t,tables:r,encodeUserId:n,settings:o,draftVisibilityTables:a}=e,{hub:i,label:l}=r,{externalSources:s,draftLabelNames:c,canonicalDraftLabelName:d}=o,u=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(_l(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,_l(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=>ds({authorUserId:W.userId},G.sourceType,J,w)).map(W=>({...W,userId:n(W.userId),isMine:J?W.userId===J:!1})),attachments:v.attachments}}}};var Ml=(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(Km(p.hubId,y)).orderBy(Cl(p.createdAt),Cl(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(Jm(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 kl,isNull as Zm}from"drizzle-orm";var er=async(e,t,r,n)=>{if((await e.update(t).set({deletedAt:null}).output().where(Xm(kl(t.id,r),Zm(t.deletedAt),n===null?void 0:kl(t.userId,n)))).length===0)throw new Error("Not Found")};var Pl=(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 Ll,eq as Vt,isNull as ey}from"drizzle-orm";var vl=e=>e===je;var Nl=e=>e===""?null:e,Ol=(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(!vl(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:Nl(W.title),updatedAt:new Date,updatedBy:String(U)}),W.content!==void 0&&await _(b,I,{body:Nl(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(Ll(Vt(S.hubId,I),nl(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(Ll(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{inJsonList as Fl}from"@aiquants/mssql/drizzle";import{and as tr,asc as $l,desc as kr,eq as Pe,inArray as ay,isNull as fn,sql as iy}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)},Hl=(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 Hl(t,e.interviewers,ny),Hl(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([]),sy=6e4,jo=(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},Wo=e=>{let t=async()=>{await new Promise(r=>setImmediate(r)),e.throwIfAborted()};return{sliceMs:Mr.sliceMs,now:se,pause:t}},qo=e=>{try{return{ok:!0,value:e()}}catch(t){return{ok:!1,cause:t}}},ly=e=>qo(()=>{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 (${Oa(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=vs(Te,Qr(M)),[ge]=await p.getOrFetch({cacheKey:he,fetcher:async()=>{let We=await d(),nt=await G(M,Te);if(!Ca(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(Fl(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(Fl(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=>qo(()=>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?qo(()=>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:sy,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"?ly(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,ay(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=Ls(he,Te,Qr(M));return p.getOrFetch({cacheKey:ge,fetcher:()=>ne(M,Te,Pe(T.businessDate,iy`${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=Ns(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=jo("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:Wo(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 cy="v5",uy=/^(?!:)[^\s\p{Cc}]+(?<!:)$/u,Yo=e=>{if(typeof e!="string"||!uy.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:${cy}`,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}),dy=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)},py=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])},my=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)])},yy=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=py(e.draftLabelNames);if(Yr(e),Object.hasOwn(e,"streamKey"))throw Ye("redisKeyPrefix","given in place of the removed key streamKey");let n=Wi(e.attachments),o=dy(e.tables.hub.title);go(e.tables.hub.sourceType),yy(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=Yo(e.redisKeyPrefix===void 0?Rn.redisKeyPrefix:e.redisKeyPrefix);return Object.freeze({externalSources:t,sourceTypes:my(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 fy,eq as Ry,sql as ye}from"drizzle-orm";var Sn=["hubId","userId","isRead","isStarred","createdAt","createdBy","updatedAt","updatedBy","readContentDigest"],Sy={isRead:{statusType:"read",callerName:"setReadStatus"},isStarred:{statusType:"star",callerName:"setStarStatus"}},$e=e=>ye`${ye.identifier(e.name)}`,gy=(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
12
|
WHEN MATCHED THEN UPDATE SET t.${l} = ${o}${p}, ${u(e.updatedAt,a)}, ${u(e.updatedBy,i)}
|
|
13
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};
|
|
14
|
+
OUTPUT ${R};`},jl=(e,t)=>(typeof e=="number"||typeof e=="string")&&String(e)===String(t),Wl=e=>e instanceof Date||typeof e=="string",by=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(", ")},Dy=(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 ${by(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(fy(Ry(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=Dy(await n.execute(gy(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}=Sy[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 wy=Object.freeze([]),zo=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},Dn=(e,t)=>e.get(t)??wy,zl=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(en);function Go(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=>Ey(me=>t.transaction(Z=>me(()=>te(Z))),e.transactionRetry),g=e.search===void 0?null:tl(e.search,R.map(te=>te.sourceType)),C={hub:c,hubLabel:m,label:h},T=g===null?null:ml({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=fl({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}=xl(q),{getAttachmentsByHubIds:b,getAttachmentForUser:N,markAttachmentMissing:L,markAttachmentPresent:P}=Ml(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}=Pl(q,{isDraftReport:I,assertHubMutable:He,incrementRedisEpoch:w}),{createDailyReport:nt,updateDailyReport:re,publishDailyReport:Le,deleteDailyReport:pt}=Ol(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)zo(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 Ty(me,Ay)){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)zo(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)zo(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}),Jo=y.sourceTypes,hc=async(te,me)=>{if(T===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let Z=Jo.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=jo("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=Wo(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:wl(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 Qo=Pt===null?null:Pt.get(Be),Xo=Qo===void 0?0:Qo;return{reportHubId:Be,matchedSets:Xo,alternatives:El(Z,Xo).flatMap(gc=>gc.alternatives),fields:Sc}}),Je=await Il(rr,Mr,At.pause,bl(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:Jo,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 Iy=(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 _y}from"drizzle-orm";import{bigint as xe,bit as Kl,char as xy,date as Cy,datetime2 as ve,foreignKey as rt,index as Mt,int as My,mssqlSchema as ky,nvarchar as ue,primaryKey as qt,uniqueIndex as Py}from"drizzle-orm/mssql-core";function vy(e,t){let r=ky(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(_y`TRY_CAST(source_id AS BIGINT)`),businessDate:Cy("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:My("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:xy("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]}),Py(`${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 Ko,binary as Jl,datetime2 as Ly,int as Ny,mssqlSchema as Oy,nvarchar as Tn,primaryKey as Ql,varchar as Hy}from"drizzle-orm/mssql-core";function Fy(e){let t=Oy(e),r=t.table("DailyReportSearchDocument",{hubId:Ko("hub_id",{mode:"number"}).notNull(),searchText:Tn("search_text",{length:"max"}).notNull(),sourceDigest:Jl("source_digest",{length:32}).notNull(),normalizerVersion:Hy("normalizer_version",{length:64}).notNull(),indexedAt:Ly("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:Ko("hub_id",{mode:"number"}).notNull(),ordinal:Ny("ordinal").notNull(),authorUserId:Ko("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 $y=5e7,lc=2e8,Uy=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))}),By=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",Vy=1,qy={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},jy=[/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:Ii(e)}),dc=(e,t)=>{switch(t){case"jpeg":{let r=mo(e);return r===null?null:uc(r)}case"png":{let r=Ci(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Mi(e,An.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},pc=(e,t)=>{let r=By.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},Wy=(e,t,r)=>{let n=dc(e,t);return n===null?null:pc(n,r)},Yy=e=>e!==null&&e<=lc,zy=(e,t)=>{if(t!=="jpeg")return dc(e,t);let r=_i(e,An);return r===null||r.blockVisits>An.maxBlockVisits?null:uc(r.header)},Gy=e=>{let t=e instanceof Error?e.message:"";return jy.some(r=>r.test(t))?"failed":"unsupported"},Ky=e=>{e.cache(!1),e.concurrency(Uy),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(qy)});let t=async(n,o,a,i,l)=>{let s=zy(n,o);if(s===null)return sc;try{let c=e(n,{limitInputPixels:$y,animated:!1});if(!Yy(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:Gy(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${Vy}`,render:r}};var mc=6e4,Jy=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 mT(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=Go({...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,Vs 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,Yo as buildDailyReportRedisKeys,Po as createDailyReportHandlers,mT as createDailyReportServer,Go as createDailyReportService,Jy as createDailyReportVisibilityCache,Cn as createEpochStore,Ky as createSharpThumbnailRenderer,Bn as dailyReportSseStreamMessageSchema,vy as defineDailyReportSchema,Fy as defineDailyReportSearchSchema,zt as encodeIdsStreamRows,gt as isStreamIdLte,Qn as parseClientTempId,Wy as predictSharpThumbnailWorkingSetBytes,Ar as readDailyReportSseStreamEntry,Iy as transformJsonArray};
|
|
15
15
|
/* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */
|