@aiquants/daily-report 0.38.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -1,12 +1,12 @@
1
- var Wn=e=>{throw TypeError(e)};var zn=(e,t,r)=>t.has(e)||Wn("Cannot "+r);var Ot=(e,t,r)=>(zn(e,t,"read from private field"),r?r.call(e):t.get(e)),Br=(e,t,r)=>t.has(e)?Wn("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Vr=(e,t,r,n)=>(zn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var _s=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,le=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${_s(r)}`),At=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),Yr=(e,t,r)=>le(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ee=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw le(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},mt=(e,t,r,n)=>t===void 0?n:ee(e,t,r);var ue=()=>Math.floor(performance.now());var $e=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},qr=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{}}}),vt=(e,t)=>t?e.map(r=>structuredClone(r)):e,kt=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-ue())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let c=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:s,expireAt:ue()+a,epoch:c}),s})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&c===null)throw new $e(o.signal.aborted?"aborted":"busy");try{for(let y of r)y();let s=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:s,expireAt:ue()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),s}finally{c?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new $e("aborted");return this.buckets.delete(r),vt(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ue())if(t.epochKey){let c=await this.epochStore.getEpoch(t.epochKey);if(c===null||i.epoch===c)return this.maybeRefreshAhead(t),vt(i.records,o);this.buckets.delete(r)}else return this.maybeRefreshAhead(t),vt(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return vt(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new $e("aborted");return vt(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 $e&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=ee("defaultTtlMs",t.defaultTtlMs,1),this.maxBuckets=ee("maxBuckets",t.maxBuckets,1),this.lastSweepAt=ue()}writeBucket(t,r){this.buckets.delete(t),this.buckets.set(t,r);let n=ue();n-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(n);for(let o of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets)break;this.buckets.delete(o)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.buckets.delete(r)}};var Gn="ids-stream";var tr=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+(?=.)/,"")},rr=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,Kn=e=>{for(let t=1;t<e.length;t++)if(rr(e[t-1],e[t])>0)return!1;return!0},Jn=(e,t)=>{let r=e.findIndex(n=>rr({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var ne=Object.freeze({businessDate:"business-date",idsStream:Gn,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),he=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 ws=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Qn=e=>e<10?`0${e}`:`${e}`,xs=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Qn(e.getMonth()+1),n=Qn(e.getDate());return`${t}-${r}-${n}`},Tt=e=>{let t=ws.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let c=new Date(0);return c.setUTCFullYear(a,i-1,l),c.getUTCFullYear()!==a||c.getUTCMonth()!==i-1||c.getUTCDate()!==l?null:`${r}-${n}-${o}`},nr=e=>Tt(e)===e;var ve=e=>e==null?null:e instanceof Date?xs(e):Tt(e);var Xn=(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)}}},am=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),Zn=e=>`[DailyReport${e}]`,fe=(e,t,r)=>e===void 0?Xn(t,Zn(r)):Xn(0,Zn(r),e);var Cs="legacy-",jr=e=>`${Cs}${e}`;import{z as Ps}from"zod";var Et=e=>Number.isSafeInteger(e)&&e>0,be=Ps.number().int().positive().max(Number.MAX_SAFE_INTEGER);var Ms=/^[1-9][0-9]*$/,Ls=/^(?:0|[1-9][0-9]*)$/,Be=e=>{if(e===null||!Ms.test(e))return null;let t=Number(e);return Et(t)?t:null},Wr=e=>{if(e===null||!Ls.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},zr=e=>e==="true"?!0:e==="false"?!1:null,Ft=e=>e===null?!1:zr(e);var eo=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),Ze=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var Ns=2166136261,Os=16777619,Gr=e=>{let t=Ns;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,Os);return t>>>0},vs=String.fromCodePoint(3),ks=String.fromCodePoint(2),Fs=String.fromCodePoint(1),or=e=>Gr(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(vs)).join(ks)).join(Fs));var to=e=>e==="intersection"||e==="union",_e=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Kr=2,ar=2,pt=Object.freeze({word:0,reading:1});var Jr=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var pm=2*(1+Kr);import{z as Dm}from"zod";var ir=/^(?:[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})$/;import{z as N}from"zod";var ro=15e3,no="lastEventId",Hs=/^\d{1,15}-\d{1,15}$/,oo=e=>Hs.test(e),Us=N.object({name:N.string().nullish(),affiliation:N.string().nullish()}),$s=N.object({name:N.string().nullish(),text:N.string().nullish(),color:N.string().nullish()}),Bs=N.object({id:be,name:N.string().nullish(),color:N.string().nullish()}),ao=N.object({id:be,userId:N.string().nullish(),userName:N.string().nullish(),content:N.string().nullish(),createdAt:N.string().nullish(),isMine:N.boolean()}),Vs=N.object({id:N.string(),fileName:N.string(),fileType:N.string().nullable(),fileSize:N.number().nullable(),createdAt:N.string().nullable(),state:N.enum(["present","absent","unknown"]),hasThumbnail:N.boolean().default(!1)}),Qr=N.object({reportHubId:be,date:N.string().nullish(),createdAt:N.string().nullish(),author:N.string().nullish(),userId:N.string().nullish(),sourceType:N.string().nullish(),employeeName:N.string().nullish(),updatedBy:N.string().nullish(),updatedAt:N.string().nullish(),category:N.string().nullish(),creationCategory:N.string().nullish(),visitTimeFrom:N.string().nullish(),visitTimeTo:N.string().nullish(),customerName:N.string().nullish(),interviewers:N.array(Us),subject:N.string().nullish(),content:N.string().nullish(),externalComments:N.array($s),isRead:N.boolean(),isStarred:N.boolean(),labels:N.array(Bs),postedComments:N.array(ao),attachments:N.array(Vs).default([])}),yt=N.string().regex(ir),Ys=N.object({type:N.literal("connected")}),sr=N.object({type:N.literal("status-update"),reportHubId:be,statusType:N.enum(["star","read"]),value:N.boolean(),clientTempId:yt,recipientRawUserId:be.optional()}),Xr=N.string().optional(),Zr=N.object({type:N.literal("comment-add"),reportHubId:be,comment:ao,clientTempId:yt,recipientRawUserId:be.optional(),sourceType:Xr}),en=N.object({type:N.literal("comment-delete"),reportHubId:be,commentId:be,clientTempId:yt,recipientRawUserId:be.optional(),sourceType:Xr}),tn=N.object({type:N.literal("report-create"),reportHubId:be,report:Qr,clientTempId:yt,recipientRawUserId:be.optional()}),rn=N.object({type:N.literal("report-update"),reportHubId:be,report:Qr,clientTempId:yt,recipientRawUserId:be.optional()}),nn=N.object({type:N.literal("report-publish"),reportHubId:be,report:Qr,clientTempId:yt,recipientRawUserId:be.optional()}),on=N.object({type:N.literal("report-delete"),reportHubId:be,clientTempId:yt,sourceType:Xr}),io=N.discriminatedUnion("type",[Ys,sr,Zr,en,tn,rn,nn,on]);var ke=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var lr=Math.max(1,Math.floor(10.556701030927835));var Ve=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Fe=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(s=>[s,0]))};o.set(i,l),Ve(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,c)=>{let s=o.get(i);if(s!==void 0){s.count+=1,s.tallies[l]+=1;return}c(),a(i)}}};var et=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var wm=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),qs=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,an=e=>{let t=e.trim();return t.length===0?null:t.replace(qs,"\uFFFD")},js=e=>{let t=an(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>et.maxValueLength?"filter-value-too-long":null},Ws=e=>{if(e.length>et.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=js(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},zs=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},so=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Ws(t);if(r!==null)return r}return zs(e)>et.maxTotalValueLength?"filters-too-long":null};var lo=e=>e.trim().length===0;var sn=e=>e!==null&&ir.test(e)?e:null,ln=e=>to(e)?e:null,cn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>_e.maxDetailIds)return null;let r=[];for(let n of t){let o=Be(n);if(o===null||r.includes(o))return null;r.push(o)}return r},co=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},uo=(e,t)=>{let r={authors:e.getAll(he.searchAuthor),sourceTypes:e.getAll(he.searchSourceType),customers:e.getAll(he.searchCustomer)},n=so(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:co(r.authors),customers:co(r.customers)}}},mo=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var yo=Object.freeze({status:400,error:"Invalid form"}),ho=e=>({status:413,error:"Form too large",measuredBy:e}),Gs=(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)}}))},Ks=async e=>{let t=Wr(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:ho("declared")};let r=!1,n=e.body===null?null:Gs(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?ho("counted"):yo}}let l=mo(i);return l===null?{refusal:yo}:{fields:l}},fo=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=zr(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},So=Object.freeze({update:(e,t,r)=>{let n=e.get(ke.title),o=e.get(ke.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:fo("toggleStar",ke.isStarred),toggleRead:fo("toggleRead",ke.isRead),addComment:(e,t)=>{let r=e.get(ke.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Be(e.get(ke.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Js=e=>Object.hasOwn(So,e),Qs=(e,t)=>{let r=e.get(ke.intent),n=e.get(ke.businessDate),o=n===null?null:Tt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(ke.operationTimestamp),i=Wr(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(ke.clientTempId);if(!l)return{error:"clientTempId required"};let c=sn(l);if(c===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:c,businessDate:o,operationTimestamp:i}};let s=Be(e.get(ke.reportHubId));return s===null?{error:"Invalid reportHubId"}:r===null||!Js(r)?{error:"Invalid intent"}:So[r](e,{clientTempId:c,businessDate:o,operationTimestamp:i,reportHubId:s},t)},go=async(e,t)=>{let r=await Ks(e);if("refusal"in r)return r;let n=Qs(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Xs=6e4,Zs="form_too_large",Ro=["declared","counted"],bo=e=>{let t=Fe({windowMs:Xs,tallies:Ro,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Ro.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(Zs,r,n)}};var it=Object.freeze({[ne.businessDate]:{body:"json",admission:["refresh-bucket","cache","miss-gate"]},[ne.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[ne.report]:{body:"json",admission:["refresh-bucket","cache","miss-gate"]},[ne.search]:{body:"json",admission:["search-limiter"]},[ne.reports]:{body:"json",admission:["search-limiter"]},[ne.searchMarks]:{body:"json",admission:["search-limiter"]},[ne.searchFacets]:{body:"json",admission:["search-limiter"]}}),Do=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),un=e=>e!==void 0&&Object.hasOwn(it,e);var dn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Ao=e=>Object.hasOwn(dn,e);var el="download",tl="thumbnail",rl="1";var mn=e=>{let t=e.getAll(tl),r=e.getAll(el);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Ao(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===rl?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{createHash as nl}from"crypto";var pn=e=>`"${nl("sha256").update(e).digest("hex")}"`,To=e=>pn(JSON.stringify(e));var ze=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),yn=(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},X=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=pn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...ze});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&yn(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},tt=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...ze});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},ol=5e3/1e3,al=new Map([[503,ol]]),Ce=e=>{let t=al.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var fn="Cross-site request rejected",il="Not Found",sl=new Set(["same-origin","none"]),ll=new Set(["GET","HEAD","OPTIONS"]),Eo=["api","action","sse","attachment"],Io=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...ze}}),cl=()=>Io(403,fn),cr=()=>Io(404,il),Ht=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:cl}),_o=e=>new URL(e.url).pathname.endsWith(".data"),ul=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},wo=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(ll.has(e.method)||ul(e)):sl.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},dl=6e4,ml="refusals",pl=32,yl=/^[a-z-]+$/,hn=e=>{if(e===null)return"-";let t=e.slice(0,pl);return yl.test(t)&&t===e?e:JSON.stringify(t)},xo=e=>{let t=Fe({windowMs:dl,tallies:Eo,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${Eo.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${hn(a.get("Sec-Fetch-Site"))} mode=${hn(a.get("Sec-Fetch-Mode"))} dest=${hn(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(ml,r,o)}};var Co=(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 hl="same-origin",fl="SAMEORIGIN",It=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":hl,"X-Frame-Options":fl}),ur=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...It});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Po=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Rl=/^[\x20-\x7E]+$/,Sl=/^[\w.+-]+\/[\w.+-]+/,Rn=e=>e&&Rl.test(e)&&Sl.test(e)?e:null,gl=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Mo=e=>encodeURIComponent(e.replace(gl,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Lo=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),dr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},No={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},mr=e=>typeof e=="string"&&Object.hasOwn(No,e),pr=e=>No[e],rt="Attachment request failed";var Ge=e=>{let t=ee("limit",e.limit,1),r=ee("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ee("queue.max",e.queue.max,0),maxPerOwner:ee("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ee("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,c=(g,I)=>g.get(I)??0,s=(g,I,v)=>{let B=c(g,I)+v;B<=0?g.delete(I):g.set(I,B)},y=g=>c(l,g)<r,m=g=>o<t&&y(g),S=g=>(o+=1,s(l,g,1),b(g)),f=()=>{let g=-1,I=r;for(let[v,B]of a.entries()){let x=c(l,B.owner);if(x<I&&(g=v,I=x,x===0))break}return g},R=()=>{for(;o<t;){let g=f();if(g<0)return;let[I]=a.splice(g,1);s(i,I.owner,-1),I.grant(S(I.owner))}},b=g=>{let I=!1;return()=>{I||(I=!0,o-=1,s(l,g,-1),R())}};return{canAcquire:m,acquire:(g,I)=>{if(I.aborted)return Promise.resolve(null);if(m(g))return Promise.resolve(S(g));if(n===null||a.length>=n.max||c(i,g)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:v}=n,B=x=>{let T=()=>{let ce=a.indexOf(k);ce<0||(a.splice(ce,1),s(i,g,-1),F(),x(null))},Y=Ve(T,v),F=()=>{clearTimeout(Y),I.removeEventListener("abort",T)},k={owner:g,grant:ce=>{F(),x(ce)}};a.push(k),s(i,g,1),I.addEventListener("abort",T,{once:!0})};return new Promise(B)}}};var bl=1024,Sn="Too many requests",Dl=(e,t)=>{ee("limitPerWindow",e,1),ee("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let c=l??{tokens:e,lastRefillMs:i};n(c,i),r.set(a,c);for(let s of r.keys()){if(r.size<=bl)break;r.delete(s)}return c};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let c=r.get(a);c&&(n(c,i),c.tokens=Math.min(e,c.tokens+l))}}},nt=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ee("windowMs",r,1e3)%1e3!==0)throw le("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Dl(e.limitPerWindow,r),i=Object.freeze({status:429,message:Sn,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Fe({windowMs:r,tallies:[t],writeSuppressed:(c,{count:s,since:y})=>{n.warn(`${t}_suppressed count=${s} since=${y} ${o(c)}`)}});return{spend:(c,s)=>a.consume(c,ue())?null:(l.record(c,t,()=>n.warn(`429 ${s} reason=${t}`)),i),refund:(c,s)=>{a.refund(c,ue(),s)}}};var Tl=256*1024,Oo=6e4,El=e=>Math.ceil(e/2),Il=new Uint8Array(new ArrayBuffer(0)),_l=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Il,t()},i=l=>{clearTimeout(o),o=Ve(()=>{l.error(new Error(`attachment body idle for ${Oo} ms`)),a()},Oo)};return new ReadableStream({start(l){i(l)},pull(l){let c=Math.min(n+Tl,r.byteLength);if(c>n&&l.enqueue(r.slice(n,c)),n=c,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},vo=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=nt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:c=>`viewer=${c}`}),l=Ge({limit:e.concurrency,maxHeldPerOwner:El(e.concurrency),queue:null});return async c=>{let{request:s,delivery:y,attachmentId:m,internalUserId:S,readAttachment:f,cookie:R,fail:b}=c,g=e.maxBytes,I=i.spend(S,`attachment=${m} viewer=${S}`);if(I)return b(I.status,I.message,I.headers);let v=await n(s),B=await t.getAttachmentForUser(v,m,S);if(!B)return o.warn(`404 attachment=${m} viewer=${S} reason=not_visible`),b(404,"Attachment not found");if(B.fileSize!=null&&B.fileSize>g)return o.warn(`413 attachment=${m} viewer=${S} reason=db_size`),b(413,"Attachment too large");let x=Rn(B.fileType),T=`filename="${Lo(B.fileName)}"; filename*=UTF-8''${Mo(B.fileName)}`,Y=await l.acquire(S,s.signal);if(!Y)return s.signal.aborted?(o.info(`503 attachment=${m} viewer=${S} reason=aborted`),b(503,"Attachment request aborted")):(o.warn(`503 attachment=${m} viewer=${S} reason=concurrency`),b(503,"Too many concurrent downloads",Ce(503)));let F=!1;try{let k=await f(B.filePath,{maxBytes:g,head:s.method==="HEAD",principal:r(S),signal:s.signal});if(s.signal.aborted)return o.info(`503 attachment=${m} viewer=${S} reason=aborted`),b(503,"Attachment request aborted");if(!k.ok){if(!mr(k.reason))return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=failure_reason`),b(500,rt);let me=pr(k.reason);return k.reason==="not_found"&&a(m,!1),o.warn(`${me} attachment=${m} viewer=${S} reason=${k.reason} code=${k.code??"-"}`),b(me,dr[me],Ce(me))}if(k.bytes.byteLength>g)return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=over_max_bytes`),b(500,rt);let ce=s.method==="HEAD";if(ce&&k.size!==void 0&&k.size>g)return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=over_max_bytes`),b(500,rt);if(!ce&&k.size!==void 0&&k.size!==k.bytes.byteLength)return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=size_mismatch`),b(500,rt);let de=x??Rn(k.contentType),Re=de!==null&&Po.has(de),z=Re?de:"application/octet-stream",te=Re&&y.kind!=="download"?"inline":"attachment",Z=ce?k.size:k.bytes.byteLength,se=new Headers({"Content-Type":z,"Content-Disposition":`${te}; ${T}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...It});return Z!==void 0&&se.set("Content-Length",String(Z)),R&&se.append("Set-Cookie",R),a(m,!0),o.info(`200 attachment=${m} viewer=${S} type=${z} disposition=${te} bytes=${Z??"-"}`),ce?new Response(null,{status:200,headers:se}):(F=!0,new Response(_l(k.bytes,Y),{status:200,headers:se}))}finally{F||Y()}}};var Pe=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),hp=Pe.queueWaitMs+Pe.readMs+Pe.renderMs+Pe.transferMarginMs;import{Buffer as wl}from"buffer";var Ho=new Set([194,198,202,206]),xl=new Set([192,193,194,195]),Uo=216,Cl=217,$o=218,Pl=4,Ml=64,Ll=2,ko=8,Fo=28,st=12,gn=8,Nl=20,Bo=st+gn+10,Ol=2,ot=(e,t)=>e[t]<<8|e[t+1],_t=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},Ke=(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},Vo=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Yo=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),qo=e=>(e.stepsLeft-=1,e.stepsLeft>=0),jo=e=>e[0]===255&&e[1]===Uo,Wo=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!qo(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===Cl)return"eoi";if(o===0||o===Uo)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=ot(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")}},vl=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!qo(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}},zo=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=ot(e,r+1),a=ot(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let c=0;c<i;c+=1){let s=e[r+7+3*c],y=s>>4,m=s&15;if(y<1||y>4||m<1||m>4)return null;l.push({id:e[r+6+3*c],horizontal:y,vertical:m})}return{marker:t,width:a,height:o,components:l}},Go=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>Pl||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},Ko=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:Ho.has(e.marker)||t<e.components.length}),bn=e=>{if(!jo(e))return null;let t=Yo(e.byteLength),r=null;for(let n=2;;){if(Wo(e,n,t)!=="segment")return null;if(Vo(t.marker)){if(r!==null||(r=zo(e,t),r===null))return null}else if(t.marker===$o){if(r===null)return null;let o=Go(e,t);return o===null?null:Ko(r,o.length)}n=t.end}},Jo=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*ko)),i=Math.ceil(e.height*o/(r*ko));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},Qo=e=>e.multiScan?Jo(e).reduce((r,n)=>r+n,0)*Ml*Ll:0,kl=896,Xo=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!jo(e))return null;let n=wl.from(e.buffer,e.byteOffset,e.byteLength),o=Yo(r),a=null,i=null,l=new Map,c=0,s=0,y=0;for(let m=2;;){let S=Wo(e,m,o);if(S===null)return null;if(S==="eoi")return i===null?null:{header:i,blockVisits:s};if(m=o.end,Vo(o.marker)){if(a!==null||!xl.has(o.marker)||(a=zo(e,o),a===null))return null;let f=Jo(a);l=new Map;for(let[R,b]of a.components.entries()){let g=l.get(b.id);l.set(b.id,g===void 0?f[R]:Math.max(g,f[R]))}c=a.components.length*(Ho.has(a.marker)?kl:1)}else if(o.marker===$o){if(a===null||y===c)return null;let f=Go(e,o);if(f===null)return null;for(let b of f){let g=l.get(b);if(g===void 0)return null;s+=g}if(y+=1,i===null&&(i=Ko(a,f.length)),s>t||!i.multiScan)return{header:i,blockVisits:s};let R=vl(n,o.end,o);if(R===null)return null;m=R}}},Zo=e=>{if(e.byteLength<24||ot(e,8)!==0||ot(e,10)!==13||!Ke(e,12,"IHDR"))return null;let t=ot(e,16)*65536+ot(e,18),r=ot(e,20)*65536+ot(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Fl=e=>{if(Ke(e,st,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=_t(e,26,2)&16383,r=_t(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Ke(e,st,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=_t(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Ke(e,st,"VP8X")?e.byteLength<Bo?null:{width:_t(e,24,3)+1,height:_t(e,27,3)+1}:null},ea=e=>{if(Zo(e)===null||e.byteLength<=Fo)return null;switch(e[Fo]){case 0:return!1;case 1:return!0;default:return null}},ta=(e,t)=>{if(Ke(e,st,"VP8 "))return"lossy";if(Ke(e,st,"VP8L"))return"lossless";if(!Ke(e,st,"VP8X")||e.byteLength<Bo)return null;if((e[Nl]&Ol)!==0)return"animated";let r=!1,n=t;for(let o=st;o+gn<=e.byteLength;){if(n-=1,n<0)return null;if(Ke(e,o,"VP8L"))return"lossless";if(Ke(e,o,"VP8 "))return r?"lossy-alpha":"lossy";Ke(e,o,"ALPH")&&(r=!0);let a=_t(e,o+4,4);o+=gn+a+a%2}return null},ra={png:Zo,jpeg:bn,webp:Fl};var Dn=Object.freeze(["image/webp","image/jpeg","image/png"]),An=1024*1024;var Hl=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Ul={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},$l=new Set(Dn),Bl=e=>typeof e=="string"&&$l.has(e),Vl=256,yr=(e,t)=>e.fileType===null||!Hl.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Yl=[137,80,78,71,13,10,26,10],ql=[255,216,255],jl=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Wl=[82,73,70,70],zl=[87,69,66,80],Ut=(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},Tn=e=>{if(Ut(e,Yl,0))return"png";if(Ut(e,ql,0))return"jpeg";for(let t of jl)if(Ut(e,t,0))return"gif";return Ut(e,Wl,0)&&Ut(e,zl,8)?"webp":null},na=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:To([t])}},oa=(e,t)=>{if(!Bl(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>An)return"too_large";let r=Ul[e.contentType];if(Tn(e.bytes)!==r)return"signature";let n=ra[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},aa=e=>{ee("maxBytes",e.maxBytes,0),ee("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)+Vl;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let c of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(c)}}}};var En=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ue(),l=new AbortController,c=!1,s,y,m=()=>{a(ue()-i)},S=x=>{s=Ve(()=>{c=!0,x({timedOut:!0}),y=Ve(m,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},f=new Promise(S),R=AbortSignal.any([r,l.signal]),b=x=>{x(n(R))},g=new Promise(b),I=x=>(clearTimeout(s),clearTimeout(y),c&&o(ue()-i,x.kind==="error"?{error:x.error}:null),x),v=g.then(x=>I({kind:"value",value:x}),x=>I({kind:"error",error:x}));return{outcome:Promise.race([g.then(x=>({timedOut:!1,value:x})),f]),settled:v}};var lt={404:"Attachment not found",500:rt,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},ia=(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=oa(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Gl=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ve(r,Pe.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},sa=()=>{},Kl=(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)}),la=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,c=(f,R)=>{let b=R.then(sa,sa);l.set(f,b);let g=()=>{l.get(f)===b&&l.delete(f)};b.then(g)},s=async(f,R)=>{let b=l.get(f.key);if(b===void 0)return t.acquire(f.owner,R);let g=Gl(R);try{if(await Kl(b,g.signal),g.signal.aborted)return null;let I=r.get(f.key);return I!==void 0?{...I,identity:"verified"}:await t.acquire(f.owner,g.signal)}finally{g.end()}},y=(f,R)=>{if(f.fileSize===null)return R.kind==="exact"?"verified":"unrecorded";if(R.kind==="exact"?R.bytes===f.fileSize:f.fileSize>R.maxBytes)return"verified";let g=R.kind==="exact"?String(R.bytes):`>${R.maxBytes}`;return i.warn(`size_mismatch expected=${f.fileSize} got=${g} attachment=${f.attachmentId} viewer=${f.owner} variant=thumbnail`),"unverified"},m=(f,R)=>(b,g)=>{let I=g===null?"":` message=${g.error instanceof Error?g.error.message:"unknown"}`;i.warn(`${f}_overrun ms=${b} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail${I}`)},S=(f,R)=>b=>{i.warn(`${f}_stuck ms=${b} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail`)};return async(f,R)=>{let b=await s(f,R);if(b===null)return{kind:"failure",status:503,reason:R.aborted?"aborted":"queue"};if(typeof b!="function")return b;let g=b,I=null;try{if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let v=r.get(f.key);if(v!==void 0)return{...v,identity:"verified"};let B=En({budgetMs:Pe.readMs,flightSignal:R,call:me=>f.readAttachment(f.filePath,{maxBytes:n,head:!1,principal:o(f.owner),signal:me}),onOverrun:m("read",f),onStuck:S("read",f)}),x=await B.outcome;if(x.timedOut)return I=B.settled,R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let T=x.value;if(!T.ok&&T.reason!=="too_large")return mr(T.reason)?(T.reason==="not_found"&&a(f.attachmentId,!1),{kind:"failure",status:pr(T.reason),reason:T.reason,code:T.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(T.ok&&T.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let Y=y(f,T.ok?{kind:"exact",bytes:T.bytes.byteLength}:{kind:"over",maxBytes:n}),F=me=>{Y==="verified"&&r.set(f.key,me)},k=me=>(F(me),{...me,identity:Y});if(!T.ok)return k({kind:"unrenderable",reason:"too_large"});let ce=Tn(T.bytes);if(ce===null)return k({kind:"unrenderable",reason:"signature"});let de=En({budgetMs:Pe.renderMs,flightSignal:R,call:me=>f.renderer.render(T.bytes,{format:ce,maxWidth:f.box.maxWidth,maxHeight:f.box.maxHeight,signal:me}),onOverrun:m("render",f),onStuck:S("render",f)}),Re=me=>{if(me.kind==="error")return;let ye=ia(me.value,f.box);"entry"in ye&&F(ye.entry)},z=null,te=()=>(z===null&&(z=de.settled.then(Re),c(f.key,z)),z);R.addEventListener("abort",te,{once:!0});let Z=await de.outcome.finally(()=>R.removeEventListener("abort",te));if(Z.timedOut||R.aborted)return I=te(),R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let se=ia(Z.value,f.box);return"entry"in se?k(se.entry):se.failure}finally{I===null?g():I.then(g,g)}}};var ca=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let c=new AbortController,s=()=>{e.get(t)?.controller===c&&e.delete(t)},m={promise:n(c.signal).finally(s),controller:c,waiters:0};return e.set(t,m),m},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var ma=10,Jl=1/ma,ua=1-Jl,Ql=1024,Xl=64,Zl=8,da="private, no-cache",ec="no-store",tc=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),rc=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},pa=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:c}=l,s=(x,T)=>nt({reason:x,limitPerWindow:T,windowMs:6e4,logger:o,windowFields:Y=>`viewer=${Y} variant=thumbnail`}),y=s("rate_limit",l.rateLimitPerMinute),m=s("revalidation_rate_limit",l.rateLimitPerMinute*ma),S=Ge({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Xl,maxPerOwner:Zl,maxWaitMs:Pe.queueWaitMs}}),f=aa({maxBytes:l.cacheBytes,maxEntries:Ql}),R=ca(),b=la({gate:S,cache:f,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),g=(x,T,Y,F)=>{let k=`attachment=${x.attachmentId} viewer=${x.internalUserId} variant=thumbnail cache=${F}`;if(T.kind==="failure")return o[rc(T)](`${T.status} ${k} reason=${T.reason} code=${T.code??"-"}`),x.fail(T.status,lt[T.status],Ce(T.status));let ce=tc[T.identity];if(T.kind==="unrenderable")return o.info(`404 ${k} reason=${T.reason}${ce}`),x.fail(404,lt[404]);let de=T.identity==="verified"?{"Cache-Control":da,ETag:Y}:{"Cache-Control":ec},Re=new Headers({"Content-Type":T.contentType,"Content-Length":String(T.bytes.byteLength),...de,"Content-Security-Policy":"default-src 'none'; sandbox",...It});return x.cookie&&Re.append("Set-Cookie",x.cookie),o.info(`200 ${k} type=${T.contentType} bytes=${T.bytes.byteLength}${ce}`),new Response(T.bytes,{status:200,headers:Re})},I=(x,T)=>{let Y=x.spend(T.internalUserId,`attachment=${T.attachmentId} viewer=${T.internalUserId} variant=thumbnail`);return Y===null?null:T.fail(Y.status,Y.message,Y.headers)},v=x=>I(y,x),B=(x,T)=>T?I(m,x):v(x);return async(x,T)=>{let{request:Y,attachmentId:F,internalUserId:k,readAttachment:ce,cookie:de,fail:Re}=x,z=dn[T],te=Y.headers.get("If-None-Match"),Z=te!==null,se=B(x,Z);if(se)return se;let me=await n(Y),ye=await t.getAttachmentForUser(me,F,k),re=ye!==null&&yr(ye,i)?na({rendererId:c.id,box:z,attachmentId:F,filePath:ye.filePath,fileType:ye.fileType,fileSize:ye.fileSize}):null;if(re&&yn(te,re.etag)){let A=new Headers({"Cache-Control":da,ETag:re.etag,...It});return de&&A.append("Set-Cookie",de),o.info(`304 attachment=${F} viewer=${k} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:A})}if(Z){let A=v(x);if(A)return A}if(!ye)return o.warn(`404 attachment=${F} viewer=${k} variant=thumbnail reason=not_visible`),Re(404,lt[404]);if(!re)return y.refund(k,ua),o.info(`404 attachment=${F} viewer=${k} variant=thumbnail reason=not_eligible`),Re(404,lt[404]);let{key:Oe,etag:Ue}=re,xe=f.get(Oe);if(xe)return y.refund(k,ua),g(x,{...xe,identity:"verified"},Ue,"hit");let We=A=>b({key:Oe,attachmentId:F,filePath:ye.filePath,fileSize:ye.fileSize,box:z,owner:k,readAttachment:ce,renderer:c},A),L;try{L=await R.join(Oe,Y.signal,We)}catch(A){return o.error(`500 attachment=${F} viewer=${k} variant=thumbnail cache=miss reason=port_exception message=${A instanceof Error?A.message:"unknown"}`),Re(500,lt[500])}return g(x,L,Ue,"miss")}};var nc='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',oc=()=>ur(403,fn,{cookie:null}),ya=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=mn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>ur(404,dr[404],{cookie:null}),crossSiteRejection:oc}),ha=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:Co(r,a)},c=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:vo({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:pa({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:s,params:y})=>{let m=null,S=(f,R,b={})=>ur(f,R,{cookie:m,extraHeaders:b});try{let{user:f,cookie:R}=await t(s,{failureRedirect:null});if(m=R??null,!f)return S(401,"Unauthorized");let b=mn(new URL(s.url).searchParams);if(b.kind==="invalid")return S(400,"Invalid attachment request");if(b.kind==="thumbnail"&&s.method!=="GET")return S(405,"Method not allowed",{Allow:"GET"});if(s.method!=="GET"&&s.method!=="HEAD")return S(405,"Method not allowed",{Allow:"GET, HEAD"});if(c===null)return S(404,"Attachment not found");if(y.token===void 0)throw new Error(nc);let g=c.idCodec.decode(y.token);if(g===null||!Et(g))return S(400,"Invalid attachment token");let I=await r.getUserIdByExternalId(f.id);if(!I)return S(403,"Forbidden");let v={request:s,delivery:b,attachmentId:g,internalUserId:I,readAttachment:c.read,cookie:m,fail:S};return b.kind!=="thumbnail"?await c.serveOriginal(v):c.serveThumbnail===null?S(404,lt[404]):await c.serveThumbnail(v,b.variant)}catch(f){if(f instanceof Response)throw f;return a.error(`500 attachment=? viewer=? reason=unexpected message=${f instanceof Error?f.message:"unknown"}`),S(500,rt)}}};var ac=32*1024*1024,ic=60,sc=4,lc=120,cc=2,uc=8*1024*1024,hr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),dc=e=>{if(e===void 0)throw At("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!hr(e))throw le("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw At("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw le("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw le("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},mc=e=>{if(e===void 0)return null;if(!hr(e))throw le("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:dc(e.renderer),rateLimitPerMinute:mt("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,lc),concurrency:mt("attachments.thumbnails.concurrency",e.concurrency,1,cc),cacheBytes:mt("attachments.thumbnails.cacheBytes",e.cacheBytes,0,uc)})},fa=e=>{let t=e;if(t===void 0)return null;if(!hr(t))throw le("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw At("attachments.idCodec","injected when attachments is given");if(!hr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw le("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw At("attachments.read","injected when attachments is given");if(typeof n!="function")throw le("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:mt("attachments.maxBytes",t.maxBytes,1,ac),rateLimitPerMinute:mt("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,ic),concurrency:mt("attachments.concurrency",t.concurrency,1,sc),thumbnails:mc(t.thumbnails)})},pc=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"]]),fr=e=>{for(let[t,r]of pc)if(Object.hasOwn(e,t))throw At(r,`given in place of the flat key ${t}`)};var Sa=8,yc=8*Sa,hc=128,fc=2,ga=fc*hc,Rc=4*ga,Sc=6e4,gc=6e4,bc="Too many reads",Ra=Object.freeze(Object.keys(it).filter(e=>it[e].admission.includes("miss-gate"))),ba=e=>{let t=Ge({limit:yc,maxHeldPerOwner:Sa,queue:{max:Rc,maxPerOwner:ga,maxWaitMs:Sc}}),r=Fe({windowMs:gc,tallies:Ra,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Ra.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}})}},Rr=(e,t)=>{let r=X(e,t,{error:{message:bc}},503);for(let[n,o]of Object.entries(Ce(503)))r.headers.set(n,o);return r};var Dc=/^[0-9a-f]{1,16}$/;var Da=e=>{let t=e.get(he.cursorReportHubId),r=e.get(he.cursorBusinessDate),n=e.get(he.cursorSnapshot),o=n!==null&&Dc.test(n)?n:null,a=null;if(t!==null){let l=Be(t);if(l===null)return{refused:"cursor"};if(r!==null&&!nr(r))return{refused:"cursor"};a={businessDate:r,reportHubId:l}}else if(r!==null)return{refused:"cursor"};let i=Ft(e.get(he.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var Sr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Ac=2,Tc=16,Ec=Ac*Tc,Ic=6e4,Aa=()=>{},_c=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Ta=e=>{let t=Ge({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Ec,queue:null}),r=Fe({windowMs:Ic,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 Aa;if(a.aborted){if(t.canAcquire(n))return Aa}else{let i=await t.acquire(n,a);if(i!==null)return _c(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var gr=30,xa=4e3,wc="stream interrupted by server error",xc="Too many streams",Cc=15e3,Ca=Symbol("ids-stream-heartbeat"),Ea=()=>{},Ia=e=>e.return(void 0).then(Ea,Ea),Pc=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Ca),Cc)}),stop:()=>clearTimeout(e)}};async function*_a(e,t,r,n){let o=t?Jn(e,t):0,a=!0;for(;;){let i=e.slice(o,o+(a?r:xa));o+=i.length;let l=o>=e.length,c=i[i.length-1];if(yield{kind:"chunk",items:i,nextCursor:l||!c?null:{businessDate:c.businessDate,reportHubId:c.reportHubId},isLast:l,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,l)return}}var Pa=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...ze});return e&&t.append("Set-Cookie",e),t},wa=(e,t,r,n,o)=>{let a=async(y,m)=>{o(),m&&await Ia(t);try{y.close()}catch{}},i=new TextEncoder,l=!1,c=null,s=new ReadableStream({async pull(y){if(l||r.aborted){await a(y,!0);return}let m=Pc();try{c===null&&(c=t.next());let S=await Promise.race([c,m.fired]);if(m.stop(),S===Ca){if(l||r.aborted){await a(y,!0);return}y.enqueue(i.encode(`
2
- `));return}c=null;let{value:f,done:R}=S;if(R){await a(y,!1);return}if(l||r.aborted){await a(y,!0);return}y.enqueue(i.encode(`${JSON.stringify(f)}
3
- `))}catch(S){if(m.stop(),c=null,o(),l||r.aborted)return;S instanceof $e||n.error(`ids-stream emission failed: ${S instanceof Error?S.message:String(S)}`);try{let f={kind:"error",error:wc};y.enqueue(i.encode(`${JSON.stringify(f)}
4
- `)),y.close()}catch{}}},cancel(){l=!0,o(),Ia(t)}});return new Response(s,{status:200,headers:Pa(e)})},Ma=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,c,s,y,m,S,f)=>{let R=!1,b=null,g=null,I=new Promise((x,T)=>{b=x,g=T});I.catch(()=>{});let v=t.getDailyReportIdsByExternalId(s,c.id,{forceRefresh:l.forceRefresh,admission:f,onFetchStart:l.cursor?void 0:()=>{R=!0,t.readSseStreamAnchor().then(x=>t.getDailyReportIdsFirstPageByExternalId(s,c.id,gr).then(T=>({items:T,streamAnchor:x}))).then(x=>b?.(x),x=>g?.(x))}});if(v.catch(()=>{}),l.cursor){let{items:x,streamAnchor:T,snapshot:Y}=await v,F=l.snapshot!==null&&l.snapshot===Y;return wa(y,_a(x,F?l.cursor:null,gr,{snapshot:Y,restarted:!F,streamAnchor:T}),m,r,S)}let B=(async function*(){let x=await Promise.race([v.then(F=>({kind:"full",source:F}),F=>({kind:"full-error",error:F})),I.then(F=>({kind:"page",page:F}),()=>({kind:"page-error"}))]),T=null,Y=!1;if(x.kind==="full")T=x.source;else if(x.kind==="page"){let{items:F,streamAnchor:k}=x.page;if(F.length<gr){yield{kind:"chunk",items:F,nextCursor:null,isLast:!0,total:F.length,streamAnchor:k};return}yield{kind:"chunk",items:F,nextCursor:null,isLast:!1,provisional:!0},Y=!0}else if(x.kind==="full-error"&&R){let F=await I.catch(()=>null);F&&F.items.length>0&&(yield{kind:"chunk",items:F.items,nextCursor:null,isLast:!1,provisional:!0})}T===null&&(T=await v),yield*_a(T.items,null,Y?xa:gr,{snapshot:T.snapshot,streamAnchor:T.streamAnchor})})();return wa(y,B,m,r,S)};return async(l,c,s,y,m)=>{let S=Da(l.searchParams);if("refused"in S)return X(s,c,{error:{message:S.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:f}=S;if(f.forceRefresh){let I=a(y,s,c);if(I!==null)return I}let R=Sr(s),b=await t.getUserIdByExternalId(y.id),g=await n.admit(b,"ids-stream",R);if(g===null){let I=X(s,c,{error:{message:xc}},503);for(let[v,B]of Object.entries(Ce(503)))I.headers.set(v,B);return I}if(R.aborted)return new Response(null,{status:200,headers:Pa(c)});try{return await i(f,y,m,c,R,g,b===null?void 0:o.admissionFor(b,ne.idsStream,R))}catch(I){if(g(),I instanceof $e)return Rr(s,c);throw I}}};import{inArray as Mc,sql as La}from"drizzle-orm";var Lc="",Nc=64,Oc=e=>e.toLowerCase(),vc=e=>e.trim().toLowerCase();function Na(e){if(e==null)return null;if(!Array.isArray(e))return new Set;let t=new Set;for(let r of e){if(typeof r!="string")continue;let n=vc(r);n.length>0&&t.add(n)}return t}function Me(e,t){return e===null?!0:t==null?!1:e.has(Oc(t))}function Le(e){return e!==null&&e.size===0}function Bt(e,t){if(t!==null)return t.size===0?La`1 = 0`:Mc(La`LOWER(${e})`,[...t])}var wt,xt,$t=class $t{constructor(t,r){Br(this,wt);Br(this,xt);Vr(this,wt,t),Vr(this,xt,r)}get visible(){return Ot(this,wt)===null?null:new Set(Ot(this,wt))}get commentable(){return Ot(this,xt)===null?null:new Set(Ot(this,xt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Na(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new $t(n,n);let a=Na(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new $t(n,i)}static unrestricted(t){return new $t(null,null)}};wt=new WeakMap,xt=new WeakMap;var He=$t;function Vt(e){let t=Oa(e.visible),r=Oa(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Oa(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Lc);if(t.length<=Nc)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 va=(e,t,r,n)=>Me(n.commentable,t)||e.authorUserId!==null&&e.authorUserId===r;import{parseQuerySets as mu}from"@aiquants/fuzzy-search";import{createHash as kc}from"crypto";import{clusterCountOf as Fc,DEFAULT_NORMALIZE_OPTIONS as Dr,InteriorPairs as Hc,isAnswerTier as Uc,normalizeText as $c,queryNeedles as Bc,resolveNormalizeOptions as Vc,toMappedFormsInto as Yc,trimmedRange as qc}from"@aiquants/fuzzy-search/normalize";var Ar=`
5
- `,Tr=4e3,jc=1,Fa=new Set([8203,8288,65279,173]),Wc=new RegExp(`[${String.fromCodePoint(...Fa)}]`,"gu"),zc=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),Gc=/(\s+)/u,Kc=/^\s+$/u,Jc=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,Qc=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]),Yt=e=>e.replace(Wc,""),Ha=e=>{let t=Yt(e);if(t.length===e.length)return{text:t,rawIndex:null};let r=new Uint32Array(t.length),n=0;for(let o=0;o<e.length;o++)Fa.has(e.charCodeAt(o))||(r[n++]=o);return{text:t,rawIndex:r}},_n=e=>$c(e,Dr),br=e=>_n(Yt(e)),Xc=Vc({...Dr,convertRomaji:!0},"[daily-report] search reading options"),Zc=3,eu=/^[-ー]+/u,tu=/[^\p{L}\p{M}]/gu,ru=/ー{2,}/gu,nu=/\p{Script=Latin}/u,ka=/(?=\p{L})\p{Script=Latin}/u,ou=e=>Fc(e.replace(eu,"").replace(tu,"").replace(ru,"\u30FC")),au=(e,t)=>{for(let r of t)if(!Uc(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})`)},Ua=e=>{if(!ka.test(e))return[];let t=br(e);if(!ka.test(t))return[];let r=Bc(t,Xc,!1);au(t,r);let n=[];for(let o of r){if(o.tier===pt.word)continue;let a=br(o.text);if(!(a.length===0||a.length>_e.maxWordLength)&&!(a===t||nu.test(a))&&!(ou(a)<Zc||n.includes(a))&&(n.push(a),n.length===Kr))break}return n},$a=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},iu=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&$a(e,t-1)?t-2:t-1;return Jc.test(String.fromCodePoint(r))&&!Qc.has(e.codePointAt(n))},su=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!iu(e,i);)i--;i===a&&(i=a+r,$a(e,i)&&i--,o++),n.push({start:t+a,end:t+i}),a=i}return n.push({start:t+a,end:t+e.length}),{pieces:n,forcedCuts:o}},wn=(e,t)=>{if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let r=[],n=0,o=0,a=0,i=0,l=()=>{i>0&&r.push([{start:a,end:a+i}]),i=0};for(let c of e.split(Gc)){let s=o;if(o+=c.length,i+c.length<=t){i===0&&(a=s),i+=c.length;continue}if(l(),Kc.test(c))continue;if(c.length<=t){a=s,i=c.length;continue}let y=su(c,s,t);n+=y.forcedCuts,r.push(y.pieces)}return l(),{chunks:r,forcedCuts:n}},xn=(e,t)=>{let r=wn(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>_n(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},Cn=(e,t)=>{let r=0;for(let n of e.matchAll(zc))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},lu=(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},Ba=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],c=[];for(let s of a){let y=e.slice(s.start,s.end),m=lu(Yc(y,Dr,new Hc(0)),y),[S,f]=qc(m.text);i+=m.text.slice(S,f);for(let R=S;R<f;R++)l.push(s.start+m.start[R]),c.push(s.start+m.end[R])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let s=0;s<l.length;s++)n.push(l[s]),o.push(c[s])}}return{text:r,start:n,end:o}},Er=(e,t=Tr)=>{let r=[],n=0;return Cn(Yt(e),o=>{let a=xn(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(Ar),forcedCuts:n}},Va=e=>e.filter(t=>t.length>0).join(Ar),cu=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
6
- `)},uu=[`\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`],du=()=>{let e=kc("sha256");e.update(JSON.stringify(Dr));for(let t of["","\u30A2","\u4F50"," "])e.update("\0"),e.update(_n(cu(t)));return e.update("\0"),e.update(JSON.stringify(uu.map(t=>Er(t,8)))),`dr-search-v${jc};fz=${e.digest("hex").slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`},In=null,Ya=()=>(In===null&&(In=du()),In);var pu=/^-+/u,yu=/\s+/u,qa=e=>{let t=pu.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},hu=(e,t)=>{let r=[...qa(e).map(n=>({text:n,tier:pt.word})),...t.flatMap(n=>qa(n).map(o=>({text:o,tier:pt.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},fu=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),Ir=(e,t)=>{if(e.length>_e.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of mu(Yt(e),t).sets){let i=[],l=new Set;for(let s of a.split(yu)){let y=br(s);if(y.length===0)return{ok:!1,reason:"blank-word"};if(y.length>_e.maxWordLength)return{ok:!1,reason:"word-too-long"};let m=hu(y,Ua(s)),S=fu(m);l.has(S)||(l.add(S),i.push({alternatives:m}))}if(i.length>_e.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let c=JSON.stringify([...l].sort());n.has(c)||(n.add(c),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>_e.maxSets?{ok:!1,reason:"too-many-sets"}:o>_e.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},qt=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var Fy=Object.freeze({sourceTypes:null,authors:null,customers:null}),Ru=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,ja=(e,t,r)=>{if(lo(e)&&Ru(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=Ir(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var Wa=6e4,Su=1,gu=2e3,bu=Object.freeze({search:null,reports:null,"search-marks":gu,"search-facets":null}),Du=(e,t)=>{let r=bu[e];return r===null?null:{max:t,maxPerOwner:ar,maxWaitMs:r}},jt=e=>{let{concurrency:t,route:r,logger:n}=e,o=nt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:Wa,logger:n,windowFields:()=>`route=${r}`}),a=Ge({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:Du(r,t)}),i=Object.freeze({status:429,message:Sn,headers:Object.freeze({"Retry-After":String(Su)})}),l=Fe({windowMs:Wa,tallies:["busy"],writeSuppressed:(c,{count:s,since:y})=>{n.warn(`busy_suppressed count=${s} since=${y} route=${r} concurrency=${t}`)}});return{admit:async(c,s)=>{let y=o.spend(c,r);if(y!==null)return{refusal:y};let m=await a.acquire(c,s);return m!==null?{release:m}:(o.refund(c,1),s.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};import{systemSseRuntime as Cu}from"@aiquants/sse";import{createSseResponse as Pu,readLastEventId as Mu,startSseHeartbeat as Lu,terminalStreamResponse as Nu}from"@aiquants/sse/server";var Wt=(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=io.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n,text:r});return{entry:Object.freeze({id:e.id,message:a}),json:n}},Au=["externalComments","postedComments"],za=new WeakMap,Tu=e=>{let t=za.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return za.set(e,r),r},Ga=e=>{let{recipientRawUserId:t,...r}=e;return r},Ka=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=Tu(e);if(t){if(n.commentsRedacted===null){let o=Ga(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(Au.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(Ga(r))),n.recipientRemoved};import{systemSseRuntime as Iu}from"@aiquants/sse";import{createSharedSource as _u}from"@aiquants/sse/shared-source";var ht="daily-report:ids:",ft="daily-report:business-date:",_r=(e,t)=>`${e}st:${t}`,Pn=e=>`${ht}user:${e}:`,Ja=(e,t)=>_r(Pn(e),t),Eu=e=>`${ft}${e}:`,Qa=(e,t)=>_r(Eu(e),t),zt=e=>`daily-report:date:${e}:user:`,Ct=(e,t)=>`${zt(e)}${t}:`,Xa=(e,t,r)=>_r(Ct(e,t),r),Je=e=>`daily-report:detail:${e}:user:`,wr=(e,t)=>`${Je(e)}${t}:`,Za=(e,t,r)=>_r(wr(e,t),r);var ct=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},wu=5e3,xu=lr,Gt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=fe(t.logger,1,"SseReader"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return _u({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Iu,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:wu,COUNT:xu});if(i)for(let l of i)for(let c of l.messages){a=c.id;let{entry:s,json:y}=Wt(c,this._logger);this._invalidateCaches(y),r.next(s)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(ht),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Je(n))}};var ri=Object.freeze({...Ht,route:"sse",frameworkDataRefusal:cr}),ei=864e5,Ou={baseMs:2e3,jitterMs:8e3},ni=6e4,Mn=lr,oi=JSON.stringify({type:"connected"}),ti="0-0",vu=(e,t,r,n)=>{if(r===null&&n===null)return!0;let o=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Me(r,e.report.sourceType);case"comment-add":case"comment-delete":return Me(n,o??"Internal");case"report-delete":return Me(r,o)}},ku=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Me(t,e.report.sourceType),Fu=(e,t)=>{e.writeEvent({event:null,id:t,data:oi})},Hu=(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||!vu(o,a,r.visibleSet,r.commentableSet)){Fu(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Ka(n,ku(o,r.commentableSet))})},ai=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:c}=e,s=async(y,m)=>{let{request:S,internalUserId:f,cursor:R}=m,b=m.initialScope.visible,g=m.initialScope.commentable,I=0,v=setInterval(()=>{let z=++I;n(S,"refresh").then(te=>{z===I&&(b=te.visible,g=te.commentable)})},ni);y.onClose(()=>clearInterval(v));let B=R===null?ti:R,x=R!==null&&o!==void 0,T=[],Y=null,F=z=>{ct(z.id,B)||(B=z.id,Hu(y,z,{internalUserId:f,visibleSet:b,commentableSet:g}))},k=async(z,te)=>{let[Z]=await z.xRange(i,"-","+",{COUNT:1});return Z!==void 0&&!ct(Z.id,te)},ce=async(z,te)=>{if(await k(z,te))return!1;let Z=te;for(;;){let se=await z.xRange(i,Z,"+",{COUNT:Mn}),me=se[0];if(me!==void 0&&me.id!==Z&&await k(z,Z))return!1;for(let Qe of se){if(Y!==null&&ct(Y,Qe.id))return!0;ct(Qe.id,B)||F(Wt(Qe,c).entry)}let ye=se.at(-1);if(se.length<Mn||ye===void 0||y.isClosed())return!0;Z=ye.id}},de=a.subscribe(z=>{if(!x){F(z);return}ct(z.id,B)||(Y===null&&(Y=z.id),T.push(z))},z=>{c.error(`[SSE:${f}] Fan-Out reader error:`,z),y.close()});if(y.onClose(de),R===null){await a.ready();try{let z=await o?.getClient();if(z){let te=await z.xRevRange(i,"+","-",{COUNT:1});te.length>0&&!ct(te[0].id,B)&&(B=te[0].id)}}catch{}}if(y.writeEvent({event:null,id:B===ti?null:B,data:oi}),Lu(y,{intervalMs:ro,retry:Ou,runtime:Cu}),R===null||o===void 0)return;await a.ready();let Re=await o.getClient();if(Re===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await ce(Re,R)){y.writeRetry(ei),y.writeEvent({event:"resync-required",id:null,data:""}),y.close();return}x=!1;for(let z of T.splice(0))F(z)};return async({request:y,params:m})=>{let S,f=()=>{let b=new Headers;S!==void 0&&b.append("Set-Cookie",S);for(let[g,I]of Object.entries(ze))b.set(g,I);return b},R=b=>Nu(b,{data:"",retryMs:ei,headers:f()});try{let b=await t(y,{failureRedirect:null});S=b.cookie;let{user:g}=b;if(!g)return R("auth-required");let I=await r.getUserIdByExternalId(g.id);if(!I)return R("forbidden");if(m.endpoint!=="updates")return new Response("Not Found",{status:404,headers:f()});let v=Mu(y,no);if(v!==null&&!oo(v))return c.warn(`[SSE:${I}] malformed resume cursor; asking the client to resync`),R("resync-required");let B=Sr(y),x=await l.admit(I,"sse",B);if(x===null){let Y=f();for(let[F,k]of Object.entries(Ce(503)))Y.set(F,k);return new Response("Too many streams",{status:503,headers:Y})}let T=!1;try{let Y=await n(y,"initial");return Pu({requestSignal:B,headers:f(),onError:(F,k)=>c.error(`[SSE:${I}] ${k} failed:`,F),produce:F=>(T=!0,F.onClose(x),s(F,{request:y,internalUserId:I,cursor:v,initialScope:Y}))})}finally{T||x()}}catch(b){if(b instanceof Response)throw b;let g=b instanceof Error?b:new Error(String(b));return c.error(`500 sse name=${g.name} message=${g.message}`),new Response("Internal Server Error",{status:500,headers:f()})}}};var ii=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...ze});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Uu=Object.freeze({...Ht,route:"api",frameworkDataRefusal:({params:e})=>un(e.endpoint)&&it[e.endpoint].body==="stream"?cr():null}),$u=Object.freeze({...Ht,route:"action"}),Bu=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),ci=6e4,ui=5,Vu=ui*Math.ceil(ci/500),Yu=2,qu=6,ju=6e4,Wu=ui*Yu*qu,zu=2,Gu=10,Ku=2,Ju=10,si=(e,t)=>Math.max(e,ar)*t,Ln=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},Cr=(e,t,r)=>Ln(X(e,t,{error:{message:r.message}},r.status),r.headers),li=e=>Ln(tt(e,null,503),Ce(503));function Nn(e){fr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:ee("service.titleMaxLength",r.titleMaxLength,1)},c=e.loginRedirectPath??"/auth/login",s=fe(e.logger,3,"API"),y=fe(e.logger,3,"Visibility"),m=fe(e.logger,1,"SSE"),S=fe(e.logger,1,"Attachment"),f=fe(e.logger,2,"Isolation"),R=fe(e.logger,2,"Action"),b=fe(e.logger,2,"Search"),g=fe(e.logger,2,"Refresh"),I=fe(e.logger,2,"Streams"),v=fe(e.logger,2,"Reads"),B=nt({reason:"refresh_rate_limit",limitPerWindow:Wu,windowMs:ju,logger:g,windowFields:()=>"route=api"}),x=Ta(I),T=ba(v),Y=async(L,A,w,V,q)=>{let K=await r.getUserIdByExternalId(A.id);try{return await q(K===null?void 0:T.admissionFor(K,L,w.signal))}catch(G){if(G instanceof $e)return Rr(w,V);throw G}},F=(L,A,w,V)=>{let q=B.spend(A.id,`endpoint=${L}`);return q===null?null:Cr(w,V,q)},k=async(L,A="initial")=>{let w=e.resolveVisibleSourceTypes;if(!w)return He.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let V=await w(L,{reason:A});return V==null?He.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):He.restrictTo(V)}catch(V){return y.error("resolveVisibleSourceTypes threw; failing closed (deny all)",V),He.restrictTo([])}},ce=async({request:L})=>{let{user:A,cookie:w}=await t(L,{failureRedirect:c}),V=new Headers;w&&V.append("Set-Cookie",w);let q=await r.getUserIdByExternalId(A.id),K=q?n(q):null;return{data:{user:A,userId:K},headers:V}},de=r.searchLimits===null?null:jt({...r.searchLimits,route:ne.search,logger:b}),Re=r.searchLimits===null?null:jt({concurrency:si(r.searchLimits.concurrency,zu),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Gu,route:ne.reports,logger:b}),z=r.searchLimits===null?null:jt({concurrency:si(r.searchLimits.concurrency,Ku),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Ju,route:ne.searchMarks,logger:b}),te=r.searchLimits===null?null:jt({...r.searchLimits,route:ne.searchFacets,logger:b}),Z={[ne.businessDate]:async(L,A,w,V,q)=>{let K=L.searchParams.get(he.businessDate),G=K===null?null:Tt(K);if(G===null)return X(w,A,{error:{message:"Invalid business date"}},400);let W=Ft(L.searchParams.get(he.forceRefresh));if(W===null)return X(w,A,{error:{message:"Invalid forceRefresh"}},400);let J=W?F(ne.businessDate,V,w,A):null;return J!==null?J:Y(ne.businessDate,V,w,A,async C=>{let oe=await r.getDailyReportsByBusinessDateByExternalId(q,G,V.id,{forceRefresh:W,admission:C});return X(w,A,{businessDate:G,reports:oe},200)})},[ne.idsStream]:Ma({service:r,logger:s,streamSlots:x,missGate:T,refuseForcedRead:(L,A,w)=>F(ne.idsStream,L,A,w)}),[ne.report]:async(L,A,w,V,q)=>{let K=Be(L.searchParams.get(he.reportHubId));if(K===null)return X(w,A,{error:{message:"Invalid reportHubId"}},400);let G=Ft(L.searchParams.get(he.forceRefresh));if(G===null)return X(w,A,{error:{message:"Invalid forceRefresh"}},400);let W=G?F(ne.report,V,w,A):null;return W!==null?W:Y(ne.report,V,w,A,async J=>{let C=await r.getDailyReportDetailByIdByExternalId(q,K,V.id,{snapshot:!0,forceRefresh:G,admission:J});return C?X(w,A,{report:C},200):X(w,A,{error:{message:"Report not found"}},404)})},[ne.search]:async(L,A,w,V,q)=>{if(de===null)return X(w,A,{error:{message:"Unknown endpoint"}},404);let K=L.searchParams.get(he.searchQuery),G=ln(L.searchParams.get(he.searchCombine));if(K===null||G===null)return X(w,A,{error:{message:"Invalid search request"}},400);let W=uo(L.searchParams,r.searchFilterSourceTypes);if(!W.ok)return X(w,A,{error:{message:"Invalid search filters",reason:W.reason}},400);let J=ja(K,G,W.filters);if(!J.ok)return X(w,A,{error:{message:"Invalid search query",reason:J.reason}},400);let{criteria:C}=J,oe=C.plan===null?[]:qt(C.plan),Se=await r.getUserIdByExternalId(V.id);if(!Se)return X(w,A,Jr([],oe),200);let Ie=await de.admit(Se,w.signal);if("refusal"in Ie)return Cr(w,A,Ie.refusal);try{let Dt=await r.searchDailyReports(q,Se,C);return X(w,A,Jr(Dt,oe),200)}finally{Ie.release()}},[ne.reports]:async(L,A,w,V,q)=>{if(Re===null)return X(w,A,{error:{message:"Unknown endpoint"}},404);let K=cn(L.searchParams.get(he.reportIds));if(K===null)return X(w,A,{error:{message:"Invalid ids"}},400);let G=await r.getUserIdByExternalId(V.id);if(!G)return X(w,A,{reports:[]},200);let W=await Re.admit(G,w.signal);if("refusal"in W)return Cr(w,A,W.refusal);try{let J=await r.getDailyReportDetailsByIdsByExternalId(q,K,V.id);return X(w,A,{reports:J},200)}finally{W.release()}},[ne.searchMarks]:async(L,A,w,V,q)=>{if(z===null)return tt(A,{error:{message:"Unknown endpoint"}},404);let K=L.searchParams.get(he.searchQuery),G=ln(L.searchParams.get(he.searchCombine));if(K===null||G===null)return tt(A,{error:{message:"Invalid search request"}},400);let W=Ir(K,G);if(!W.ok)return tt(A,{error:{message:"Invalid search query",reason:W.reason}},400);let J=cn(L.searchParams.get(he.reportIds));if(J===null)return tt(A,{error:{message:"Invalid ids"}},400);let C=await r.getUserIdByExternalId(V.id);if(!C)return tt(A,{wordsDigest:or(qt(W.plan)),reports:[]},200);let oe=await z.admit(C,w.signal);if("refusal"in oe)return w.signal.aborted?li(A):Ln(tt(A,{error:{message:oe.refusal.message}},oe.refusal.status),oe.refusal.headers);try{let Se=await r.markDailyReportSearchHits(q,C,W.plan,J,{signal:w.signal});return w.signal.throwIfAborted(),tt(A,Se,200)}catch(Se){if(w.signal.aborted&&Se===w.signal.reason)return li(A);throw Se}finally{oe.release()}},[ne.searchFacets]:async(L,A,w,V,q)=>{if(te===null)return X(w,A,{error:{message:"Unknown endpoint"}},404);let K=await r.getUserIdByExternalId(V.id);if(!K)return X(w,A,{sourceTypes:[],authors:[],customers:[]},200);let G=await te.admit(K,w.signal);if("refusal"in G)return Cr(w,A,G.refusal);try{let W=await r.listDailyReportSearchFacets(q,K);return X(w,A,W,200)}finally{G.release()}}},se=async({request:L,params:A})=>{let{user:w,cookie:V}=await t(L,{failureRedirect:null}),q=V??null;if(!w)return X(L,q,{error:{message:"Unauthorized"}},401);let K=A.endpoint;if(!un(K))return X(L,q,{error:{message:"Unknown endpoint"}},404);let G=Do[it[K].body];if(!G.includes(L.method)){let J=X(L,q,{error:{message:"Method not allowed"}},405);return J.headers.set("Allow",G.join(", ")),J}let W=ue();try{let J=new URL(L.url),C=await k(L),oe=await Z[K](J,q,L,w,C);return it[K].body==="json"&&s.debug(`${oe.status} endpoint=${K} etag_match=${oe.status===304}`),oe}catch(J){let C=ue()-W,oe=J instanceof Error?J:new Error(String(J));return s.error(`500 endpoint=${K} elapsed=${C}ms name=${oe.name} code=${"code"in oe?oe.code:"N/A"} message=${oe.message}`,oe),X(L,q,{error:{message:"Internal Server Error"}},500)}},me=bo(R),ye=nt({reason:"rate_limit",limitPerWindow:Vu,windowMs:ci,logger:R,windowFields:()=>"route=action"}),Qe=async(L,A,w,V,q)=>{let{clientTempId:K}=L;if(L.intent==="create"){let C=await r.createDailyReport(A,L.businessDate,K);return q(L,C.reportHubId,{report:C})}let{reportHubId:G,businessDate:W}=L,J=async(C,oe)=>{try{let Se=await oe(C.value);return q(C,G,{updatedStatus:{isStarred:Se.isStarred,isRead:Se.isRead},operationTimestamp:C.operationTimestamp})}catch(Se){if(Se instanceof Error&&Se.message==="Not Found")return V({error:"Report not found"},{status:404});throw Se}};switch(L.intent){case"update":try{return await r.updateDailyReport(G,A,L.changes,K),q(L,G,{})}catch(C){if(C instanceof Error){if(C.message==="Unauthorized")return V({error:"Unauthorized"},{status:403});if(C.message==="Not Found")return V({error:"Report not found"},{status:404})}throw C}case"publish":try{let C=await r.publishDailyReport(G,A,K);return q(L,G,{report:C})}catch(C){if(C instanceof Error){if(C.message==="Unauthorized")return V({error:"Unauthorized"},{status:403});if(C.message==="Not Found")return V({error:"Report not found"},{status:404})}throw C}case"delete":try{return await r.deleteDailyReport(G,A,K),q(L,G,{})}catch(C){if(C instanceof Error){if(C.message==="Unauthorized")return V({error:"Unauthorized"},{status:403});if(C.message==="Not Found")return V({error:"Report not found"},{status:404})}throw C}case"toggleStar":return await J(L,C=>r.setStarStatus(w,A,G,W,C,K));case"toggleRead":return await J(L,C=>r.setReadStatus(w,A,G,W,C,K));case"addComment":try{let C=await r.addComment(w,A,G,L.content,W,K);return q(L,G,{newComment:C})}catch(C){if(C instanceof Error){if(C.message==="Not Found")return V({error:"Report not found"},{status:404});if(C.message.startsWith("Comments are restricted"))return V({error:"Comments are restricted for this report"},{status:403})}throw C}case"deleteComment":try{return await r.deleteComment(w,A,G,L.commentId,W,K),q(L,G,{deletedCommentId:L.commentId})}catch(C){if(C instanceof Error){if(C.message==="Unauthorized")return V({error:"Unauthorized"},{status:403});if(C.message==="Not Found")return V({error:"Comment not found"},{status:404})}throw C}}},re=async({request:L,params:A})=>{let{user:w,cookie:V}=await t(L,{failureRedirect:null}),q=(W,J)=>ii(W,{...J,setCookie:V}),K=(W,J,C)=>ii(Bu(W,J,C),{setCookie:V});if(!w)return q({error:"Unauthorized"},{status:401});let G=ue();try{if(A.endpoint!==ne.action)return q({error:"Unknown endpoint"},{status:404});let W=ye.spend(w.id,"action");if(W!==null)return q({error:W.message},{status:W.status,headers:W.headers});let J=await go(L,l);if("refusal"in J){let{refusal:Ie}=J;return Ie.status===413&&me(Ie.measuredBy),q({error:Ie.error},{status:Ie.status})}let{command:C}=J;if(C.intent==="clearCache"&&!e.enableDevCacheClear)return q({error:"Invalid intent"},{status:400});let oe=await r.getUserIdByExternalId(w.id);if(!oe)return q({error:"User not found"},{status:404});let Se=await k(L);return C.intent==="clearCache"?(await r.clearCache(),q({status:"OK",intent:"clearCache"})):await Qe(C,oe,Se,q,K)}catch(W){if(W instanceof Response)throw W;let J=ue()-G,C=W instanceof Error?W:new Error(String(W));return s.error(`500 action elapsed=${J}ms name=${C.name} message=${C.message}`,C),q({error:"Internal Server Error"},{status:500})}},Oe=ai({authenticate:t,service:r,resolveViewerScope:k,redis:o,sseReader:a,streamKey:i,streamSlots:x,logger:m}),Ue=ha({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:k,logger:S}),xe=xo(f),We=(L,A)=>async w=>{let V=_o(w.request)?L.frameworkDataRefusal(w):null;if(V!==null)throw V;return wo(w.request,L)?(xe(L.route,w.request),L.crossSiteRejection()):A(w)};return{index:{loader:ce},api:{loader:We(Uu,se),action:We($u,re)},sse:{loader:We(ri,Oe)},attachment:{loader:We(ya,Ue)}}}import{chunk as Rd,MAX_IN_LIST as Sd,runWithTransactionRetry as gd}from"@aiquants/mssql";import{and as Te,asc as Ne,desc as Mt,eq as $,getColumns as bd,inArray as qe,isNull as Lt,sql as Ci}from"drizzle-orm";import{sql as Pt}from"drizzle-orm";var Pr=(e,t,r,n)=>{if(r.length===0)return;let{hub:o,hubLabel:a,label:i}=e,l=n==="author-or-authorless"?Pt`${o.userId} = ${t} OR ${o.userId} IS NULL`:Pt`${o.userId} = ${t}`,c=Pt.join(r.map(s=>Pt`${s}`),Pt`, `);return Pt`(${l} OR NOT EXISTS (SELECT 1 FROM ${a} INNER JOIN ${i} ON ${i.id} = ${a.labelId} WHERE ${a.hubId} = ${o.id} AND ${i.name} IN (${c})))`};var Qu=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],Xu=["document","comment"],Zu=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],ed=["hubId","ordinal","authorUserId","commentText"],On=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},di=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw Yr(e,n,r)},mi=(e,t,r)=>{if(typeof t!="object"||t===null)throw le(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw le(`${e}.${o}`,"a column",n[o])},pi=(e,t)=>{if(!On(e))throw le("search","a plain object",e);di("search key",e,Qu);let{tables:r}=e;if(!On(r))throw le("search.tables","a plain object with document and comment",r);di("search.tables key",r,Xu),mi("search.tables.document",r.document,Zu),mi("search.tables.comment",r.comment,ed);let n=new Map;if(e.externalSourceTexts!==void 0){if(!On(e.externalSourceTexts))throw le("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw Yr("search.externalSourceTexts key",o,t);if(typeof a!="function")throw le(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:ee("search.concurrency",e.concurrency,1),rateLimitPerMinute:ee("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var ut=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},Rt=(e,t)=>{let r=typeof e=="string"?Be(e):typeof e=="number"&&Et(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},St=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};import{sql as H}from"drizzle-orm";var td=/[[%_]/gu,rd=e=>e.replace(td,t=>`[${t}]`),yi=e=>`%${rd(e)}%`;var Ye=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),gt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),Jt=Object.freeze({value:"value"}),Ae=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),U=e=>H`${H.identifier(e.name)}`,Kt=e=>H.join(e.map(t=>H`${t}`),H`, `),hi=(e,t)=>H`SELECT ${U(e.id)} AS ${H.identifier(Ae.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${Kt(t)}) ORDER BY ${e.id}`,nd=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(m=>yi(m.text)),l=H.join(i.map(m=>H`${o.searchText} LIKE ${m}`),H` OR `),c=H.join(i.map(m=>H`${a.commentText} LIKE ${m}`),H` OR `),s=Bt(n.sourceType,r.scope.commentable),y=s===void 0?H``:H` AND (${s} OR ${a.authorUserId} = ${r.userId})`;return H`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${c})${y}))`},fi=(e,t,r)=>H`(${H.join(t.words.map(n=>nd(e,n,r)),H` AND `)})`,vn=(e,t,r,n)=>{let{hub:o}=e,a=[H`${o.deletedAt} IS NULL`],i=Pr(e,t.userId,r,"author");i!==void 0&&a.push(i);let l=Bt(o.sourceType,t.scope.visible);return l!==void 0&&a.push(l),n!==void 0&&a.push(H`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},od=(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(H`LOWER(${r.sourceType}) IN (${Kt([...t.sourceTypes])})`)}return t.authors!==null&&o.push(H`${n.authorName} IN (${Kt(t.authors)})`),t.customers!==null&&o.push(H`${n.customerName} IN (${Kt(t.customers)})`),o},Ri=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,c=[...vn(e,r,n,o),...od(e,t.filters)];if(l!==null){let s=l.combine==="intersection"?H` AND `:H` OR `;c.push(H`(${H.join(l.sets.map(y=>fi(e,y,r)),s)})`)}return H`SELECT ${U(a.id)} AS ${H.identifier(Ye.reportHubId)}, CONVERT(char(10), ${U(a.businessDate)}, 23) AS ${H.identifier(Ye.businessDate)}, ${U(a.sourceType)} AS ${H.identifier(Ye.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${H.join(c,H` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},Si=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=H.join(t.sets.map((c,s)=>H`(CASE WHEN ${fi(e,c,r)} THEN ${2**s} ELSE 0 END)`),H` + `);return H`SELECT ${U(a.id)} AS ${H.identifier(gt.reportHubId)}, ${l} AS ${H.identifier(gt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${H.join(vn(e,r,n,o),H` AND `)}`},gi=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...vn(e,r,n),H`${i} IS NOT NULL`];return H`SELECT ${i} AS ${H.identifier(Jt.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${H.join(l,H` AND `)} GROUP BY ${i} ORDER BY ${i}`},bi=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(c=>({[n.hubId.name]:c.hubId,[n.searchText.name]:c.searchText,[n.sourceDigest.name]:c.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:c.authorName,[n.customerName.name]:c.customerName}))),i=JSON.stringify(t.flatMap(c=>c.comments.map(s=>({[o.hubId.name]:c.hubId,[o.ordinal.name]:s.ordinal,[o.authorUserId.name]:s.authorUserId,[o.commentText.name]:s.commentText})))),l=JSON.stringify(t.map(c=>c.hubId));return H`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${U(n.hubId)} bigint, ${U(n.searchText)} nvarchar(max), ${U(n.sourceDigest)} char(64), ${U(n.normalizerVersion)} varchar(64), ${U(n.authorName)} nvarchar(max), ${U(n.customerName)} nvarchar(max))) AS s ON t.${U(n.hubId)} = s.${U(n.hubId)}
8
- WHEN MATCHED THEN UPDATE SET t.${U(n.searchText)} = s.${U(n.searchText)}, t.${U(n.sourceDigest)} = CONVERT(binary(32), s.${U(n.sourceDigest)}, 2), t.${U(n.normalizerVersion)} = s.${U(n.normalizerVersion)}, t.${U(n.authorName)} = s.${U(n.authorName)}, t.${U(n.customerName)} = s.${U(n.customerName)}, t.${U(n.indexedAt)} = SYSUTCDATETIME()
9
- WHEN NOT MATCHED THEN INSERT (${U(n.hubId)}, ${U(n.searchText)}, ${U(n.sourceDigest)}, ${U(n.normalizerVersion)}, ${U(n.authorName)}, ${U(n.customerName)}) VALUES (s.${U(n.hubId)}, s.${U(n.searchText)}, CONVERT(binary(32), s.${U(n.sourceDigest)}, 2), s.${U(n.normalizerVersion)}, s.${U(n.authorName)}, s.${U(n.customerName)});
1
+ var ao=e=>{throw TypeError(e)};var io=(e,t,r)=>t.has(e)||ao("Cannot "+r);var Ot=(e,t,r)=>(io(e,t,"read from private field"),r?r.call(e):t.get(e)),jr=(e,t,r)=>t.has(e)?ao("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Wr=(e,t,r,n)=>(io(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var zr=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,ne=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${zr(r)}`),Qe=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),Gr=(e,t,r)=>ne(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),te=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw ne(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},ht=(e,t,r,n)=>t===void 0?n:te(e,t,r);var ue=()=>Math.floor(performance.now());var $e=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},Kr=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{}}}),Ft=(e,t)=>t?e.map(r=>structuredClone(r)):e,ol=8,al=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=ol*a.length;for(let i of a)typeof i=="string"?r+=2*i.length:typeof i=="object"&&i!==null&&n.push(i)}return r},Ht=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-ue())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let c=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:s,expireAt:ue()+a,epoch:c}),s})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&c===null)throw new $e(o.signal.aborted?"aborted":"busy");try{for(let m of r)m();let s=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:s,expireAt:ue()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),s}finally{c?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new $e("aborted");return this.dropBucket(r),Ft(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ue())if(t.epochKey){let c=await this.epochStore.getEpoch(t.epochKey);if(c===null||i.epoch===c)return this.maybeRefreshAhead(t),Ft(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),Ft(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return Ft(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new $e("aborted");return Ft(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 $e&&(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=te("defaultTtlMs",t.defaultTtlMs,1),this.maxBuckets=te("maxBuckets",t.maxBuckets,1),this.maxBytes=te("maxBytes",t.maxBytes,1),this.lastSweepAt=ue()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=al(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=ue();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};var il=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var so=e=>e<10?`0${e}`:`${e}`,sl=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=so(e.getMonth()+1),n=so(e.getDate());return`${t}-${r}-${n}`},It=e=>{let t=il.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let c=new Date(0);return c.setUTCFullYear(a,i-1,l),c.getUTCFullYear()!==a||c.getUTCMonth()!==i-1||c.getUTCDate()!==l?null:`${r}-${n}-${o}`},or=e=>It(e)===e;var ve=e=>e==null?null:e instanceof Date?sl(e):It(e);import{z as ll}from"zod";var lt=e=>Number.isSafeInteger(e)&&e>0,be=ll.number().int().positive().max(Number.MAX_SAFE_INTEGER);var lo="ids-columns";var _t=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],c=new Map;for(let s=t;s<r;s++){let{reportHubId:m,businessDate:u,sourceType:f}=e[s];n.push(m),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let h=f===void 0?null:f,R=c.get(h);R===void 0&&(R=i.length,i.push(h),c.set(h,R)),l.push(R)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},ar=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+(?=.)/,"")},co=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,cl=(e,t,r,n)=>co(e,t,r,n)<0,Jr=(e,t)=>co(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),uo=e=>{for(let t=1;t<e.length;t++)if(!cl(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},po=(e,t)=>{let r=e.findIndex(n=>Jr({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var ie=Object.freeze({businessDate:"business-date",idsStream:lo,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),Re=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 mo=(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)}}},sm=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),yo=e=>`[DailyReport${e}]`,Se=(e,t,r)=>e===void 0?mo(t,yo(r)):mo(0,yo(r),e);var ul="legacy-",Qr=e=>`${ul}${e}`;var dl=/^[1-9][0-9]*$/,pl=/^(?:0|[1-9][0-9]*)$/,Be=e=>{if(e===null||!dl.test(e))return null;let t=Number(e);return lt(t)?t:null},Xr=e=>{if(e===null||!pl.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Zr=e=>e==="true"?!0:e==="false"?!1:null,Ut=e=>e===null?!1:Zr(e);var ho=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),Xe=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var ml=16777619,en=2166136261,tn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,ml);return o>>>0},fo=e=>tn(en,e,0,e.length),yl=String.fromCodePoint(3),hl=String.fromCodePoint(2),fl=String.fromCodePoint(1),ir=e=>fo(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(yl)).join(hl)).join(fl));var Ro=e=>e==="intersection"||e==="union",_e=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),rn=2,sr=2,ft=Object.freeze({word:0,reading:1});var nn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var mm=2*(1+rn);import{z as Dm}from"zod";var lr=/^(?:[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})$/;import{z as C}from"zod";var So=15e3,go="lastEventId",Rl=/^\d{1,15}-\d{1,15}$/,bo=e=>Rl.test(e),Sl=C.object({name:C.string().nullish(),affiliation:C.string().nullish()}),gl=C.object({name:C.string().nullish(),text:C.string().nullish(),color:C.string().nullish()}),bl=C.object({id:be,name:C.string().nullish(),color:C.string().nullish()}),Do=C.object({id:be,userId:C.string().nullish(),userName:C.string().nullish(),content:C.string().nullish(),createdAt:C.string().nullish(),isMine:C.boolean()}),Dl=C.object({id:C.string(),fileName:C.string(),fileType:C.string().nullable(),fileSize:C.number().nullable(),createdAt:C.string().nullable(),state:C.enum(["present","absent","unknown"]),hasThumbnail:C.boolean().default(!1)}),on=C.object({reportHubId:be,date:C.string().nullish(),createdAt:C.string().nullish(),author:C.string().nullish(),userId:C.string().nullish(),sourceType:C.string().nullish(),employeeName:C.string().nullish(),updatedBy:C.string().nullish(),updatedAt:C.string().nullish(),category:C.string().nullish(),creationCategory:C.string().nullish(),visitTimeFrom:C.string().nullish(),visitTimeTo:C.string().nullish(),customerName:C.string().nullish(),interviewers:C.array(Sl),subject:C.string().nullish(),content:C.string().nullish(),externalComments:C.array(gl),isRead:C.boolean(),isStarred:C.boolean(),isDraft:C.boolean(),labels:C.array(bl),postedComments:C.array(Do),attachments:C.array(Dl).default([])}),Rt=C.string().regex(lr),Al=C.object({type:C.literal("connected")}),cr=C.object({type:C.literal("status-update"),reportHubId:be,statusType:C.enum(["star","read"]),value:C.boolean(),clientTempId:Rt,recipientRawUserId:be.optional()}),an=C.string().optional(),sn=C.object({type:C.literal("comment-add"),reportHubId:be,comment:Do,clientTempId:Rt,recipientRawUserId:be.optional(),sourceType:an}),ln=C.object({type:C.literal("comment-delete"),reportHubId:be,commentId:be,clientTempId:Rt,recipientRawUserId:be.optional(),sourceType:an}),cn=C.object({type:C.literal("report-create"),reportHubId:be,report:on,clientTempId:Rt,recipientRawUserId:be.optional()}),un=C.object({type:C.literal("report-update"),reportHubId:be,report:on,clientTempId:Rt,recipientRawUserId:be.optional()}),dn=C.object({type:C.literal("report-publish"),reportHubId:be,report:on,clientTempId:Rt,recipientRawUserId:be.optional()}),pn=C.object({type:C.literal("report-delete"),reportHubId:be,clientTempId:Rt,sourceType:an}),Ao=C.discriminatedUnion("type",[Al,cr,sn,ln,cn,un,dn,pn]);var Oe=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var ur=Math.max(1,Math.floor(10.556701030927835));var Ve=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Fe=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(s=>[s,0]))};o.set(i,l),Ve(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,c)=>{let s=o.get(i);if(s!==void 0){s.count+=1,s.tallies[l]+=1;return}c(),a(i)}}};var Ze=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var _m=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),Tl=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,mn=e=>{let t=e.trim();return t.length===0?null:t.replace(Tl,"\uFFFD")},El=e=>{let t=mn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>Ze.maxValueLength?"filter-value-too-long":null},wl=e=>{if(e.length>Ze.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=El(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},Il=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},To=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=wl(t);if(r!==null)return r}return Il(e)>Ze.maxTotalValueLength?"filters-too-long":null};var Eo=e=>e.trim().length===0;var yn=e=>e!==null&&lr.test(e)?e:null,hn=e=>Ro(e)?e:null,fn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>_e.maxDetailIds)return null;let r=[];for(let n of t){let o=Be(n);if(o===null||r.includes(o))return null;r.push(o)}return r},wo=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},Io=(e,t)=>{let r={authors:e.getAll(Re.searchAuthor),sourceTypes:e.getAll(Re.searchSourceType),customers:e.getAll(Re.searchCustomer)},n=To(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:wo(r.authors),customers:wo(r.customers)}}},_o=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Co=Object.freeze({status:400,error:"Invalid form"}),Mo=e=>({status:413,error:"Form too large",measuredBy:e}),_l=(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)}}))},xl=async e=>{let t=Xr(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Mo("declared")};let r=!1,n=e.body===null?null:_l(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?Mo("counted"):Co}}let l=_o(i);return l===null?{refusal:Co}:{fields:l}},Po=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=Zr(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},No=Object.freeze({update:(e,t,r)=>{let n=e.get(Oe.title),o=e.get(Oe.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:Po("toggleStar",Oe.isStarred),toggleRead:Po("toggleRead",Oe.isRead),addComment:(e,t)=>{let r=e.get(Oe.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Be(e.get(Oe.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Cl=e=>Object.hasOwn(No,e),Ml=(e,t)=>{let r=e.get(Oe.intent),n=e.get(Oe.businessDate),o=n===null?null:It(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Oe.operationTimestamp),i=Xr(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Oe.clientTempId);if(!l)return{error:"clientTempId required"};let c=yn(l);if(c===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:c,businessDate:o,operationTimestamp:i}};let s=Be(e.get(Oe.reportHubId));return s===null?{error:"Invalid reportHubId"}:r===null||!Cl(r)?{error:"Invalid intent"}:No[r](e,{clientTempId:c,businessDate:o,operationTimestamp:i,reportHubId:s},t)},ko=async(e,t)=>{let r=await xl(e);if("refusal"in r)return r;let n=Ml(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Pl=6e4,Ll="form_too_large",Lo=["declared","counted"],vo=e=>{let t=Fe({windowMs:Pl,tallies:Lo,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Lo.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(Ll,r,n)}};var St=Object.freeze({[ie.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ie.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[ie.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ie.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[ie.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[ie.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[ie.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),Oo=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Rn=e=>e!==void 0&&Object.hasOwn(St,e);var Sn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Fo=e=>Object.hasOwn(Sn,e);var Nl="download",kl="thumbnail",vl="1";var gn=e=>{let t=e.getAll(kl),r=e.getAll(Nl);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Fo(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===vl?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{createHash as Ol}from"crypto";var bn=e=>`"${Ol("sha256").update(e).digest("hex")}"`,Ho=e=>bn(JSON.stringify(e));var je=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),Dn=(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},Uo=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=bn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...je});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&Dn(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},An=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...je});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},Tn=e=>(t,r,n,o)=>{if(o!==200)return An(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)},Fl=5e3/1e3,Hl=new Map([[503,Fl]]),Me=e=>{let t=Hl.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var wn="Cross-site request rejected",Ul="Not Found",$l=new Set(["same-origin","none"]),Bl=new Set(["GET","HEAD","OPTIONS"]),$o=["api","action","sse","attachment"],Bo=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...je}}),Vl=()=>Bo(403,wn),dr=()=>Bo(404,Ul),$t=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:Vl}),Vo=e=>new URL(e.url).pathname.endsWith(".data"),ql=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},qo=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Bl.has(e.method)||ql(e)):$l.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},Yl=6e4,jl="refusals",Wl=32,zl=/^[a-z-]+$/,En=e=>{if(e===null)return"-";let t=e.slice(0,Wl);return zl.test(t)&&t===e?e:JSON.stringify(t)},Yo=e=>{let t=Fe({windowMs:Yl,tallies:$o,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${$o.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${En(a.get("Sec-Fetch-Site"))} mode=${En(a.get("Sec-Fetch-Mode"))} dest=${En(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(jl,r,o)}};var jo=(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 Gl="same-origin",Kl="SAMEORIGIN",xt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Gl,"X-Frame-Options":Kl}),pr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...xt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Wo=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Jl=/^[\x20-\x7E]+$/,Ql=/^[\w.+-]+\/[\w.+-]+/,In=e=>e&&Jl.test(e)&&Ql.test(e)?e:null,Xl=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,zo=e=>encodeURIComponent(e.replace(Xl,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Go=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),mr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},Ko={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},yr=e=>typeof e=="string"&&Object.hasOwn(Ko,e),hr=e=>Ko[e],et="Attachment request failed";var We=e=>{let t=te("limit",e.limit,1),r=te("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:te("queue.max",e.queue.max,0),maxPerOwner:te("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:te("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,c=(S,A)=>S.get(A)??0,s=(S,A,x)=>{let F=c(S,A)+x;F<=0?S.delete(A):S.set(A,F)},m=S=>c(l,S)<r,u=S=>o<t&&m(S),f=S=>(o+=1,s(l,S,1),b(S)),h=()=>{let S=-1,A=r;for(let[x,F]of a.entries()){let E=c(l,F.owner);if(E<A&&(S=x,A=E,E===0))break}return S},R=()=>{for(;o<t;){let S=h();if(S<0)return;let[A]=a.splice(S,1);s(i,A.owner,-1),A.grant(f(A.owner))}},b=S=>{let A=!1;return()=>{A||(A=!0,o-=1,s(l,S,-1),R())}};return{canAcquire:u,acquire:(S,A)=>{if(A.aborted)return Promise.resolve(null);if(u(S))return Promise.resolve(f(S));if(n===null||a.length>=n.max||c(i,S)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:x}=n,F=E=>{let D=()=>{let de=a.indexOf(H);de<0||(a.splice(de,1),s(i,S,-1),M(),E(null))},$=Ve(D,x),M=()=>{clearTimeout($),A.removeEventListener("abort",D)},H={owner:S,grant:de=>{M(),E(de)}};a.push(H),s(i,S,1),A.addEventListener("abort",D,{once:!0})};return new Promise(F)}}};var Zl=1024,_n="Too many requests",ec=(e,t)=>{te("limitPerWindow",e,1),te("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let c=l??{tokens:e,lastRefillMs:i};n(c,i),r.set(a,c);for(let s of r.keys()){if(r.size<=Zl)break;r.delete(s)}return c};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let c=r.get(a);c&&(n(c,i),c.tokens=Math.min(e,c.tokens+l))}}},tt=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(te("windowMs",r,1e3)%1e3!==0)throw ne("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=ec(e.limitPerWindow,r),i=Object.freeze({status:429,message:_n,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Fe({windowMs:r,tallies:[t],writeSuppressed:(c,{count:s,since:m})=>{n.warn(`${t}_suppressed count=${s} since=${m} ${o(c)}`)}});return{spend:(c,s)=>a.consume(c,ue())?null:(l.record(c,t,()=>n.warn(`429 ${s} reason=${t}`)),i),refund:(c,s)=>{a.refund(c,ue(),s)}}};var rc=256*1024,Jo=6e4,nc=e=>Math.ceil(e/2),oc=new Uint8Array(new ArrayBuffer(0)),ac=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=oc,t()},i=l=>{clearTimeout(o),o=Ve(()=>{l.error(new Error(`attachment body idle for ${Jo} ms`)),a()},Jo)};return new ReadableStream({start(l){i(l)},pull(l){let c=Math.min(n+rc,r.byteLength);if(c>n&&l.enqueue(r.slice(n,c)),n=c,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},Qo=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=tt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:c=>`viewer=${c}`}),l=We({limit:e.concurrency,maxHeldPerOwner:nc(e.concurrency),queue:null});return async c=>{let{request:s,delivery:m,attachmentId:u,internalUserId:f,readAttachment:h,cookie:R,fail:b}=c,S=e.maxBytes,A=i.spend(f,`attachment=${u} viewer=${f}`);if(A)return b(A.status,A.message,A.headers);let x=await n(s),F=await t.getAttachmentForUser(x,u,f);if(!F)return o.warn(`404 attachment=${u} viewer=${f} reason=not_visible`),b(404,"Attachment not found");if(F.fileSize!=null&&F.fileSize>S)return o.warn(`413 attachment=${u} viewer=${f} reason=db_size`),b(413,"Attachment too large");let E=In(F.fileType),D=`filename="${Go(F.fileName)}"; filename*=UTF-8''${zo(F.fileName)}`,$=await l.acquire(f,s.signal);if(!$)return s.signal.aborted?(o.info(`503 attachment=${u} viewer=${f} reason=aborted`),b(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${f} reason=concurrency`),b(503,"Too many concurrent downloads",Me(503)));let M=!1;try{let H=await h(F.filePath,{maxBytes:S,head:s.method==="HEAD",principal:r(f),signal:s.signal});if(s.signal.aborted)return o.info(`503 attachment=${u} viewer=${f} reason=aborted`),b(503,"Attachment request aborted");if(!H.ok){if(!yr(H.reason))return o.error(`500 attachment=${u} viewer=${f} reason=port_contract code=failure_reason`),b(500,et);let me=hr(H.reason);return H.reason==="not_found"&&a(u,!1),o.warn(`${me} attachment=${u} viewer=${f} reason=${H.reason} code=${H.code??"-"}`),b(me,mr[me],Me(me))}if(H.bytes.byteLength>S)return o.error(`500 attachment=${u} viewer=${f} reason=port_contract code=over_max_bytes`),b(500,et);let de=s.method==="HEAD";if(de&&H.size!==void 0&&H.size>S)return o.error(`500 attachment=${u} viewer=${f} reason=port_contract code=over_max_bytes`),b(500,et);if(!de&&H.size!==void 0&&H.size!==H.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${f} reason=port_contract code=size_mismatch`),b(500,et);let pe=E??In(H.contentType),ge=pe!==null&&Wo.has(pe),G=ge?pe:"application/octet-stream",se=ge&&m.kind!=="download"?"inline":"attachment",re=de?H.size:H.bytes.byteLength,ce=new Headers({"Content-Type":G,"Content-Disposition":`${se}; ${D}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...xt});return re!==void 0&&ce.set("Content-Length",String(re)),R&&ce.append("Set-Cookie",R),a(u,!0),o.info(`200 attachment=${u} viewer=${f} type=${G} disposition=${se} bytes=${re??"-"}`),de?new Response(null,{status:200,headers:ce}):(M=!0,new Response(ac(H.bytes,$),{status:200,headers:ce}))}finally{M||$()}}};var Pe=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),hy=Pe.queueWaitMs+Pe.readMs+Pe.renderMs+Pe.transferMarginMs;import{Buffer as ic}from"buffer";var ea=new Set([194,198,202,206]),sc=new Set([192,193,194,195]),ta=216,lc=217,ra=218,cc=4,uc=64,dc=2,Xo=8,Zo=28,ct=12,xn=8,pc=20,na=ct+xn+10,mc=2,rt=(e,t)=>e[t]<<8|e[t+1],Ct=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},ze=(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},oa=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,aa=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),ia=e=>(e.stepsLeft-=1,e.stepsLeft>=0),sa=e=>e[0]===255&&e[1]===ta,la=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!ia(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===lc)return"eoi";if(o===0||o===ta)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")}},yc=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!ia(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}},ca=(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 c=0;c<i;c+=1){let s=e[r+7+3*c],m=s>>4,u=s&15;if(m<1||m>4||u<1||u>4)return null;l.push({id:e[r+6+3*c],horizontal:m,vertical:u})}return{marker:t,width:a,height:o,components:l}},ua=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>cc||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},da=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:ea.has(e.marker)||t<e.components.length}),Cn=e=>{if(!sa(e))return null;let t=aa(e.byteLength),r=null;for(let n=2;;){if(la(e,n,t)!=="segment")return null;if(oa(t.marker)){if(r!==null||(r=ca(e,t),r===null))return null}else if(t.marker===ra){if(r===null)return null;let o=ua(e,t);return o===null?null:da(r,o.length)}n=t.end}},pa=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*Xo)),i=Math.ceil(e.height*o/(r*Xo));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},ma=e=>e.multiScan?pa(e).reduce((r,n)=>r+n,0)*uc*dc:0,hc=896,ya=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!sa(e))return null;let n=ic.from(e.buffer,e.byteOffset,e.byteLength),o=aa(r),a=null,i=null,l=new Map,c=0,s=0,m=0;for(let u=2;;){let f=la(e,u,o);if(f===null)return null;if(f==="eoi")return i===null?null:{header:i,blockVisits:s};if(u=o.end,oa(o.marker)){if(a!==null||!sc.has(o.marker)||(a=ca(e,o),a===null))return null;let h=pa(a);l=new Map;for(let[R,b]of a.components.entries()){let S=l.get(b.id);l.set(b.id,S===void 0?h[R]:Math.max(S,h[R]))}c=a.components.length*(ea.has(a.marker)?hc:1)}else if(o.marker===ra){if(a===null||m===c)return null;let h=ua(e,o);if(h===null)return null;for(let b of h){let S=l.get(b);if(S===void 0)return null;s+=S}if(m+=1,i===null&&(i=da(a,h.length)),s>t||!i.multiScan)return{header:i,blockVisits:s};let R=yc(n,o.end,o);if(R===null)return null;u=R}}},ha=e=>{if(e.byteLength<24||rt(e,8)!==0||rt(e,10)!==13||!ze(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}},fc=e=>{if(ze(e,ct,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Ct(e,26,2)&16383,r=Ct(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(ze(e,ct,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Ct(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return ze(e,ct,"VP8X")?e.byteLength<na?null:{width:Ct(e,24,3)+1,height:Ct(e,27,3)+1}:null},fa=e=>{if(ha(e)===null||e.byteLength<=Zo)return null;switch(e[Zo]){case 0:return!1;case 1:return!0;default:return null}},Ra=(e,t)=>{if(ze(e,ct,"VP8 "))return"lossy";if(ze(e,ct,"VP8L"))return"lossless";if(!ze(e,ct,"VP8X")||e.byteLength<na)return null;if((e[pc]&mc)!==0)return"animated";let r=!1,n=t;for(let o=ct;o+xn<=e.byteLength;){if(n-=1,n<0)return null;if(ze(e,o,"VP8L"))return"lossless";if(ze(e,o,"VP8 "))return r?"lossy-alpha":"lossy";ze(e,o,"ALPH")&&(r=!0);let a=Ct(e,o+4,4);o+=xn+a+a%2}return null},Sa={png:ha,jpeg:Cn,webp:fc};var Mn=Object.freeze(["image/webp","image/jpeg","image/png"]),Pn=1024*1024;var Rc=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Sc={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},gc=new Set(Mn),bc=e=>typeof e=="string"&&gc.has(e),Dc=256,fr=(e,t)=>e.fileType===null||!Rc.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Ac=[137,80,78,71,13,10,26,10],Tc=[255,216,255],Ec=[[71,73,70,56,55,97],[71,73,70,56,57,97]],wc=[82,73,70,70],Ic=[87,69,66,80],Bt=(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},Ln=e=>{if(Bt(e,Ac,0))return"png";if(Bt(e,Tc,0))return"jpeg";for(let t of Ec)if(Bt(e,t,0))return"gif";return Bt(e,wc,0)&&Bt(e,Ic,8)?"webp":null},ga=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:Ho([t])}},ba=(e,t)=>{if(!bc(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Pn)return"too_large";let r=Sc[e.contentType];if(Ln(e.bytes)!==r)return"signature";let n=Sa[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Da=e=>{te("maxBytes",e.maxBytes,0),te("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+Dc;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let c of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(c)}}}};var Nn=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ue(),l=new AbortController,c=!1,s,m,u=()=>{a(ue()-i)},f=E=>{s=Ve(()=>{c=!0,E({timedOut:!0}),m=Ve(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},h=new Promise(f),R=AbortSignal.any([r,l.signal]),b=E=>{E(n(R))},S=new Promise(b),A=E=>(clearTimeout(s),clearTimeout(m),c&&o(ue()-i,E.kind==="error"?{error:E.error}:null),E),x=S.then(E=>A({kind:"value",value:E}),E=>A({kind:"error",error:E}));return{outcome:Promise.race([S.then(E=>({timedOut:!1,value:E})),h]),settled:x}};var ut={404:"Attachment not found",500:et,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Aa=(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=ba(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},_c=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ve(r,Pe.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Ta=()=>{},xc=(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)}),Ea=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,c=(h,R)=>{let b=R.then(Ta,Ta);l.set(h,b);let S=()=>{l.get(h)===b&&l.delete(h)};b.then(S)},s=async(h,R)=>{let b=l.get(h.key);if(b===void 0)return t.acquire(h.owner,R);let S=_c(R);try{if(await xc(b,S.signal),S.signal.aborted)return null;let A=r.get(h.key);return A!==void 0?{...A,identity:"verified"}:await t.acquire(h.owner,S.signal)}finally{S.end()}},m=(h,R)=>{if(h.fileSize===null)return R.kind==="exact"?"verified":"unrecorded";if(R.kind==="exact"?R.bytes===h.fileSize:h.fileSize>R.maxBytes)return"verified";let S=R.kind==="exact"?String(R.bytes):`>${R.maxBytes}`;return i.warn(`size_mismatch expected=${h.fileSize} got=${S} attachment=${h.attachmentId} viewer=${h.owner} variant=thumbnail`),"unverified"},u=(h,R)=>(b,S)=>{let A=S===null?"":` message=${S.error instanceof Error?S.error.message:"unknown"}`;i.warn(`${h}_overrun ms=${b} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail${A}`)},f=(h,R)=>b=>{i.warn(`${h}_stuck ms=${b} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail`)};return async(h,R)=>{let b=await s(h,R);if(b===null)return{kind:"failure",status:503,reason:R.aborted?"aborted":"queue"};if(typeof b!="function")return b;let S=b,A=null;try{if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let x=r.get(h.key);if(x!==void 0)return{...x,identity:"verified"};let F=Nn({budgetMs:Pe.readMs,flightSignal:R,call:me=>h.readAttachment(h.filePath,{maxBytes:n,head:!1,principal:o(h.owner),signal:me}),onOverrun:u("read",h),onStuck:f("read",h)}),E=await F.outcome;if(E.timedOut)return A=F.settled,R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let D=E.value;if(!D.ok&&D.reason!=="too_large")return yr(D.reason)?(D.reason==="not_found"&&a(h.attachmentId,!1),{kind:"failure",status:hr(D.reason),reason:D.reason,code:D.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(D.ok&&D.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let $=m(h,D.ok?{kind:"exact",bytes:D.bytes.byteLength}:{kind:"over",maxBytes:n}),M=me=>{$==="verified"&&r.set(h.key,me)},H=me=>(M(me),{...me,identity:$});if(!D.ok)return H({kind:"unrenderable",reason:"too_large"});let de=Ln(D.bytes);if(de===null)return H({kind:"unrenderable",reason:"signature"});let pe=Nn({budgetMs:Pe.renderMs,flightSignal:R,call:me=>h.renderer.render(D.bytes,{format:de,maxWidth:h.box.maxWidth,maxHeight:h.box.maxHeight,signal:me}),onOverrun:u("render",h),onStuck:f("render",h)}),ge=me=>{if(me.kind==="error")return;let he=Aa(me.value,h.box);"entry"in he&&M(he.entry)},G=null,se=()=>(G===null&&(G=pe.settled.then(ge),c(h.key,G)),G);R.addEventListener("abort",se,{once:!0});let re=await pe.outcome.finally(()=>R.removeEventListener("abort",se));if(re.timedOut||R.aborted)return A=se(),R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let ce=Aa(re.value,h.box);return"entry"in ce?H(ce.entry):ce.failure}finally{A===null?S():A.then(S,S)}}};var wa=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let c=new AbortController,s=()=>{e.get(t)?.controller===c&&e.delete(t)},u={promise:n(c.signal).finally(s),controller:c,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 xa=10,Cc=1/xa,Ia=1-Cc,Mc=1024,Pc=64,Lc=8,_a="private, no-cache",Nc="no-store",kc=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),vc=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Ca=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:c}=l,s=(E,D)=>tt({reason:E,limitPerWindow:D,windowMs:6e4,logger:o,windowFields:$=>`viewer=${$} variant=thumbnail`}),m=s("rate_limit",l.rateLimitPerMinute),u=s("revalidation_rate_limit",l.rateLimitPerMinute*xa),f=We({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Pc,maxPerOwner:Lc,maxWaitMs:Pe.queueWaitMs}}),h=Da({maxBytes:l.cacheBytes,maxEntries:Mc}),R=wa(),b=Ea({gate:f,cache:h,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),S=(E,D,$,M)=>{let H=`attachment=${E.attachmentId} viewer=${E.internalUserId} variant=thumbnail cache=${M}`;if(D.kind==="failure")return o[vc(D)](`${D.status} ${H} reason=${D.reason} code=${D.code??"-"}`),E.fail(D.status,ut[D.status],Me(D.status));let de=kc[D.identity];if(D.kind==="unrenderable")return o.info(`404 ${H} reason=${D.reason}${de}`),E.fail(404,ut[404]);let pe=D.identity==="verified"?{"Cache-Control":_a,ETag:$}:{"Cache-Control":Nc},ge=new Headers({"Content-Type":D.contentType,"Content-Length":String(D.bytes.byteLength),...pe,"Content-Security-Policy":"default-src 'none'; sandbox",...xt});return E.cookie&&ge.append("Set-Cookie",E.cookie),o.info(`200 ${H} type=${D.contentType} bytes=${D.bytes.byteLength}${de}`),new Response(D.bytes,{status:200,headers:ge})},A=(E,D)=>{let $=E.spend(D.internalUserId,`attachment=${D.attachmentId} viewer=${D.internalUserId} variant=thumbnail`);return $===null?null:D.fail($.status,$.message,$.headers)},x=E=>A(m,E),F=(E,D)=>D?A(u,E):x(E);return async(E,D)=>{let{request:$,attachmentId:M,internalUserId:H,readAttachment:de,cookie:pe,fail:ge}=E,G=Sn[D],se=$.headers.get("If-None-Match"),re=se!==null,ce=F(E,re);if(ce)return ce;let me=await n($),he=await t.getAttachmentForUser(me,M,H),oe=he!==null&&fr(he,i)?ga({rendererId:c.id,box:G,attachmentId:M,filePath:he.filePath,fileType:he.fileType,fileSize:he.fileSize}):null;if(oe&&Dn(se,oe.etag)){let T=new Headers({"Cache-Control":_a,ETag:oe.etag,...xt});return pe&&T.append("Set-Cookie",pe),o.info(`304 attachment=${M} viewer=${H} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:T})}if(re){let T=x(E);if(T)return T}if(!he)return o.warn(`404 attachment=${M} viewer=${H} variant=thumbnail reason=not_visible`),ge(404,ut[404]);if(!oe)return m.refund(H,Ia),o.info(`404 attachment=${M} viewer=${H} variant=thumbnail reason=not_eligible`),ge(404,ut[404]);let{key:ke,etag:Ue}=oe,it=h.get(ke);if(it)return m.refund(H,Ia),S(E,{...it,identity:"verified"},Ue,"hit");let st=T=>b({key:ke,attachmentId:M,filePath:he.filePath,fileSize:he.fileSize,box:G,owner:H,readAttachment:de,renderer:c},T),Ee;try{Ee=await R.join(ke,$.signal,st)}catch(T){return o.error(`500 attachment=${M} viewer=${H} variant=thumbnail cache=miss reason=port_exception message=${T instanceof Error?T.message:"unknown"}`),ge(500,ut[500])}return S(E,Ee,Ue,"miss")}};var Oc='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Fc=()=>pr(403,wn,{cookie:null}),Ma=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=gn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>pr(404,mr[404],{cookie:null}),crossSiteRejection:Fc}),Pa=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:jo(r,a)},c=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Qo({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Ca({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:s,params:m})=>{let u=null,f=(h,R,b={})=>pr(h,R,{cookie:u,extraHeaders:b});try{let{user:h,cookie:R}=await t(s,{failureRedirect:null});if(u=R??null,!h)return f(401,"Unauthorized");let b=gn(new URL(s.url).searchParams);if(b.kind==="invalid")return f(400,"Invalid attachment request");if(b.kind==="thumbnail"&&s.method!=="GET")return f(405,"Method not allowed",{Allow:"GET"});if(s.method!=="GET"&&s.method!=="HEAD")return f(405,"Method not allowed",{Allow:"GET, HEAD"});if(c===null)return f(404,"Attachment not found");if(m.token===void 0)throw new Error(Oc);let S=c.idCodec.decode(m.token);if(S===null||!lt(S))return f(400,"Invalid attachment token");let A=await r.getUserIdByExternalId(h.id);if(!A)return f(403,"Forbidden");let x={request:s,delivery:b,attachmentId:S,internalUserId:A,readAttachment:c.read,cookie:u,fail:f};return b.kind!=="thumbnail"?await c.serveOriginal(x):c.serveThumbnail===null?f(404,ut[404]):await c.serveThumbnail(x,b.variant)}catch(h){if(h instanceof Response)throw h;return a.error(`500 attachment=? viewer=? reason=unexpected message=${h instanceof Error?h.message:"unknown"}`),f(500,et)}}};var Hc=32*1024*1024,Uc=60,$c=4,Bc=120,Vc=2,qc=8*1024*1024,Rr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yc=e=>{if(e===void 0)throw Qe("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Rr(e))throw ne("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Qe("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw ne("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw ne("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},jc=e=>{if(e===void 0)return null;if(!Rr(e))throw ne("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:Yc(e.renderer),rateLimitPerMinute:ht("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Bc),concurrency:ht("attachments.thumbnails.concurrency",e.concurrency,1,Vc),cacheBytes:ht("attachments.thumbnails.cacheBytes",e.cacheBytes,0,qc)})},La=e=>{let t=e;if(t===void 0)return null;if(!Rr(t))throw ne("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Qe("attachments.idCodec","injected when attachments is given");if(!Rr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw ne("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Qe("attachments.read","injected when attachments is given");if(typeof n!="function")throw ne("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:ht("attachments.maxBytes",t.maxBytes,1,Hc),rateLimitPerMinute:ht("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,Uc),concurrency:ht("attachments.concurrency",t.concurrency,1,$c),thumbnails:jc(t.thumbnails)})},Wc=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"]]),Sr=e=>{for(let[t,r]of Wc)if(Object.hasOwn(e,t))throw Qe(r,`given in place of the flat key ${t}`)};var ka=8,zc=8*ka,Gc=128,Kc=2,va=Kc*Gc,Jc=4*va,Qc=6e4,Xc=6e4,Zc="Too many reads",Na=Object.freeze(Object.keys(St).filter(e=>St[e].admission.includes("miss-gate"))),Oa=e=>{let t=We({limit:zc,maxHeldPerOwner:ka,queue:{max:Jc,maxPerOwner:va,maxWaitMs:Qc}}),r=Fe({windowMs:Xc,tallies:Na,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Na.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}})}},gr=(e,t,r)=>{let n=e(t,r,{error:{message:Zc}},503);for(let[o,a]of Object.entries(Me(503)))n.headers.set(o,a);return n};var eu=/^[0-9a-f]{1,16}$/,tu=e=>lt(e.reportHubId)&&(e.businessDate===null||or(e.businessDate)),ru=e=>typeof e=="string"&&eu.test(e);var Fa=e=>{let t=e.get(Re.cursorReportHubId),r=e.get(Re.cursorBusinessDate),n=e.get(Re.cursorSnapshot),o=ru(n)?n:null,a=null;if(t!==null){let l=Be(t);if(l===null)return{refused:"cursor"};let c={businessDate:r,reportHubId:l};if(!tu(c))return{refused:"cursor"};a=c}else if(r!==null)return{refused:"cursor"};let i=Ut(e.get(Re.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var br=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,nu=2,ou=16,au=nu*ou,iu=6e4,Ha=()=>{},su=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Ua=e=>{let t=We({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:au,queue:null}),r=Fe({windowMs:iu,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 Ha;if(a.aborted){if(t.canAcquire(n))return Ha}else{let i=await t.acquire(n,a);if(i!==null)return su(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var Dr=30,Ya=4e3,lu="stream interrupted by server error",cu="Too many streams",uu=15e3,ja=Symbol("ids-stream-heartbeat"),$a=()=>{},Ba=e=>e.return(void 0).then($a,$a),du=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(ja),uu)}),stop:()=>clearTimeout(e)}};async function*Va(e,t,r,n){let o=t?po(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Ya),e.length),l=_t(e,o,i),c=i>o?e[i-1]:void 0;o=i;let s=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:s||c===void 0?null:{businessDate:c.businessDate,reportHubId:c.reportHubId},isLast:s,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,s)return}}var Wa=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...je});return e&&t.append("Set-Cookie",e),t},qa=(e,t,r,n,o)=>{let a=async(m,u)=>{o(),u&&await Ba(t);try{m.close()}catch{}},i=new TextEncoder,l=!1,c=null,s=new ReadableStream({async pull(m){if(l||r.aborted){await a(m,!0);return}let u=du();try{c===null&&(c=t.next());let f=await Promise.race([c,u.fired]);if(u.stop(),f===ja){if(l||r.aborted){await a(m,!0);return}m.enqueue(i.encode(`
2
+ `));return}c=null;let{value:h,done:R}=f;if(R){await a(m,!1);return}if(l||r.aborted){await a(m,!0);return}m.enqueue(i.encode(`${JSON.stringify(h)}
3
+ `))}catch(f){if(u.stop(),c=null,o(),l||r.aborted)return;f instanceof $e||n.error(`ids-stream emission failed: ${f instanceof Error?f.message:String(f)}`);try{let h={kind:"error",error:lu};m.enqueue(i.encode(`${JSON.stringify(h)}
4
+ `)),m.close()}catch{}}},cancel(){l=!0,o(),Ba(t)}});return new Response(s,{status:200,headers:Wa(e)})},za=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,c,s,m,u,f,h)=>{let R=!1,b=null,S=null,A=new Promise((E,D)=>{b=E,S=D});A.catch(()=>{});let x=t.getDailyReportIdsByExternalId(s,c.id,{forceRefresh:l.forceRefresh,admission:h,onFetchStart:l.cursor?void 0:()=>{R=!0,t.readSseStreamAnchor().then(E=>t.getDailyReportIdsFirstPageByExternalId(s,c.id,Dr).then(D=>({items:D,streamAnchor:E}))).then(E=>b?.(E),E=>S?.(E))}});if(x.catch(()=>{}),l.cursor){let{items:E,streamAnchor:D,snapshot:$}=await x,M=l.snapshot!==null&&l.snapshot===$;return qa(m,Va(E,M?l.cursor:null,Dr,{snapshot:$,restarted:!M,streamAnchor:D}),u,r,f)}let F=(async function*(){let E=await Promise.race([x.then(M=>({kind:"full",source:M}),M=>({kind:"full-error",error:M})),A.then(M=>({kind:"page",page:M}),()=>({kind:"page-error"}))]),D=null,$=!1;if(E.kind==="full")D=E.source;else if(E.kind==="page"){let{items:M,streamAnchor:H}=E.page;if(M.length<Dr){yield{kind:"chunk",..._t(M,0,M.length),nextCursor:null,isLast:!0,total:M.length,streamAnchor:H};return}yield{kind:"chunk",..._t(M,0,M.length),nextCursor:null,isLast:!1,provisional:!0},$=!0}else if(E.kind==="full-error"&&R){let M=await A.catch(()=>null);M&&M.items.length>0&&(yield{kind:"chunk",..._t(M.items,0,M.items.length),nextCursor:null,isLast:!1,provisional:!0})}D===null&&(D=await x),yield*Va(D.items,null,$?Ya:Dr,{snapshot:D.snapshot,streamAnchor:D.streamAnchor})})();return qa(m,F,u,r,f)};return async(l,c,s,m,u,f)=>{let h=Fa(l.searchParams);if("refused"in h)return f(s,c,{error:{message:h.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:R}=h;if(R.forceRefresh){let x=a(m,s,c,f);if(x!==null)return x}let b=br(s),S=await t.getUserIdByExternalId(m.id),A=await n.admit(S,"ids-stream",b);if(A===null){let x=f(s,c,{error:{message:cu}},503);for(let[F,E]of Object.entries(Me(503)))x.headers.set(F,E);return x}if(b.aborted)return new Response(null,{status:200,headers:Wa(c)});try{return await i(R,m,u,c,b,A,S===null?void 0:o.admissionFor(S,ie.idsStream,b))}catch(x){if(A(),x instanceof $e)return gr(f,s,c);throw x}}};import{inArray as pu,sql as Ga}from"drizzle-orm";var mu="",yu=64,hu=e=>e.toLowerCase(),fu=e=>e.trim().toLowerCase();function Ka(e){if(e==null)return null;if(!Array.isArray(e))return new Set;let t=new Set;for(let r of e){if(typeof r!="string")continue;let n=fu(r);n.length>0&&t.add(n)}return t}function Le(e,t){return e===null?!0:t==null?!1:e.has(hu(t))}function Ne(e){return e!==null&&e.size===0}function qt(e,t){if(t!==null)return t.size===0?Ga`1 = 0`:pu(Ga`LOWER(${e})`,[...t])}var Mt,Pt,Vt=class Vt{constructor(t,r){jr(this,Mt);jr(this,Pt);Wr(this,Mt,t),Wr(this,Pt,r)}get visible(){return Ot(this,Mt)===null?null:new Set(Ot(this,Mt))}get commentable(){return Ot(this,Pt)===null?null:new Set(Ot(this,Pt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Ka(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new Vt(n,n);let a=Ka(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new Vt(n,i)}static unrestricted(t){return new Vt(null,null)}};Mt=new WeakMap,Pt=new WeakMap;var He=Vt;function Yt(e){let t=Ja(e.visible),r=Ja(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Ja(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(mu);if(t.length<=yu)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 Qa=(e,t,r,n)=>Le(n.commentable,t)||e.authorUserId!==null&&e.authorUserId===r;import{parseQuerySets as Qu}from"@aiquants/fuzzy-search";import{createHash as Ru}from"crypto";import{setImmediate as Xa}from"timers/promises";import{clusterCountOf as Su,DEFAULT_NORMALIZE_OPTIONS as Tr,InteriorPairs as gu,isAnswerTier as bu,normalizeText as Du,queryNeedles as Au,resolveNormalizeOptions as Tu,toMappedFormsInto as Eu,trimmedRange as wu}from"@aiquants/fuzzy-search/normalize";var Er=`
5
+ `,kn=4e3,Iu=1,ei=new Set([8203,8288,65279,173]),_u=new RegExp(`[${String.fromCodePoint(...ei)}]`,"gu"),xu=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),Cu=/(\s+)/u,Mu=/^\s+$/u,Pu=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,Lu=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]),jt=e=>e.replace(_u,""),ti=e=>{let t=jt(e);if(t.length===e.length)return{text:t,rawIndex:null};let r=new Uint32Array(t.length),n=0;for(let o=0;o<e.length;o++)ei.has(e.charCodeAt(o))||(r[n++]=o);return{text:t,rawIndex:r}},vn=e=>Du(e,Tr),Ar=e=>vn(jt(e)),Nu=Tu({...Tr,convertRomaji:!0},"[daily-report] search reading options"),ku=3,vu=/^[-ー]+/u,Ou=/[^\p{L}\p{M}]/gu,Fu=/ー{2,}/gu,Hu=/\p{Script=Latin}/u,Za=/(?=\p{L})\p{Script=Latin}/u,Uu=e=>Su(e.replace(vu,"").replace(Ou,"").replace(Fu,"\u30FC")),$u=(e,t)=>{for(let r of t)if(!bu(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})`)},ri=e=>{if(!Za.test(e))return[];let t=Ar(e);if(!Za.test(t))return[];let r=Au(t,Nu,!1);$u(t,r);let n=[];for(let o of r){if(o.tier===ft.word)continue;let a=Ar(o.text);if(!(a.length===0||a.length>_e.maxWordLength)&&!(a===t||Hu.test(a))&&!(Uu(a)<ku||n.includes(a))&&(n.push(a),n.length===rn))break}return n},ni=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},Bu=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&ni(e,t-1)?t-2:t-1;return Pu.test(String.fromCodePoint(r))&&!Lu.has(e.codePointAt(n))},Vu=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!Bu(e,i);)i--;i===a&&(i=a+r,ni(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}},wr=(e,t)=>{if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let r=[],n=0,o=0,a=0,i=0,l=()=>{i>0&&r.push([{start:a,end:a+i}]),i=0};for(let c of e.split(Cu)){let s=o;if(o+=c.length,i+c.length<=t){i===0&&(a=s),i+=c.length;continue}if(l(),Mu.test(c))continue;if(c.length<=t){a=s,i=c.length;continue}let m=Vu(c,s,t);n+=m.forcedCuts,r.push(m.pieces)}return l(),{chunks:r,forcedCuts:n}},On=(e,t)=>{let r=wr(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>vn(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},Fn=(e,t)=>{let r=0;for(let n of e.matchAll(xu))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},qu=(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},oi=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],c=[];for(let s of a){let m=e.slice(s.start,s.end),u=qu(Eu(m,Tr,new gu(0)),m),[f,h]=wu(u.text);i+=u.text.slice(f,h);for(let R=f;R<h;R++)l.push(s.start+u.start[R]),c.push(s.start+u.end[R])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let s=0;s<l.length;s++)n.push(l[s]),o.push(c[s])}}return{text:r,start:n,end:o}},Ir=(e,t=kn)=>{let r=[],n=0;return Fn(jt(e),o=>{let a=On(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(Er),forcedCuts:n}},ai=e=>e.filter(t=>t.length>0).join(Er),Yu=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
6
+ `)},ju=[`\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`],Wu=["","\u30A2","\u4F50"," "],zu=()=>JSON.stringify(ju.map(e=>Ir(e,8))),Gu=e=>`dr-search-v${Iu};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var Ku=async()=>{let e=Ru("sha256");e.update(JSON.stringify(Tr));for(let t of Wu)await Xa(),e.update("\0"),e.update(vn(Yu(t)));return await Xa(),e.update("\0"),e.update(zu()),Gu(e.digest("hex"))},Ju=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},Hn=Ju(Ku);var Xu=/^-+/u,Zu=/\s+/u,ii=e=>{let t=Xu.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},ed=(e,t)=>{let r=[...ii(e).map(n=>({text:n,tier:ft.word})),...t.flatMap(n=>ii(n).map(o=>({text:o,tier:ft.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},td=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),_r=(e,t)=>{if(e.length>_e.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of Qu(jt(e),t).sets){let i=[],l=new Set;for(let s of a.split(Zu)){let m=Ar(s);if(m.length===0)return{ok:!1,reason:"blank-word"};if(m.length>_e.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=ed(m,ri(s)),f=td(u);l.has(f)||(l.add(f),i.push({alternatives:u}))}if(i.length>_e.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let c=JSON.stringify([...l].sort());n.has(c)||(n.add(c),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>_e.maxSets?{ok:!1,reason:"too-many-sets"}:o>_e.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},Wt=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var Uh=Object.freeze({sourceTypes:null,authors:null,customers:null}),rd=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,si=(e,t,r)=>{if(Eo(e)&&rd(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=_r(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var li=6e4,nd=1,od=3200,ci=2e3,ad=Object.freeze({search:od,reports:ci,"search-marks":ci,"search-facets":null}),id=(e,t)=>{let r=ad[e];return r===null?null:{max:t,maxPerOwner:sr,maxWaitMs:r}},zt=e=>{let{concurrency:t,route:r,logger:n}=e,o=tt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:li,logger:n,windowFields:()=>`route=${r}`}),a=We({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:id(r,t)}),i=Object.freeze({status:429,message:_n,headers:Object.freeze({"Retry-After":String(nd)})}),l=Fe({windowMs:li,tallies:["busy"],writeSuppressed:(c,{count:s,since:m})=>{n.warn(`busy_suppressed count=${s} since=${m} route=${r} concurrency=${t}`)}});return{admit:async(c,s)=>{let m=o.spend(c,r);if(m!==null)return{refusal:m};let u=await a.acquire(c,s);return u!==null?{release:u}:(o.refund(c,1),s.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};import{systemSseRuntime as yd}from"@aiquants/sse";import{createSseResponse as hd,readLastEventId as fd,startSseHeartbeat as Rd,terminalStreamResponse as Sd}from"@aiquants/sse/server";var Gt=(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=Ao.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n,text:r});return{entry:Object.freeze({id:e.id,message:a}),json:n}},sd=["externalComments","postedComments"],ui=new WeakMap,ld=e=>{let t=ui.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return ui.set(e,r),r},di=e=>{let{recipientRawUserId:t,...r}=e;return r},pi=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=ld(e);if(t){if(n.commentsRedacted===null){let o=di(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(sd.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(di(r))),n.recipientRemoved};import{systemSseRuntime as ud}from"@aiquants/sse";import{createSharedSource as dd}from"@aiquants/sse/shared-source";var gt="daily-report:ids:",bt="daily-report:business-date:",xr=(e,t)=>`${e}st:${t}`,Un=e=>`${gt}user:${e}:`,mi=(e,t)=>xr(Un(e),t),cd=e=>`${bt}${e}:`,yi=(e,t)=>xr(cd(e),t),Kt=e=>`daily-report:date:${e}:user:`,Lt=(e,t)=>`${Kt(e)}${t}:`,hi=(e,t,r)=>xr(Lt(e,t),r),Ge=e=>`daily-report:detail:${e}:user:`,Cr=(e,t)=>`${Ge(e)}${t}:`,fi=(e,t,r)=>xr(Cr(e,t),r);var dt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},pd=5e3,md=ur,Jt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=Se(t.logger,1,"SseReader"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return dd({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:ud,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:pd,COUNT:md});if(i)for(let l of i)for(let c of l.messages){a=c.id;let{entry:s,json:m}=Gt(c,this._logger);this._invalidateCaches(m),r.next(s)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(gt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ge(n))}};var gi=Object.freeze({...$t,route:"sse",frameworkDataRefusal:dr}),Ri=864e5,gd={baseMs:2e3,jitterMs:8e3},bi=6e4,$n=ur,Di=JSON.stringify({type:"connected"}),Si="0-0",bd=(e,t,r,n)=>{if(r===null&&n===null)return!0;let o=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Le(r,e.report.sourceType);case"comment-add":case"comment-delete":return Le(n,o??"Internal");case"report-delete":return Le(r,o)}},Dd=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Le(t,e.report.sourceType),Ad=(e,t)=>{e.writeEvent({event:null,id:t,data:Di})},Td=(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||!bd(o,a,r.visibleSet,r.commentableSet)){Ad(e,t.id);return}e.writeEvent({event:null,id:t.id,data:pi(n,Dd(o,r.commentableSet))})},Ai=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:c}=e,s=async(m,u)=>{let{request:f,internalUserId:h,cursor:R}=u,b=u.initialScope.visible,S=u.initialScope.commentable,A=0,x=setInterval(()=>{let G=++A;n(f,"refresh").then(se=>{G===A&&(b=se.visible,S=se.commentable)})},bi);m.onClose(()=>clearInterval(x));let F=R===null?Si:R,E=R!==null&&o!==void 0,D=[],$=null,M=G=>{dt(G.id,F)||(F=G.id,Td(m,G,{internalUserId:h,visibleSet:b,commentableSet:S}))},H=async(G,se)=>{let[re]=await G.xRange(i,"-","+",{COUNT:1});return re!==void 0&&!dt(re.id,se)},de=async(G,se)=>{if(await H(G,se))return!1;let re=se;for(;;){let ce=await G.xRange(i,re,"+",{COUNT:$n}),me=ce[0];if(me!==void 0&&me.id!==re&&await H(G,re))return!1;for(let Ke of ce){if($!==null&&dt($,Ke.id))return!0;dt(Ke.id,F)||M(Gt(Ke,c).entry)}let he=ce.at(-1);if(ce.length<$n||he===void 0||m.isClosed())return!0;re=he.id}},pe=a.subscribe(G=>{if(!E){M(G);return}dt(G.id,F)||($===null&&($=G.id),D.push(G))},G=>{c.error(`[SSE:${h}] Fan-Out reader error:`,G),m.close()});if(m.onClose(pe),R===null){await a.ready();try{let G=await o?.getClient();if(G){let se=await G.xRevRange(i,"+","-",{COUNT:1});se.length>0&&!dt(se[0].id,F)&&(F=se[0].id)}}catch{}}if(m.writeEvent({event:null,id:F===Si?null:F,data:Di}),Rd(m,{intervalMs:So,retry:gd,runtime:yd}),R===null||o===void 0)return;await a.ready();let ge=await o.getClient();if(ge===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await de(ge,R)){m.writeRetry(Ri),m.writeEvent({event:"resync-required",id:null,data:""}),m.close();return}E=!1;for(let G of D.splice(0))M(G)};return async({request:m,params:u})=>{let f,h=()=>{let b=new Headers;f!==void 0&&b.append("Set-Cookie",f);for(let[S,A]of Object.entries(je))b.set(S,A);return b},R=b=>Sd(b,{data:"",retryMs:Ri,headers:h()});try{let b=await t(m,{failureRedirect:null});f=b.cookie;let{user:S}=b;if(!S)return R("auth-required");let A=await r.getUserIdByExternalId(S.id);if(!A)return R("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:h()});let x=fd(m,go);if(x!==null&&!bo(x))return c.warn(`[SSE:${A}] malformed resume cursor; asking the client to resync`),R("resync-required");let F=br(m),E=await l.admit(A,"sse",F);if(E===null){let $=h();for(let[M,H]of Object.entries(Me(503)))$.set(M,H);return new Response("Too many streams",{status:503,headers:$})}let D=!1;try{let $=await n(m,"initial");return hd({requestSignal:F,headers:h(),onError:(M,H)=>c.error(`[SSE:${A}] ${H} failed:`,M),produce:M=>(D=!0,M.onClose(E),s(M,{request:m,internalUserId:A,cursor:x,initialScope:$}))})}finally{D||E()}}catch(b){if(b instanceof Response)throw b;let S=b instanceof Error?b:new Error(String(b));return c.error(`500 sse name=${S.name} message=${S.message}`),new Response("Internal Server Error",{status:500,headers:h()})}}};var Ti=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...je});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Ed=Object.freeze({...$t,route:"api",frameworkDataRefusal:({params:e})=>Rn(e.endpoint)&&St[e.endpoint].body==="stream"?dr():null}),wd=Object.freeze({...$t,route:"action"}),Id=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),xi=6e4,Ci=5,_d=Ci*Math.ceil(xi/500),xd=2,Cd=6,Md=6e4,Pd=Ci*xd*Cd,Ld=2,Nd=10,kd=2,vd=10,Ei=(e,t)=>Math.max(e,sr)*t,Mi=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},Od=Object.freeze({etag:(e,t,r)=>Uo(e,t,r,200),"no-store":(e,t,r)=>An(t,r,200)}),Fd=e=>Tn(e.body==="json"?Od[e.cache]:null),wi=Tn(null),Ii=(e,t,r,n)=>Mi(e(t,r,{error:{message:n.message}},n.status),n.headers),_i=(e,t,r)=>Mi(e(t,r,null,503),Me(503));function Bn(e){Sr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:te("service.titleMaxLength",r.titleMaxLength,1)},c=e.loginRedirectPath??"/auth/login",s=Se(e.logger,3,"API"),m=Se(e.logger,3,"Visibility"),u=Se(e.logger,1,"SSE"),f=Se(e.logger,1,"Attachment"),h=Se(e.logger,2,"Isolation"),R=Se(e.logger,2,"Action"),b=Se(e.logger,2,"Search"),S=Se(e.logger,2,"Refresh"),A=Se(e.logger,2,"Streams"),x=Se(e.logger,2,"Reads"),F=tt({reason:"refresh_rate_limit",limitPerWindow:Pd,windowMs:Md,logger:S,windowFields:()=>"route=api"}),E=Ua(A),D=Oa(x),$=async(T,O,N,P,U,W)=>{let K=await r.getUserIdByExternalId(O.id);try{return await W(K===null?void 0:D.admissionFor(K,T,N.signal))}catch(z){if(z instanceof $e)return gr(U,N,P);throw z}},M=(T,O,N,P,U)=>{let W=F.spend(O.id,`endpoint=${T}`);return W===null?null:Ii(U,N,P,W)},H=async(T,O="initial")=>{let N=e.resolveVisibleSourceTypes;if(!N)return He.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let P=await N(T,{reason:O});return P==null?He.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):He.restrictTo(P)}catch(P){return m.error("resolveVisibleSourceTypes threw; failing closed (deny all)",P),He.restrictTo([])}},de=async({request:T})=>{let{user:O,cookie:N}=await t(T,{failureRedirect:c}),P=new Headers;N&&P.append("Set-Cookie",N);let U=await r.getUserIdByExternalId(O.id),W=U?n(U):null;return{data:{user:O,userId:W},headers:P}},pe=T=>{let{limiter:O}=T;return async(N,P,U,W,K,z)=>{if(O===null)return z(U,P,{error:{message:"Unknown endpoint"}},404);let X=T.parse(N);if(!X.ok)return z(U,P,X.invalid,400);let k=await r.getUserIdByExternalId(W.id);if(!k)return z(U,P,T.emptyAnswer(X.parsed),200);let{signal:ae}=U,fe=await O.admit(k,ae);if("refusal"in fe)return ae.aborted?_i(z,U,P):Ii(z,U,P,fe.refusal);try{ae.throwIfAborted();let ye=await T.read(X.parsed,{userId:k,user:W,scope:K},ae);return ae.throwIfAborted(),z(U,P,ye,200)}catch(ye){if(ae.aborted&&ye===ae.reason)return _i(z,U,P);throw ye}finally{fe.release()}}},ge=r.searchLimits===null?null:zt({...r.searchLimits,route:ie.search,logger:b}),G=r.searchLimits===null?null:zt({concurrency:Ei(r.searchLimits.concurrency,Ld),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Nd,route:ie.reports,logger:b}),se=r.searchLimits===null?null:zt({concurrency:Ei(r.searchLimits.concurrency,kd),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*vd,route:ie.searchMarks,logger:b}),re=r.searchLimits===null?null:zt({...r.searchLimits,route:ie.searchFacets,logger:b}),ce={[ie.businessDate]:async(T,O,N,P,U,W)=>{let K=T.searchParams.get(Re.businessDate),z=K===null?null:It(K);if(z===null)return W(N,O,{error:{message:"Invalid business date"}},400);let X=Ut(T.searchParams.get(Re.forceRefresh));if(X===null)return W(N,O,{error:{message:"Invalid forceRefresh"}},400);let k=X?M(ie.businessDate,P,N,O,W):null;return k!==null?k:$(ie.businessDate,P,N,O,W,async ae=>{let fe=await r.getDailyReportsByBusinessDateByExternalId(U,z,P.id,{forceRefresh:X,admission:ae});return W(N,O,{businessDate:z,reports:fe},200)})},[ie.idsStream]:za({service:r,logger:s,streamSlots:E,missGate:D,refuseForcedRead:(T,O,N,P)=>M(ie.idsStream,T,O,N,P)}),[ie.report]:async(T,O,N,P,U,W)=>{let K=Be(T.searchParams.get(Re.reportHubId));if(K===null)return W(N,O,{error:{message:"Invalid reportHubId"}},400);let z=Ut(T.searchParams.get(Re.forceRefresh));if(z===null)return W(N,O,{error:{message:"Invalid forceRefresh"}},400);let X=z?M(ie.report,P,N,O,W):null;return X!==null?X:$(ie.report,P,N,O,W,async k=>{let ae=await r.getDailyReportDetailByIdByExternalId(U,K,P.id,{snapshot:!0,forceRefresh:z,admission:k});return ae?W(N,O,{report:ae},200):W(N,O,{error:{message:"Report not found"}},404)})},[ie.search]:pe({limiter:ge,parse:T=>{let O=T.searchParams.get(Re.searchQuery),N=hn(T.searchParams.get(Re.searchCombine));if(O===null||N===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let P=Io(T.searchParams,r.searchFilterSourceTypes);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:P.reason}}};let U=si(O,N,P.filters);if(!U.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:U.reason}}};let{criteria:W}=U;return{ok:!0,parsed:{criteria:W,words:W.plan===null?[]:Wt(W.plan)}}},emptyAnswer:({words:T})=>nn([],T),read:async({criteria:T,words:O},{userId:N,scope:P})=>nn(await r.searchDailyReports(P,N,T),O)}),[ie.reports]:pe({limiter:G,parse:T=>{let O=fn(T.searchParams.get(Re.reportIds));return O===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:O}},emptyAnswer:()=>({reports:[]}),read:async(T,{user:O,scope:N})=>({reports:await r.getDailyReportDetailsByIdsByExternalId(N,T,O.id)})}),[ie.searchMarks]:pe({limiter:se,parse:T=>{let O=T.searchParams.get(Re.searchQuery),N=hn(T.searchParams.get(Re.searchCombine));if(O===null||N===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let P=_r(O,N);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:P.reason}}};let U=fn(T.searchParams.get(Re.reportIds));return U===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:P.plan,ids:U}}},emptyAnswer:({plan:T})=>({wordsDigest:ir(Wt(T)),reports:[],deferred:[]}),read:({plan:T,ids:O},{userId:N,scope:P},U)=>r.markDailyReportSearchHits(P,N,T,O,{signal:U})}),[ie.searchFacets]:pe({limiter:re,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(T,{userId:O,scope:N})=>r.listDailyReportSearchFacets(N,O)})},me=async({request:T,params:O})=>{let{user:N,cookie:P}=await t(T,{failureRedirect:null}),U=P??null;if(!N)return wi(T,U,{error:{message:"Unauthorized"}},401);let W=O.endpoint;if(!Rn(W))return wi(T,U,{error:{message:"Unknown endpoint"}},404);let K=St[W],z=Fd(K),X=Oo[K.body];if(!X.includes(T.method)){let ae=z(T,U,{error:{message:"Method not allowed"}},405);return ae.headers.set("Allow",X.join(", ")),ae}let k=ue();try{let ae=new URL(T.url),fe=await H(T),ye=await ce[W](ae,U,T,N,fe,z);return K.body==="json"&&s.debug(ye.headers.has("ETag")?`${ye.status} endpoint=${W} etag_match=${ye.status===304}`:`${ye.status} endpoint=${W}`),ye}catch(ae){let fe=ue()-k,ye=ae instanceof Error?ae:new Error(String(ae));return s.error(`500 endpoint=${W} elapsed=${fe}ms name=${ye.name} code=${"code"in ye?ye.code:"N/A"} message=${ye.message}`,ye),z(T,U,{error:{message:"Internal Server Error"}},500)}},he=vo(R),Ke=tt({reason:"rate_limit",limitPerWindow:_d,windowMs:xi,logger:R,windowFields:()=>"route=action"}),oe=async(T,O,N,P,U)=>{let{clientTempId:W}=T;if(T.intent==="create"){let k=await r.createDailyReport(O,T.businessDate,W);return U(T,k.reportHubId,{report:k})}let{reportHubId:K,businessDate:z}=T,X=async(k,ae)=>{try{let fe=await ae(k.value);return U(k,K,{updatedStatus:{isStarred:fe.isStarred,isRead:fe.isRead},operationTimestamp:k.operationTimestamp})}catch(fe){if(fe instanceof Error&&fe.message==="Not Found")return P({error:"Report not found"},{status:404});throw fe}};switch(T.intent){case"update":try{return await r.updateDailyReport(K,O,T.changes,W),U(T,K,{})}catch(k){if(k instanceof Error){if(k.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(k.message==="Not Found")return P({error:"Report not found"},{status:404})}throw k}case"publish":try{let k=await r.publishDailyReport(K,O,W);return U(T,K,{report:k})}catch(k){if(k instanceof Error){if(k.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(k.message==="Not Found")return P({error:"Report not found"},{status:404})}throw k}case"delete":try{return await r.deleteDailyReport(K,O,W),U(T,K,{})}catch(k){if(k instanceof Error){if(k.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(k.message==="Not Found")return P({error:"Report not found"},{status:404})}throw k}case"toggleStar":return await X(T,k=>r.setStarStatus(N,O,K,z,k,W));case"toggleRead":return await X(T,k=>r.setReadStatus(N,O,K,z,k,W));case"addComment":try{let k=await r.addComment(N,O,K,T.content,z,W);return U(T,K,{newComment:k})}catch(k){if(k instanceof Error){if(k.message==="Not Found")return P({error:"Report not found"},{status:404});if(k.message.startsWith("Comments are restricted"))return P({error:"Comments are restricted for this report"},{status:403})}throw k}case"deleteComment":try{return await r.deleteComment(N,O,K,T.commentId,z,W),U(T,K,{deletedCommentId:T.commentId})}catch(k){if(k instanceof Error){if(k.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(k.message==="Not Found")return P({error:"Comment not found"},{status:404})}throw k}}},ke=async({request:T,params:O})=>{let{user:N,cookie:P}=await t(T,{failureRedirect:null}),U=(z,X)=>Ti(z,{...X,setCookie:P}),W=(z,X,k)=>Ti(Id(z,X,k),{setCookie:P});if(!N)return U({error:"Unauthorized"},{status:401});let K=ue();try{if(O.endpoint!==ie.action)return U({error:"Unknown endpoint"},{status:404});let z=Ke.spend(N.id,"action");if(z!==null)return U({error:z.message},{status:z.status,headers:z.headers});let X=await ko(T,l);if("refusal"in X){let{refusal:ye}=X;return ye.status===413&&he(ye.measuredBy),U({error:ye.error},{status:ye.status})}let{command:k}=X;if(k.intent==="clearCache"&&!e.enableDevCacheClear)return U({error:"Invalid intent"},{status:400});let ae=await r.getUserIdByExternalId(N.id);if(!ae)return U({error:"User not found"},{status:404});let fe=await H(T);return k.intent==="clearCache"?(await r.clearCache(),U({status:"OK",intent:"clearCache"})):await oe(k,ae,fe,U,W)}catch(z){if(z instanceof Response)throw z;let X=ue()-K,k=z instanceof Error?z:new Error(String(z));return s.error(`500 action elapsed=${X}ms name=${k.name} message=${k.message}`,k),U({error:"Internal Server Error"},{status:500})}},Ue=Ai({authenticate:t,service:r,resolveViewerScope:H,redis:o,sseReader:a,streamKey:i,streamSlots:E,logger:u}),it=Pa({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:H,logger:f}),st=Yo(h),Ee=(T,O)=>async N=>{let P=Vo(N.request)?T.frameworkDataRefusal(N):null;if(P!==null)throw P;return qo(N.request,T)?(st(T.route,N.request),T.crossSiteRejection()):O(N)};return{index:{loader:de},api:{loader:Ee(Ed,me),action:Ee(wd,ke)},sse:{loader:Ee(gi,Ue)},attachment:{loader:Ee(Ma,it)}}}import{chunk as yp,MAX_IN_LIST as hp,runWithTransactionRetry as fp}from"@aiquants/mssql";import{and as Ae,asc as Ce,desc as Nt,eq as V,getColumns as Rp,inArray as ot,isNull as kt,sql as Kn}from"drizzle-orm";import{sql as pt}from"drizzle-orm";var Pi=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 pt.join(e.map(t=>pt`${t}`),pt`, `)},Pr=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return pt`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${Pi(t)}))`},Li=(e,t)=>{let{hubLabel:r,label:n}=e;return pt`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${Pi(t)}))`},Lr=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?pt`${o.userId} = ${t} OR ${o.userId} IS NULL`:pt`${o.userId} = ${t}`;return pt`(${a} OR NOT ${Pr(e,r)})`};var Hd=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],Ud=["document","comment"],$d=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],Bd=["hubId","ordinal","authorUserId","commentText"],Vn=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Ni=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw Gr(e,n,r)},ki=(e,t,r)=>{if(typeof t!="object"||t===null)throw ne(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw ne(`${e}.${o}`,"a column",n[o])},vi=(e,t)=>{if(!Vn(e))throw ne("search","a plain object",e);Ni("search key",e,Hd);let{tables:r}=e;if(!Vn(r))throw ne("search.tables","a plain object with document and comment",r);Ni("search.tables key",r,Ud),ki("search.tables.document",r.document,$d),ki("search.tables.comment",r.comment,Bd);let n=new Map;if(e.externalSourceTexts!==void 0){if(!Vn(e.externalSourceTexts))throw ne("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw Gr("search.externalSourceTexts key",o,t);if(typeof a!="function")throw ne(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:te("search.concurrency",e.concurrency,1),rateLimitPerMinute:te("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var mt=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},Dt=(e,t)=>{let r=typeof e=="string"?Be(e):typeof e=="number"&&lt(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},At=(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";var Vd=/[[%_]/gu,qd=e=>e.replace(Vd,t=>`[${t}]`),Oi=e=>`%${qd(e)}%`;var qe=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),Tt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),Xt=Object.freeze({value:"value"}),we=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),Y=e=>B`${B.identifier(e.name)}`,Qt=e=>B.join(e.map(t=>B`${t}`),B`, `),Fi=(e,t)=>B`SELECT ${Y(e.id)} AS ${B.identifier(we.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${Qt(t)}) ORDER BY ${e.id}`,Yd=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>Oi(u.text)),l=B.join(i.map(u=>B`${o.searchText} LIKE ${u}`),B` OR `),c=B.join(i.map(u=>B`${a.commentText} LIKE ${u}`),B` OR `),s=qt(n.sourceType,r.scope.commentable),m=s===void 0?B``:B` AND (${s} OR ${a.authorUserId} = ${r.userId})`;return B`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${c})${m}))`},Hi=(e,t,r)=>B`(${B.join(t.words.map(n=>Yd(e,n,r)),B` AND `)})`,qn=(e,t,r,n)=>{let{hub:o}=e,a=[B`${o.deletedAt} IS NULL`,Lr(e,t.userId,r,"author")],i=qt(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},jd=(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 (${Qt([...t.sourceTypes])})`)}return t.authors!==null&&o.push(B`${n.authorName} IN (${Qt(t.authors)})`),t.customers!==null&&o.push(B`${n.customerName} IN (${Qt(t.customers)})`),o},Ui=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,c=[...qn(e,r,n,o),...jd(e,t.filters)];if(l!==null){let s=l.combine==="intersection"?B` AND `:B` OR `;c.push(B`(${B.join(l.sets.map(m=>Hi(e,m,r)),s)})`)}return B`SELECT ${Y(a.id)} AS ${B.identifier(qe.reportHubId)}, CONVERT(char(10), ${Y(a.businessDate)}, 23) AS ${B.identifier(qe.businessDate)}, ${Y(a.sourceType)} AS ${B.identifier(qe.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(c,B` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},$i=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=B.join(t.sets.map((c,s)=>B`(CASE WHEN ${Hi(e,c,r)} THEN ${2**s} ELSE 0 END)`),B` + `);return B`SELECT ${Y(a.id)} AS ${B.identifier(Tt.reportHubId)}, ${l} AS ${B.identifier(Tt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(qn(e,r,n,o),B` AND `)}`},Bi=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...qn(e,r,n),B`${i} IS NOT NULL`];return B`SELECT ${i} AS ${B.identifier(Xt.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${B.join(l,B` AND `)} GROUP BY ${i} ORDER BY ${i}`},Vi=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(c=>({[n.hubId.name]:c.hubId,[n.searchText.name]:c.searchText,[n.sourceDigest.name]:c.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:c.authorName,[n.customerName.name]:c.customerName}))),i=JSON.stringify(t.flatMap(c=>c.comments.map(s=>({[o.hubId.name]:c.hubId,[o.ordinal.name]:s.ordinal,[o.authorUserId.name]:s.authorUserId,[o.commentText.name]:s.commentText})))),l=JSON.stringify(t.map(c=>c.hubId));return B`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${Y(n.hubId)} bigint, ${Y(n.searchText)} nvarchar(max), ${Y(n.sourceDigest)} char(64), ${Y(n.normalizerVersion)} varchar(64), ${Y(n.authorName)} nvarchar(max), ${Y(n.customerName)} nvarchar(max))) AS s ON t.${Y(n.hubId)} = s.${Y(n.hubId)}
8
+ WHEN MATCHED THEN UPDATE SET t.${Y(n.searchText)} = s.${Y(n.searchText)}, t.${Y(n.sourceDigest)} = CONVERT(binary(32), s.${Y(n.sourceDigest)}, 2), t.${Y(n.normalizerVersion)} = s.${Y(n.normalizerVersion)}, t.${Y(n.authorName)} = s.${Y(n.authorName)}, t.${Y(n.customerName)} = s.${Y(n.customerName)}, t.${Y(n.indexedAt)} = SYSUTCDATETIME()
9
+ WHEN NOT MATCHED THEN INSERT (${Y(n.hubId)}, ${Y(n.searchText)}, ${Y(n.sourceDigest)}, ${Y(n.normalizerVersion)}, ${Y(n.authorName)}, ${Y(n.customerName)}) VALUES (s.${Y(n.hubId)}, s.${Y(n.searchText)}, CONVERT(binary(32), s.${Y(n.sourceDigest)}, 2), s.${Y(n.normalizerVersion)}, s.${Y(n.authorName)}, s.${Y(n.customerName)});
10
10
  DELETE FROM ${o} WHERE ${o.hubId} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${l}));
11
- INSERT INTO ${o} (${U(o.hubId)}, ${U(o.ordinal)}, ${U(o.authorUserId)}, ${U(o.commentText)}) SELECT ${U(o.hubId)}, ${U(o.ordinal)}, ${U(o.authorUserId)}, ${U(o.commentText)} FROM OPENJSON(${i}) WITH (${U(o.hubId)} bigint, ${U(o.ordinal)} int, ${U(o.authorUserId)} bigint, ${U(o.commentText)} nvarchar(max));`},Di=(e,t)=>H`SELECT ${U(e.hubId)} AS ${H.identifier(Ae.hubId)}, LOWER(CONVERT(char(64), ${U(e.sourceDigest)}, 2)) AS ${H.identifier(Ae.sourceDigest)}, ${U(e.normalizerVersion)} AS ${H.identifier(Ae.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${Kt(t)})`,Ai=(e,t,r)=>H`SELECT TOP (${r}) ${U(e.id)} AS ${H.identifier(Ae.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var Ti=e=>({search:async(t,r)=>Le(r.scope.visible)?[]:ut(await t.execute(Ri(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=St(o[Ye.sourceType],Ye.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${Ye.sourceType} is null`);return{reportHubId:Rt(o[Ye.reportHubId],Ye.reportHubId),businessDate:St(o[Ye.businessDate],Ye.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Le(r.scope.visible))return new Map;let n=ut(await t.execute(Si(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[gt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${gt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(Rt(i[gt.reportHubId],gt.reportHubId),l)}return a},facetValues:async(t,r)=>Le(r.scope.visible)?[]:ut(await t.execute(gi(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=St(o[Jt.value],Jt.value);if(a===null)throw new Error(`[daily-report] search: column ${Jt.value} is null`);return a})});import{chunk as Mr,MAX_IN_LIST as Lr}from"@aiquants/mssql";import{sql as Ii}from"drizzle-orm";import{createHash as ad}from"crypto";var id=Object.freeze({authorName:"author",customerName:"customer"}),kn=e=>e===null?null:an(e),Ei=(e,t,r)=>{let n=kn(r);if(n!==null&&n.length>et.maxValueLength){let o=et.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${id[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},Qt=e=>e===null?"n;":`s${e.length}:${e}`,Xt="utf16le",sd=e=>{let t=ad("sha256");t.update(`F${e.fields.length};`,Xt);for(let[r,n]of e.fields)t.update(Qt(r)+Qt(n),Xt);return t.update(`C${e.comments.length};`,Xt),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${Qt(r.text)}`,Xt)}),t.update(`P;${Qt(kn(e.filterValues.authorName))}${Qt(kn(e.filterValues.customerName))}`,Xt),t.digest("hex")},Fn=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=Er(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=Er(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:Va(r),comments:n,sourceDigest:sd(e),forcedCuts:t,authorName:Ei(e.hubId,"authorName",e.filterValues.authorName),customerName:Ei(e.hubId,"customerName",e.filterValues.customerName)}};var _i=e=>{let t=async(c,s)=>{let y=[];for(let m of Mr(s,Lr))for(let S of ut(await c.execute(hi(e.hub,m))))y.push(Rt(S[Ae.hubId],Ae.hubId));return y},r=async(c,s)=>{for(let y of Mr(s,Lr))await c.execute(bi(e.tables,y,e.normalizerVersion))},n=async(c,s)=>{let y=new Map;for(let m of Mr(s,Lr))for(let S of ut(await c.execute(Di(e.tables.document,m))))y.set(Rt(S[Ae.hubId],Ae.hubId),{sourceDigest:St(S[Ae.sourceDigest],Ae.sourceDigest),normalizerVersion:St(S[Ae.normalizerVersion],Ae.normalizerVersion)});return y},o=async(c,s,y)=>ut(await c.execute(Ai(e.hub,s,y))).map(m=>Rt(m[Ae.hubId],Ae.hubId)),a=async(c,s)=>{let y=await t(c,[...new Set(s)].sort((S,f)=>S-f));if(y.length===0)return;let m=(await e.loadSources(c,y)).map(Fn);m.length>0&&await r(c,m)},i=c=>e.inTransaction(async s=>{await s.execute(Ii`SET DEADLOCK_PRIORITY LOW`);let y=await t(s,c),m=await n(s,y),S=(await e.loadSources(s,y)).map(Fn),f=S.filter(R=>{let b=m.get(R.hubId);return b===void 0||b.sourceDigest!==R.sourceDigest||b.normalizerVersion!==e.normalizerVersion});return f.length>0&&await r(s,f),await s.execute(Ii`SET DEADLOCK_PRIORITY NORMAL`),{scanned:S.length,written:f.length,forcedCuts:S.reduce((R,b)=>R+b.forcedCuts,0)}});return{writeHubs:a,reconcile:async(c,s)=>{let{batchSize:y,hubIds:m,signal:S,onProgress:f}=s;ee("reconcileSearchIndex: batchSize",y,1,Lr);let R=ue(),b=m===void 0?null:Mr([...new Set(m)].sort((I,v)=>I-v),y),g={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let I=0;;I++){S?.throwIfAborted();let v=b===null?await o(c,g.lastHubId===null?0:g.lastHubId,y):b[I];if(v===void 0||v.length===0)break;let B=await i(v);g={scanned:g.scanned+B.scanned,written:g.written+B.written,skipped:g.skipped+B.scanned-B.written,forcedCuts:g.forcedCuts+B.forcedCuts,lastHubId:v[v.length-1]},f?.(g)}return{...g,elapsedMs:ue()-R}}}};import{holdsMultiUnitCluster as ld}from"@aiquants/fuzzy-search/normalize";var Hn=255,Nr=Object.values(pt).sort((e,t)=>e-t),cd=new Intl.Segmenter("und",{granularity:"grapheme"}),ud=(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},dd=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length,md=(e,t,r)=>{let n=e.slice(t,r);if(!ld(n))return null;let o=new Int32Array(r-t),a=new Int32Array(r-t);for(let{index:i,segment:l}of cd.segment(n))o.fill(t+i,i,i+l.length),a.fill(t+i+l.length,i,i+l.length);return{start:t,clusterStarts:o,clusterEnds:a}},pd=(e,t,r)=>({start:e.clusterStarts[t-e.start],end:e.clusterEnds[r-1-e.start]}),yd=(e,t,r=Tr)=>{let n=new Map;for(let l of t){if(l.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let c=n.get(l.text);(c===void 0||l.tier<c)&&n.set(l.text,l.tier)}let o=[];if(n.size===0)return o;let a=Ha(e),i=l=>a.rawIndex===null?l:a.rawIndex[l];return Cn(a.text,(l,c)=>{let s=xn(l,r).text,y=null,m=null;for(let[S,f]of n){let R=s.indexOf(S);if(!(R<0)){if(y===null){let b=wn(l,r);y=ud(Ba(l,b),s),m=dd(b,l)?null:md(e,i(c),i(c+l.length-1)+1)}for(;R>=0;){let b=i(c+y.start[R]),g=i(c+y.end[R+S.length-1]-1)+1;m===null?o.push({start:b,end:g,tier:f}):o.push({...pd(m,b,g),tier:f}),R=s.indexOf(S,R+1)}}}}),o},hd=(e,t,r=Tr)=>{let n=yd(e,t,r),o=[];if(n.length===0)return o;let a=Nr.map(()=>new Int32Array(e.length+1));for(let{start:s,end:y,tier:m}of n)a[m][s]++,a[m][y]--;let i=new Int32Array(Nr.length),l=0,c=Hn;for(let s=0;s<=e.length;s++){let y=Hn;for(let m=Nr.length-1;m>=0;m--){let S=Nr[m];i[S]+=a[S][s],i[S]>0&&(y=S)}y!==c&&(c!==Hn&&o.push(l,s,c),l=s,c=y)}return o},wi=(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)},xi=(e,t)=>{let r=t.flatMap(a=>a.alternatives),n={},o=(a,i)=>{typeof i!="string"||i.length===0||(n[a]={fingerprint:Gr(i),ranges:hd(i,r)})};for(let a of eo)o(Ze.field(a),e[a]);e.interviewers.forEach((a,i)=>{o(Ze.interviewer(i,"name"),a.name),o(Ze.interviewer(i,"affiliation"),a.affiliation)}),e.attachments.forEach((a,i)=>{o(Ze.attachment(i),a.fileName)}),e.externalComments.forEach((a,i)=>{o(Ze.comment(jr(i),"author"),a.name),o(Ze.comment(jr(i),"content"),a.text)});for(let a of e.postedComments)o(Ze.comment(a.id,"author"),a.userName),o(Ze.comment(a.id,"content"),a.content);return n};var at=e=>bd(e),Pi=tr([]),we=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),c=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${c}:${s}`},Dd=e=>{let{length:t}=e;if(t===void 0)throw le("tables.hub.title","a character column with a declared length",t);return ee("tables.hub.title.length",t,1)},Mi=e=>e===""?null:e,Ad=Object.freeze([]),Un=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},Or=(e,t)=>e.get(t)??Ad,Li=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Ar),Td=e=>{let t=new Set;return e.filter(r=>{let n=r.toLowerCase();return t.has(n)?!1:(t.add(n),!0)})};function $n(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:c}=e,{hub:s,internal:y,comment:m,label:S,hubLabel:f,userStatus:R}=r,b=e.externalSources??[],g=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],I=g[0]??"\u4E0B\u66F8\u304D",v=fe(e.logger,1,"Service");fr(e);let B=fa(e.attachments),x=Dd(s.title),T=u=>gd(d=>t.transaction(p=>d(()=>u(p))),e.transactionRetry),Y=e.search===void 0?null:pi(e.search,b.map(u=>u.sourceType)),F={hub:s,hubLabel:f,label:S},k=Y===null?null:Ti({tables:{...F,search:Y.tables},draftLabelNames:g}),ce=null,de=()=>{if(Y===null)return null;if(ce===null){let u=Y.externalSourceTexts;ce=_i({hub:s,tables:Y.tables,loadSources:(d,p)=>ys(d,p,u),inTransaction:T,normalizerVersion:Ya()})}return ce},Re=e.idsTtlMs??18e4,z="daily-report:ids:epoch",te=e.businessDateTtlMs??3e5,Z="daily-report:date-epoch:",se="daily-report:detail-epoch:",ye=`${e.streamKey??"daily-report:sse-stream"}:v2`,Qe=e.streamMaxLen??1e4,re=u=>c.incrementEpoch(u),Oe=u=>Bt(s.sourceType,u),Ue=(u,d)=>Pr(F,u,g,d),xe=async(u,d)=>{let p=await i?.getClient();if(!p){v.warn(`[SSE] Redis client unavailable (${d})`);return}let h=JSON.stringify(u),D=Buffer.byteLength(h);if(D>6356992){v.warn(`[SSE] Event too large (${d}): ${D} bytes > ${6356992}; not published`);return}let _=ue();try{await p.xAdd(ye,"*",{data:h},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:Qe}});let P=ue()-_;P>1e3&&v.warn(`[SSE] Slow publish (${d}): ${P}ms`)}catch(P){v.error(`[SSE] Redis publish failed (${d}):`,P)}},We=async()=>{try{let u=await i?.getClient();if(u===void 0)return null;let[d]=await u.xRevRange(ye,"+","-",{COUNT:1});return d===void 0?null:d.id}catch(u){return v.error("SSE stream anchor read failed",u),null}},L=u=>u==null||u===""?null:/^\d+$/.test(u)?a(Number(u)):u,A=()=>{let u={};for(let d of b)u[`ext_${d.sourceType}`]=at(d.table);return u},w=u=>{let d=u;for(let p of b)d=d.leftJoin(p.table,Te($(s.sourceType,p.sourceType),$(s.sourceIdNum,p.idColumn)));return d},V=u=>{let{hub:d,internal:p}=u,h=d.summary,D=[],_=null,P=null,O=null,M=null,j=null,E=null,Q=[],ae=b.find(pe=>pe.sourceType===d.sourceType),ge=ae?u[`ext_${ae.sourceType}`]:void 0;if(ae&&ge){let pe=ae.mapRow(ge);pe.content!==void 0&&(h=pe.content),pe.employeeName!==void 0&&(E=pe.employeeName),pe.category!==void 0&&(_=pe.category),pe.creationCategory!==void 0&&(P=pe.creationCategory),pe.visitTimeFrom!==void 0&&(O=pe.visitTimeFrom),pe.visitTimeTo!==void 0&&(M=pe.visitTimeTo),pe.customerName!==void 0&&(j=pe.customerName),pe.interviewers!==void 0&&(D=pe.interviewers),pe.externalComments!==void 0&&(Q=pe.externalComments)}else d.sourceType==="Internal"&&p&&(h=p.body);return{content:h,author:u.creatorName??L(d.createdBy)??"",employeeName:E??u.creatorName??L(d.createdBy),updatedBy:L(d.updatedBy),category:_,creationCategory:P,visitTimeFrom:O,visitTimeTo:M,customerName:j,interviewers:D,externalComments:Q}},q=(u,d,p)=>{let{hub:h}=d,D=V(d),_=(d.labels??[]).map(E=>({id:E.id,name:E.name,color:E.color})),P=d.postedCommentRows??[],O=Me(u.commentable,h.sourceType),M=D.creationCategory?g.includes(D.creationCategory):!1,j=Ie?.[0]??null;return M&&j&&!_.some(E=>E.id===j)&&_.push({id:j,name:I,color:null}),{reportHubId:h.id,date:we(h.businessDate,"YYYY-MM-DD"),author:D.author,userId:h.userId?a(h.userId):"",sourceType:h.sourceType??"Internal",createdAt:we(h.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:we(h.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:D.updatedBy,employeeName:D.employeeName,category:D.category,creationCategory:D.creationCategory,visitTimeFrom:D.visitTimeFrom,visitTimeTo:D.visitTimeTo,customerName:D.customerName,interviewers:D.interviewers,subject:h.title,content:D.content,externalComments:O?D.externalComments:[],isRead:d.isRead??!1,isStarred:d.isStarred??!1,labels:_,postedComments:P.filter(E=>va({authorUserId:E.userId},h.sourceType,p??null,u)).map(E=>({...E,userId:a(E.userId),isMine:p?E.userId===p:!1})),attachments:d.attachments}},K=async(u,d)=>(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).where(Te(Lt(s.deletedAt),Ue(d,"author-or-authorless"),Oe(u.visible))).orderBy(Mt(s.businessDate),Mt(s.id))).map(h=>({...h,businessDate:we(h.businessDate,"YYYY-MM-DD")})),G=async(u,d,p)=>{let h=await C(d);return h?Le(u.visible)?[]:(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(p).from(s).where(Te(Lt(s.deletedAt),Ue(h,"author-or-authorless"),Oe(u.visible))).orderBy(Mt(s.businessDate),Mt(s.id))).map(_=>({..._,businessDate:we(_.businessDate,"YYYY-MM-DD")})):[]},W=async(u,d)=>{let p=await w(t.select({hub:at(s),internal:at(y),creatorName:n.displayName,...A()}).from(s)).leftJoin(y,$(s.id,y.hubId)).leftJoin(n,$(s.userId,n.id)).where(Te($(s.businessDate,Ci`${d}`),Lt(s.deletedAt),Oe(u.visible))).orderBy(Mt(s.id)),h=await Zt(p.map(D=>D.hub.id));return p.map(D=>q(u,{...D,attachments:h.get(D.hub.id)??[]}))},J=new Map,C=async u=>{if(!e.disableUserIdCache&&J.has(u))return J.get(u)??null;let d=await o(u);return d!==null&&!e.disableUserIdCache&&J.set(u,d),d},oe=async(u,d,{forceRefresh:p=!1,snapshot:h=!1,ttlMsOverride:D,onFetchStart:_,admission:P}={})=>{let O=await C(d);if(!O)return{items:[],streamAnchor:null,snapshot:Pi};if(Le(u.visible))return{items:[],streamAnchor:await We(),snapshot:Pi};let M=Ja(O,Vt(u)),[j]=await l.getOrFetch({cacheKey:M,fetcher:async()=>{let E=await We(),Q=await K(u,O);if(!Kn(Q)){v.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let ae=[...Q].sort(rr);return[{items:ae,streamAnchor:E,snapshot:tr(ae)}]}return[{items:Q,streamAnchor:E,snapshot:tr(Q)}]},onFetchStart:_,forceRefresh:p,snapshot:h,admission:P,ttlMsOverride:D??Re,epochKey:z,refreshAheadRatio:.5});if(j===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return j},Se=(u,d,{forceRefresh:p=!1,snapshot:h=!1,ttlMsOverride:D}={})=>{let _=ve(d);return _?Le(u.visible)?Promise.resolve([]):l.getOrFetch({cacheKey:Qa(_,Vt(u)),fetcher:()=>W(u,_),forceRefresh:p,snapshot:h,ttlMsOverride:D??te}):Promise.resolve([])},Ie=null,Dt=async()=>(Ie!==null||(Ie=(await t.select({id:S.id}).from(S).where(qe(S.name,g)).orderBy(S.id)).map(d=>d.id)),Ie),Fr=async()=>{let u=await Dt();if(u.length===0)return null;let[d]=await t.select({id:S.id}).top(1).from(S).where($(S.name,I));return d?.id??u[0]},Xi=(u,d)=>d!=null?"absent":u!=null?"present":"unknown",Zt=async u=>{let d=new Map,p=r.attachment;if(u.length===0||!p||B===null)return d;let h=B.idCodec,D=B.thumbnails!==null,_=await t.select({id:p.id,hubId:p.hubId,fileName:p.fileName,fileType:p.fileType,fileSize:p.fileSize,createdAt:p.createdAt,objectCheckedAt:p.objectCheckedAt,objectMissingAt:p.objectMissingAt}).from(p).where(qe(p.hubId,u)).orderBy(Ne(p.createdAt),Ne(p.id));for(let P of _){let O=P.fileType?String(P.fileType):null,M=P.fileSize!=null?Number(P.fileSize):null,j=Xi(P.objectCheckedAt,P.objectMissingAt),E={id:h.encode(Number(P.id)),fileName:String(P.fileName),fileType:O,fileSize:M,createdAt:we(P.createdAt,"YYYY-MM-DD HH:mm:ss"),state:j,hasThumbnail:D&&j!=="absent"&&yr({fileType:O,fileSize:M},B.maxBytes)},Q=d.get(Number(P.hubId));Q?Q.push(E):d.set(Number(P.hubId),[E])}return d},Zi=async(u,d,p)=>{let h=r.attachment;return!h||Le(u.visible)?null:(await t.select({fileName:h.fileName,filePath:h.filePath,fileType:h.fileType,fileSize:h.fileSize}).top(1).from(h).innerJoin(s,$(s.id,h.hubId)).where(Te($(h.id,d),Lt(s.deletedAt),Ue(p,"author"),Oe(u.visible))))[0]??null},es=async u=>{let d=r.attachment;if(!d)return;let p=new Date;try{await t.update(d).set({objectCheckedAt:p,objectMissingAt:p,updatedAt:p}).where($(d.id,u))}catch(h){v.error("markAttachmentMissing failed",h)}},ts=async u=>{let d=r.attachment;if(!d)return;let p=new Date;try{await t.update(d).set({objectCheckedAt:p,objectMissingAt:null,updatedAt:p}).where($(d.id,u))}catch(h){v.error("markAttachmentPresent failed",h)}},Hr=async(u,d,p)=>{let h=await w(t.select({hub:at(s),internal:at(y),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,...A()}).from(s)).leftJoin(y,$(s.id,y.hubId)).leftJoin(R,Te($(s.id,R.hubId),$(R.userId,d))).leftJoin(n,$(s.userId,n.id)).where(Te(p,Lt(s.deletedAt),Ue(d,"author"),Oe(u.visible))).orderBy(Mt(s.id));if(h.length===0)return[];let D=h.map(E=>E.hub.id),_=await t.select({hubId:f.hubId,id:S.id,name:S.name,color:S.color}).from(f).innerJoin(S,$(f.labelId,S.id)).where(qe(f.hubId,D)),P=await t.select({hubId:m.hubId,id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,$(m.userId,n.id)).where(qe(m.hubId,D)).orderBy(Ne(m.createdAt)),O=await Zt(D),M=new Map,j=new Map;for(let E of _){let Q=M.get(E.hubId);Q||(Q=[],M.set(E.hubId,Q)),Q.push({id:E.id,name:E.name,color:E.color})}for(let E of P){let Q=j.get(E.hubId);Q||(Q=[],j.set(E.hubId,Q)),Q.push({id:E.id,content:E.body,createdAt:we(E.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:E.userId,userName:E.userName||""})}return h.map(E=>{let Q=E.hub.id;return q(u,{...E,attachments:O.get(Q)??[],labels:M.get(Q)||[],postedCommentRows:j.get(Q)||[]},d)})},rs=async(u,d,p,{forceRefresh:h=!1,snapshot:D=!1,ttlMsOverride:_,admission:P}={})=>{let O=await C(p);if(!O)return[];let M=ve(d);if(!M)return[];if(Le(u.visible))return[];let j=Xa(M,O,Vt(u));return l.getOrFetch({cacheKey:j,fetcher:()=>Hr(u,O,$(s.businessDate,Ci`${M}`)),forceRefresh:h,snapshot:D,admission:P,ttlMsOverride:_??te,epochKey:`${Z}${M}`})},Nt=async(u,d,p,{forceRefresh:h=!1,snapshot:D=!1,ttlMsOverride:_,admission:P}={})=>{if(Le(u.visible))return null;let O=Za(d,p,Vt(u));return(await l.getOrFetch({cacheKey:O,fetcher:async()=>{let j=await w(t.select({hub:at(s),internal:at(y),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,...A()}).from(s)).leftJoin(y,$(s.id,y.hubId)).leftJoin(R,Te($(s.id,R.hubId),$(R.userId,p))).leftJoin(n,$(s.userId,n.id)).where(Te($(s.id,d),Lt(s.deletedAt),Ue(p,"author"),Oe(u.visible)));if(j.length===0)return[];let E=j[0].hub.id,Q=await t.select({id:S.id,name:S.name,color:S.color}).from(f).innerJoin(S,$(f.labelId,S.id)).where($(f.hubId,E)),ae=await t.select({id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,$(m.userId,n.id)).where($(m.hubId,E)).orderBy(Ne(m.createdAt)),ge=await Zt([E]),pe=Q.map(Xe=>({id:Xe.id,name:Xe.name,color:Xe.color})),Is=ae.map(Xe=>({id:Xe.id,content:Xe.body,createdAt:we(Xe.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Xe.userId,userName:Xe.userName||""}));return[q(u,{...j[0],attachments:ge.get(E)??[],labels:pe,postedCommentRows:Is},p)]},forceRefresh:h,snapshot:D,admission:P,ttlMsOverride:_??te,epochKey:`${se}${d}`}))[0]??null},ns=async(u,d,p,h={})=>{let D=await C(p);return D?Nt(u,d,D,h):null},os=async(u,d,p)=>{if(d.length>_e.maxDetailIds)throw le("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${_e.maxDetailIds} ids`,d.length);let h=await C(p);return!h||d.length===0?[]:Le(u.visible)?[]:Hr(u,h,qe(s.id,[...d]))},as=async(u,d)=>{let[p]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).where(Te($(s.id,u),Ue(d,"author")));return p??null},Ur=async(u,d,p)=>{let h=await as(d,p);if(!h||h.deletedAt||!Me(u.visible,h.sourceType))throw new Error("Not Found")},is=async(u,d,p,h,D,_)=>{await Ur(u,p,d);let P=await t.select().top(1).from(R).where(Te($(R.hubId,p),$(R.userId,d))),O;if(P.length>0?P[0].isStarred!==D?O=(await t.update(R).set({isStarred:D,updatedAt:new Date,updatedBy:String(d)}).output().where(Te($(R.hubId,p),$(R.userId,d))))[0]:O=P[0]:O=(await t.insert(R).output().values({hubId:p,userId:d,isStarred:D,isRead:!1,createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}))[0],h){let M=ve(h);M&&(l.invalidatePrefix(Ct(M,d)),await re(`${Z}${M}`))}return l.invalidatePrefix(wr(p,d)),await re(`${se}${p}`),await xe(sr.parse({type:"status-update",reportHubId:p,recipientRawUserId:d,statusType:"star",value:D,clientTempId:_}),"setStarStatus"),O},ss=async(u,d,p,h,D,_)=>{await Ur(u,p,d);let P=await t.select().top(1).from(R).where(Te($(R.hubId,p),$(R.userId,d))),O;if(P.length>0?P[0].isRead!==D?O=(await t.update(R).set({isRead:D,updatedAt:new Date,updatedBy:String(d)}).output().where(Te($(R.hubId,p),$(R.userId,d))))[0]:O=P[0]:O=(await t.insert(R).output().values({hubId:p,userId:d,isRead:D,isStarred:!1,createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}))[0],h){let M=ve(h);M&&(l.invalidatePrefix(Ct(M,d)),await re(`${Z}${M}`))}return l.invalidatePrefix(wr(p,d)),await re(`${se}${p}`),await xe(sr.parse({type:"status-update",reportHubId:p,recipientRawUserId:d,statusType:"read",value:D,clientTempId:_}),"setReadStatus"),O},Vn=async(u,d)=>{if(d===null)return;let p=await Dt();if(p.length===0)return;let[h]=await t.select({hubId:f.hubId}).top(1).from(f).where(Te($(f.hubId,u),qe(f.labelId,p)));return h?d:void 0},ls=async(u,d,p,h,D,_)=>{let[P]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where($(s.id,p));if(!P||P.deletedAt)throw new Error("Not Found");if(await Ur(u,p,d),!Me(u.commentable,P.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(P.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let O=await Vn(p,P.userId),M=de(),j=await T(async ge=>{let[pe]=await ge.insert(m).output().values({hubId:p,userId:d,body:h,createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)});return M!==null&&await M.writeHubs(ge,[p]),pe}),[E]=await t.select({displayName:n.displayName}).top(1).from(n).where($(n.id,d)),Q=E?.displayName??"";if(D){let ge=ve(D);ge&&(l.invalidatePrefix(zt(ge)),await re(`${Z}${ge}`))}l.invalidatePrefix(Je(p)),await re(`${se}${p}`);let ae={id:j.id,userId:a(j.userId),userName:Q,content:j.body,createdAt:we(j.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await xe(Zr.parse({type:"comment-add",reportHubId:p,comment:ae,clientTempId:_,recipientRawUserId:O,sourceType:P.sourceType}),"addComment"),ae},cs=async(u,d)=>await u.select().top(1).from(m).where($(m.id,d)),us=async(u,d,p,h,D,_)=>{let P=await cs(t,h);if(P.length===0)throw new Error("Not Found");if(P[0].hubId!==p)throw new Error("Not Found");let[O]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where($(s.id,P[0].hubId));if(!(O&&Me(u.visible,O.sourceType)))throw new Error("Not Found");if(P[0].userId!==d)throw new Error("Unauthorized");let M=await Vn(p,O.userId),j=de();if(await T(async E=>{await E.delete(m).where($(m.id,h)),j!==null&&await j.writeHubs(E,[p])}),D){let E=ve(D);E&&(l.invalidatePrefix(zt(E)),await re(`${Z}${E}`))}l.invalidatePrefix(Je(p)),await re(`${se}${p}`),await xe(en.parse({type:"comment-delete",reportHubId:p,commentId:h,clientTempId:_,recipientRawUserId:M,sourceType:O?.sourceType}),"deleteComment")},ds=async(u,d)=>{let p=new Map,h=r.attachment;if(!h||B===null)return p;let D=await u.select({hubId:h.hubId,fileName:h.fileName}).from(h).where(qe(h.hubId,[...d])).orderBy(Ne(h.hubId),Ne(h.createdAt),Ne(h.id));for(let _ of D)Un(p,Number(_.hubId),String(_.fileName));return p},ms=async(u,d,p)=>{let h=new Map;for(let[D,_]of p){let P=new Map;for(let{hub:M}of d)M.sourceType===D&&M.sourceIdNum!==null&&P.set(M.sourceIdNum,M.id);if(P.size===0)continue;let O=await _(u,[...P.keys()]);for(let[M,j]of O){let E=P.get(M);if(E===void 0)throw le(`search.externalSourceTexts.${D} answer key`,"a source id that was asked for",M);if(!(Array.isArray(j)&&j.every(Q=>typeof Q=="string")))throw le(`search.externalSourceTexts.${D} answer for ${M}`,"an array of strings",j);h.set(E,j)}}return h},ps=(u,d)=>{let p=V(u),h=[["subject",u.hub.title],["content",p.content],["author",p.author],["employeeName",p.employeeName],["updatedBy",p.updatedBy],["category",p.category],["creationCategory",p.creationCategory],["customerName",p.customerName]];for(let _ of p.interviewers)h.push(["interviewerName",_.name??null],["interviewerAffiliation",_.affiliation??null]);for(let _ of d.labelNames)h.push(["label",_]);for(let _ of d.attachmentNames)h.push(["attachment",_]);for(let _ of d.extraTexts)h.push(["extra",_]);let D=[];for(let _ of p.externalComments)D.push({authorUserId:null,text:Li(_.name,_.text)});for(let _ of d.postedComments)D.push({authorUserId:_.userId,text:Li(_.userName,_.body)});return{hubId:u.hub.id,fields:h,comments:D,filterValues:{authorName:p.employeeName,customerName:p.customerName}}},ys=async(u,d,p)=>{let h=[];for(let D of Rd(d,Sd)){let _=await w(u.select({hub:at(s),internal:at(y),creatorName:n.displayName,...A()}).from(s)).leftJoin(y,$(s.id,y.hubId)).leftJoin(n,$(s.userId,n.id)).where(qe(s.id,[...D])).orderBy(Ne(s.id)),P=new Map,O=await u.select({hubId:f.hubId,name:S.name}).from(f).innerJoin(S,$(f.labelId,S.id)).where(qe(f.hubId,[...D])).orderBy(Ne(f.hubId),Ne(S.id));for(let ae of O)Un(P,ae.hubId,ae.name);let M=new Map,j=await u.select({hubId:m.hubId,userId:m.userId,body:m.body,userName:n.displayName}).from(m).leftJoin(n,$(m.userId,n.id)).where(qe(m.hubId,[...D])).orderBy(Ne(m.hubId),Ne(m.createdAt),Ne(m.id));for(let ae of j)Un(M,ae.hubId,ae);let E=await ds(u,D),Q=await ms(u,_,p);for(let ae of _){let ge=ae.hub.id;h.push(ps(ae,{labelNames:Or(P,ge),postedComments:Or(M,ge),attachmentNames:Or(E,ge),extraTexts:Or(Q,ge)}))}}return h},hs=(u,d,p)=>k===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):k.search(t,{criteria:p,viewerUserId:d,scope:u}),Yn=Object.freeze(Td(["Internal",...b.map(u=>u.sourceType)])),fs=async(u,d)=>{if(k===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let p=Yn.filter(_=>Me(u.visible,_)),h=await k.facetValues(t,{column:"authorName",viewerUserId:d,scope:u}),D=await k.facetValues(t,{column:"customerName",viewerUserId:d,scope:u});return{sourceTypes:p,authors:h,customers:D}},Rs=async(u,d,p,h,D)=>{if(k===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(h.length>_e.maxDetailIds)throw le("markDailyReportSearchHits: reportHubIds",`at most ${_e.maxDetailIds} ids`,h.length);let{signal:_}=D,P=or(qt(p));if(h.length===0||Le(u.visible))return{wordsDigest:P,reports:[]};_.throwIfAborted();let O=await Hr(u,d,qe(s.id,[...h]));_.throwIfAborted();let M=p.combine==="union"&&p.sets.length>=2&&O.length>0?await k.matchedSets(t,{plan:p,viewerUserId:d,scope:u,ids:O.map(E=>E.reportHubId)}):null,j=[];for(let E of O){j.length>0&&await new Promise(ge=>setImmediate(ge)),_.throwIfAborted();let Q=M===null?null:M.get(E.reportHubId),ae=Q===void 0?0:Q;j.push({reportHubId:E.reportHubId,matchedSets:ae,fields:xi(E,wi(p,ae))})}return{wordsDigest:P,reports:j}},Ss=u=>{let d=de();return d===null?Promise.reject(new Error("[daily-report] reconcileSearchIndex: the search setting is not configured")):d.reconcile(t,u)},gs=async(u,d,p)=>{if(!nr(d))throw le("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",d);v.info("createDailyReport called",{userId:u,businessDate:d});let[h]=await t.select({displayName:n.displayName}).from(n).where($(n.id,u)),D=h?.displayName??a(u),_=de();try{let P=await T(async M=>{v.info("Starting transaction");let j=`internal-temp-${Date.now()}-${Math.random()}`,[E]=await M.insert(s).output().values({sourceType:"Internal",sourceId:j,businessDate:new Date(`${d}T00:00:00Z`),userId:u,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)});await M.update(s).set({sourceId:String(E.id)}).where($(s.id,E.id)),v.info("Hub created",E),await M.insert(y).values({hubId:E.id,body:"",createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}),v.info("Internal created"),v.info("Calling getDraftLabelId");let Q=await Fr();v.info("draftLabelId",Q);let ae=[];return Q&&(await M.insert(f).values({hubId:E.id,labelId:Q,createdAt:new Date,createdBy:String(u)}),ae.push({id:Q,name:I,color:null})),v.info("Label assigned"),_!==null&&await _.writeHubs(M,[E.id]),{reportHubId:E.id,date:d,createdAt:we(E.createdAt,"YYYY-MM-DD HH:mm:ss"),author:D,userId:a(u),sourceType:"Internal",employeeName:D,updatedBy:a(u),updatedAt:we(E.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:E.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:ae,postedComments:[],attachments:[]}});l.invalidatePrefix(Ct(d,u)),l.invalidatePrefix(ft),l.invalidatePrefix(Pn(u)),await re(z),await re(`${Z}${d}`);let O=await Nt(He.unrestricted("post-write self read: the writer always sees the row they just wrote"),P.reportHubId,u,{forceRefresh:!0});if(O){let M=await Dt(),j=O.labels.some(E=>M.includes(E.id));await xe(tn.parse({type:"report-create",reportHubId:O.reportHubId,report:O,clientTempId:p,recipientRawUserId:j?u:void 0}),"createDailyReport")}return O??P}catch(P){throw v.error("Error in createDailyReport",P),P}},er=async(u,d)=>await u.select().top(1).from(s).where($(s.id,d)),$r=async(u,d,p)=>{await u.update(s).set(p).where($(s.id,d))},qn=async(u,d,p)=>{await u.update(y).set(p).where($(y.hubId,d))},jn=async(u,d,p)=>{await u.delete(f).where(Te($(f.hubId,d),$(f.labelId,p)))},bs=async(u,d,p)=>{let h=await er(t,u);if(!h.length||h[0].deletedAt)throw new Error("Not Found");if(h[0].userId!==d)throw new Error("Unauthorized");let D=de();if(await T(async _=>{await $r(_,u,{deletedAt:new Date,deletedBy:String(d),updatedAt:new Date,updatedBy:String(d)}),D!==null&&await D.writeHubs(_,[u])}),l.invalidatePrefix(Je(u)),l.invalidatePrefix(ft),l.invalidatePrefix(ht),await re(z),h[0].businessDate){let _=ve(we(h[0].businessDate,"YYYY-MM-DD"));_&&await re(`${Z}${_}`)}await xe(on.parse({type:"report-delete",reportHubId:u,clientTempId:p,sourceType:h[0].sourceType}),"deleteDailyReport")},Ds=async(u,d,p,h)=>{let D=await er(t,u);if(!D.length||D[0].deletedAt)throw new Error("Not Found");if(D[0].userId!==d)throw new Error("Unauthorized");let _=de();await T(async M=>{p.title!==void 0&&await $r(M,u,{title:Mi(p.title),updatedAt:new Date,updatedBy:String(d)}),p.content!==void 0&&await qn(M,u,{body:Mi(p.content),updatedAt:new Date,updatedBy:String(d)}),_!==null&&await _.writeHubs(M,[u])}),l.invalidatePrefix(Je(u)),l.invalidatePrefix(ft),await re(`${se}${u}`);let P=ve(we(D[0].businessDate,"YYYY-MM-DD"));P&&(l.invalidatePrefix(zt(P)),await re(`${Z}${P}`));let O=await Nt(He.unrestricted("post-write self read: the writer always sees the row they just wrote"),u,d,{forceRefresh:!0});if(O){let M=await Dt(),j=O.labels.some(E=>M.includes(E.id));await xe(rn.parse({type:"report-update",reportHubId:O.reportHubId,report:O,clientTempId:h,recipientRawUserId:j?d:void 0}),"updateDailyReport")}},As=async(u,d,p)=>{let h=await er(t,u);if(!h.length)throw new Error("Not Found");if(h[0].userId!==d)throw new Error("Unauthorized");let D=await Fr();if(!D)return null;let _=de();if(await T(async M=>{await jn(M,u,D),_!==null&&await _.writeHubs(M,[u])}),l.invalidatePrefix(Je(u)),l.invalidatePrefix(ft),l.invalidatePrefix(ht),await re(z),h[0].businessDate){let M=ve(we(h[0].businessDate,"YYYY-MM-DD"));M&&await re(`${Z}${M}`)}let P=ve(we(h[0].businessDate,"YYYY-MM-DD"));P&&l.invalidatePrefix(Ct(P,d));let O=await Nt(He.unrestricted("post-write self read: the writer always sees the row they just wrote"),u,d,{forceRefresh:!0});return O&&await xe(nn.parse({type:"report-publish",reportHubId:O.reportHubId,report:O,clientTempId:p}),"publishDailyReport"),O??null},Ts=async(u,d)=>{l.invalidatePrefix(ft),l.invalidatePrefix(ht),await re(z);for(let p of new Set(u))l.invalidatePrefix(Je(p)),await re(`${se}${p}`);for(let p of new Set(d)){let h=ve(p);h&&await re(`${Z}${h}`)}},Es=async()=>{l.clearAll(),J.clear(),Ie=null,c&&await re(z),v.info("Server-side DB/SQL caches cleared successfully.")};return{streamKey:ye,streamMaxLen:Qe,attachmentDelivery:B,titleMaxLength:x,searchLimits:Y===null?null:{concurrency:Y.concurrency,rateLimitPerMinute:Y.rateLimitPerMinute},searchFilterSourceTypes:Yn,clearCache:Es,invalidateHubReadCaches:Ts,getUserIdByExternalId:C,getDailyReportIdsByExternalId:oe,getDailyReportIdsFirstPageByExternalId:G,readSseStreamAnchor:We,getDailyReportsByBusinessDate:Se,getDailyReportsByBusinessDateByExternalId:rs,getDailyReportDetailById:Nt,getDailyReportDetailByIdByExternalId:ns,getDailyReportDetailsByIdsByExternalId:os,getDraftLabelId:Fr,searchDailyReports:hs,markDailyReportSearchHits:Rs,listDailyReportSearchFacets:fs,reconcileSearchIndex:Ss,getAttachmentsByHubIds:Zt,getAttachmentForUser:Zi,markAttachmentMissing:es,markAttachmentPresent:ts,setStarStatus:is,setReadStatus:ss,addComment:ls,deleteComment:us,createDailyReport:gs,updateDailyReport:Ds,publishDailyReport:As,deleteDailyReport:bs,findDailyReportHubById:er,updateDailyReportHub:$r,updateDailyReportInternal:qn,deleteDailyReportLabel:jn}}var Ed=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(fe(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return fe(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};import{desc as Ni,sql as Id}from"drizzle-orm";import{bigint as De,bit as Oi,date as _d,datetime2 as Ee,foreignKey as je,index as dt,int as wd,mssqlSchema as xd,nvarchar as ie,primaryKey as bt,uniqueIndex as Cd}from"drizzle-orm/mssql-core";function Pd(e,t){let r=xd(e),n=t.userTable,o=r.table("DailyReportHub",{id:De("id",{mode:"number"}).identity().notNull(),sourceType:ie("source_type",{length:20}).notNull(),sourceId:ie("source_id",{length:100}).notNull(),sourceIdNum:De("source_id_num",{mode:"number"}).generatedAlwaysAs(Id`TRY_CAST(source_id AS BIGINT)`),businessDate:_d("business_date"),userId:De("user_id",{mode:"number"}),title:ie("title",{length:200}),summary:ie("summary",{length:"max"}),createdAt:Ee("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull(),updatedAt:Ee("updated_at").notNull(),updatedBy:ie("updated_by",{length:50}).notNull(),deletedAt:Ee("deleted_at"),deletedBy:ie("deleted_by",{length:50})},m=>[bt({name:`${e}_DailyReportHub_pk`,columns:[m.id]}),je({name:`${e}_DailyReportHub_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),dt(`${e}_DailyReportHub_business_date_index`).on(m.businessDate),dt(`${e}_DailyReportHub_updated_at_index`).on(m.updatedAt),dt(`${e}_DailyReportHub_source_index`).on(m.sourceType,m.sourceId),dt(`${e}_DailyReportHub_user_id_index`).on(m.userId),dt(`${e}_DailyReportHub_business_date_id_index`).on(Ni(m.businessDate),Ni(m.id)),dt(`${e}_DailyReportHub_deleted_at_index`).on(m.deletedAt)]),a=r.table("DailyReportInternal",{hubId:De("hub_id",{mode:"number"}).notNull(),body:ie("body",{length:"max"}),metadata:ie("metadata",{length:"max"}),createdAt:Ee("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull(),updatedAt:Ee("updated_at").notNull(),updatedBy:ie("updated_by",{length:50}).notNull()},m=>[bt({name:`${e}_DailyReportInternal_pk`,columns:[m.hubId]}),je({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:De("id",{mode:"number"}).identity().notNull(),hubId:De("hub_id",{mode:"number"}).notNull(),userId:De("user_id",{mode:"number"}).notNull(),body:ie("body",{length:"max"}).notNull(),createdAt:Ee("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull(),updatedAt:Ee("updated_at").notNull(),updatedBy:ie("updated_by",{length:50}).notNull()},m=>[bt({name:`${e}_DailyReportComment_pk`,columns:[m.id]}),je({name:`${e}_DailyReportComment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),je({name:`${e}_DailyReportComment_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),dt(`${e}_DailyReportComment_hub_id_index`).on(m.hubId)]),l=r.table("DailyReportLabel",{id:De("id",{mode:"number"}).identity().notNull(),userId:De("user_id",{mode:"number"}),name:ie("name",{length:50}).notNull(),color:ie("color",{length:20}),sortOrder:wd("sort_order"),createdAt:Ee("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull(),updatedAt:Ee("updated_at").notNull(),updatedBy:ie("updated_by",{length:50}).notNull()},m=>[bt({name:`${e}_DailyReportLabel_pk`,columns:[m.id]}),je({name:`${e}_DailyReportLabel_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),c=r.table("DailyReportHub_Label",{hubId:De("hub_id",{mode:"number"}).notNull(),labelId:De("label_id",{mode:"number"}).notNull(),createdAt:Ee("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull()},m=>[bt({name:`${e}_DailyReportHub_Label_pk`,columns:[m.hubId,m.labelId]}),je({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),je({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[m.labelId],foreignColumns:[l.id]})]),s=r.table("DailyReportUserStatus",{hubId:De("hub_id",{mode:"number"}).notNull(),userId:De("user_id",{mode:"number"}).notNull(),isRead:Oi("is_read").default(!1).notNull(),isStarred:Oi("is_starred").default(!1).notNull(),createdAt:Ee("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull(),updatedAt:Ee("updated_at").notNull(),updatedBy:ie("updated_by",{length:50}).notNull()},m=>[bt({name:`${e}_DailyReportUserStatus_pk`,columns:[m.hubId,m.userId]}),je({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),je({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),y=r.table("DailyReportAttachment",{id:De("id",{mode:"number"}).identity().notNull(),hubId:De("hub_id",{mode:"number"}).notNull(),uploadedBy:De("uploaded_by",{mode:"number"}),sourceKey:ie("source_key",{length:200}).notNull(),fileName:ie("file_name",{length:255}).notNull(),filePath:ie("file_path",{length:"max"}).notNull(),fileType:ie("file_type",{length:100}),fileSize:De("file_size",{mode:"number"}),objectCheckedAt:Ee("object_checked_at"),objectMissingAt:Ee("object_missing_at"),createdAt:Ee("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull(),updatedAt:Ee("updated_at").notNull(),updatedBy:ie("updated_by",{length:50}).notNull()},m=>[bt({name:`${e}_DailyReportAttachment_pk`,columns:[m.id]}),je({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),je({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[m.uploadedBy],foreignColumns:[n.id]}),Cd(`${e}_DailyReportAttachment_source_unique`).on(m.hubId,m.sourceKey),dt(`${e}_DailyReportAttachment_hub_id_index`).on(m.hubId,m.createdAt)]);return{hub:o,internal:a,comment:i,attachment:y,label:l,hubLabel:c,userStatus:s}}import{bigint as Bn,binary as vi,datetime2 as Md,int as Ld,mssqlSchema as Nd,nvarchar as vr,primaryKey as ki,varchar as Od}from"drizzle-orm/mssql-core";function vd(e){let t=Nd(e),r=t.table("DailyReportSearchDocument",{hubId:Bn("hub_id",{mode:"number"}).notNull(),searchText:vr("search_text",{length:"max"}).notNull(),sourceDigest:vi("source_digest",{length:32}).notNull(),normalizerVersion:Od("normalizer_version",{length:64}).notNull(),indexedAt:Md("indexed_at").notNull(),rowVersion:vi("row_version",{length:8}).notNull(),authorName:vr("author_name",{length:et.maxValueLength}),customerName:vr("customer_name",{length:et.maxValueLength})},o=>[ki({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:Bn("hub_id",{mode:"number"}).notNull(),ordinal:Ld("ordinal").notNull(),authorUserId:Bn("author_user_id",{mode:"number"}),commentText:vr("comment_text",{length:"max"}).notNull()},o=>[ki({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var kd=5e7,zi=2e8,Fd=1,Gi=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})})}),Fi=125,Hi=4,Ui=16,$i=50,Bi=2,kr=Object.freeze({renderMs:Pe.renderMs,nanosecondsPerBlockVisit:Fi,margin:Hi,maxBlockVisits:Math.floor(Pe.renderMs*1e6/(Fi*Hi)),walkBudgetMs:Ui,nanosecondsPerWalkStep:$i,walkMargin:Bi,maxWalkSteps:Math.floor(Ui*1e6/($i*Bi))}),Hd=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Vi=75,Yi=4,qi="#ffffff",Ud=1,$d={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Bd=[/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/],ji=Object.freeze({ok:!1,reason:"failed"}),Wi=Object.freeze({ok:!1,reason:"unsupported"}),Ki=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Qo(e)}),Ji=(e,t)=>{switch(t){case"jpeg":{let r=bn(e);return r===null?null:Ki(r)}case"png":{let r=ea(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=ta(e,kr.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},Qi=(e,t)=>{let r=Hd.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Gi,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},Vd=(e,t,r)=>{let n=Ji(e,t);return n===null?null:Qi(n,r)},Yd=e=>e!==null&&e<=zi,qd=(e,t)=>{if(t!=="jpeg")return Ji(e,t);let r=Xo(e,kr);return r===null||r.blockVisits>kr.maxBlockVisits?null:Ki(r.header)},jd=e=>{let t=e instanceof Error?e.message:"";return Bd.some(r=>r.test(t))?"failed":"unsupported"},Wd=e=>{e.cache(!1),e.concurrency(Fd),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values($d)});let t=async(n,o,a,i,l)=>{let c=qd(n,o);if(c===null)return Wi;try{let s=e(n,{limitInputPixels:kd,animated:!1});if(!Yd(Qi(c,await s.metadata())))return Wi;if(l.aborted)return ji;let y=await s.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:qi}).webp({quality:Vi,effort:Yi}).toBuffer();return{ok:!0,bytes:new Uint8Array(y),contentType:"image/webp"}}catch(s){return{ok:!1,reason:jd(s)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?ji:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Vi}-e${Yi}/flatten-${qi}/v${Ud}`,render:r}};var zd=4096,Gd=6e4;function iR(e){e.redis||fe(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=qr(e.redis),r=new kt({defaultTtlMs:ee("cacheDefaultTtlMs",e.cacheDefaultTtlMs??Gd,1),maxBuckets:ee("cacheMaxBuckets",e.cacheMaxBuckets??zd,1)},t),n=$n({...e,cache:r,epochs:t}),o=new Gt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Nn({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(i=>i.sourceType)])],...a}}export{An as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,Dn as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,zi as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,kr as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,Gi as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,Mn as DAILY_REPORT_SSE_CATCH_UP_BATCH,ni as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,Gt as DailyReportSseReader,He as DailyReportViewerScope,kt as SqlResultCache,Nn as createDailyReportHandlers,iR as createDailyReportServer,$n as createDailyReportService,qr as createEpochStore,Wd as createSharpThumbnailRenderer,Pd as defineDailyReportSchema,vd as defineDailyReportSearchSchema,ct as isStreamIdLte,sn as parseClientTempId,Vd as predictSharpThumbnailWorkingSetBytes,Wt as readDailyReportSseStreamEntry,Ed as transformJsonArray};
11
+ INSERT INTO ${o} (${Y(o.hubId)}, ${Y(o.ordinal)}, ${Y(o.authorUserId)}, ${Y(o.commentText)}) SELECT ${Y(o.hubId)}, ${Y(o.ordinal)}, ${Y(o.authorUserId)}, ${Y(o.commentText)} FROM OPENJSON(${i}) WITH (${Y(o.hubId)} bigint, ${Y(o.ordinal)} int, ${Y(o.authorUserId)} bigint, ${Y(o.commentText)} nvarchar(max));`},qi=(e,t)=>B`SELECT ${Y(e.hubId)} AS ${B.identifier(we.hubId)}, LOWER(CONVERT(char(64), ${Y(e.sourceDigest)}, 2)) AS ${B.identifier(we.sourceDigest)}, ${Y(e.normalizerVersion)} AS ${B.identifier(we.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${Qt(t)})`,Yi=(e,t,r)=>B`SELECT TOP (${r}) ${Y(e.id)} AS ${B.identifier(we.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var ji=e=>({search:async(t,r)=>Ne(r.scope.visible)?[]:mt(await t.execute(Ui(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=At(o[qe.sourceType],qe.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${qe.sourceType} is null`);return{reportHubId:Dt(o[qe.reportHubId],qe.reportHubId),businessDate:At(o[qe.businessDate],qe.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Ne(r.scope.visible))return new Map;let n=mt(await t.execute($i(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[Tt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${Tt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(Dt(i[Tt.reportHubId],Tt.reportHubId),l)}return a},facetValues:async(t,r)=>Ne(r.scope.visible)?[]:mt(await t.execute(Bi(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=At(o[Xt.value],Xt.value);if(a===null)throw new Error(`[daily-report] search: column ${Xt.value} is null`);return a})});import{chunk as Nr,MAX_IN_LIST as kr}from"@aiquants/mssql";import{sql as zi}from"drizzle-orm";import{createHash as Wd}from"crypto";var zd=Object.freeze({authorName:"author",customerName:"customer"}),Yn=e=>e===null?null:mn(e),Wi=(e,t,r)=>{let n=Yn(r);if(n!==null&&n.length>Ze.maxValueLength){let o=Ze.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${zd[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},Zt=e=>e===null?"n;":`s${e.length}:${e}`,er="utf16le",Gd=e=>{let t=Wd("sha256");t.update(`F${e.fields.length};`,er);for(let[r,n]of e.fields)t.update(Zt(r)+Zt(n),er);return t.update(`C${e.comments.length};`,er),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${Zt(r.text)}`,er)}),t.update(`P;${Zt(Yn(e.filterValues.authorName))}${Zt(Yn(e.filterValues.customerName))}`,er),t.digest("hex")},jn=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=Ir(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=Ir(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:ai(r),comments:n,sourceDigest:Gd(e),forcedCuts:t,authorName:Wi(e.hubId,"authorName",e.filterValues.authorName),customerName:Wi(e.hubId,"customerName",e.filterValues.customerName)}};var Gi=e=>{let t=async(c,s)=>{let m=[];for(let u of Nr(s,kr))for(let f of mt(await c.execute(Fi(e.hub,u))))m.push(Dt(f[we.hubId],we.hubId));return m},r=async(c,s)=>{for(let m of Nr(s,kr))await c.execute(Vi(e.tables,m,e.normalizerVersion))},n=async(c,s)=>{let m=new Map;for(let u of Nr(s,kr))for(let f of mt(await c.execute(qi(e.tables.document,u))))m.set(Dt(f[we.hubId],we.hubId),{sourceDigest:At(f[we.sourceDigest],we.sourceDigest),normalizerVersion:At(f[we.normalizerVersion],we.normalizerVersion)});return m},o=async(c,s,m)=>mt(await c.execute(Yi(e.hub,s,m))).map(u=>Dt(u[we.hubId],we.hubId)),a=async(c,s)=>{let m=await t(c,[...new Set(s)].sort((f,h)=>f-h));if(m.length===0)return;let u=(await e.loadSources(c,m)).map(jn);u.length>0&&await r(c,u)},i=c=>e.inTransaction(async s=>{await s.execute(zi`SET DEADLOCK_PRIORITY LOW`);let m=await t(s,c),u=await n(s,m),f=(await e.loadSources(s,m)).map(jn),h=f.filter(R=>{let b=u.get(R.hubId);return b===void 0||b.sourceDigest!==R.sourceDigest||b.normalizerVersion!==e.normalizerVersion});return h.length>0&&await r(s,h),await s.execute(zi`SET DEADLOCK_PRIORITY NORMAL`),{scanned:f.length,written:h.length,forcedCuts:f.reduce((R,b)=>R+b.forcedCuts,0)}});return{writeHubs:a,reconcile:async(c,s)=>{let{batchSize:m,hubIds:u,signal:f,onProgress:h}=s;te("reconcileSearchIndex: batchSize",m,1,kr);let R=ue(),b=u===void 0?null:Nr([...new Set(u)].sort((A,x)=>A-x),m),S={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let A=0;;A++){f?.throwIfAborted();let x=b===null?await o(c,S.lastHubId===null?0:S.lastHubId,m):b[A];if(x===void 0||x.length===0)break;let F=await i(x);S={scanned:S.scanned+F.scanned,written:S.written+F.written,skipped:S.skipped+F.scanned-F.written,forcedCuts:S.forcedCuts+F.forcedCuts,lastHubId:x[x.length-1]},h?.(S)}return{...S,elapsedMs:ue()-R}}}};import{holdsMultiUnitCluster as Kd}from"@aiquants/fuzzy-search/normalize";var Wn=255,vr=Object.values(ft).sort((e,t)=>e-t),Jd=new Intl.Segmenter("und",{granularity:"grapheme"}),De=Object.freeze({split:120,plan:200,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),nt=5e5,Or=Math.floor(nt/De.linear),Qd=Math.floor(nt/De.segment),Ki=Math.floor(nt/De.sweep),Qi=Math.floor(nt/De.scan),Gn=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),Xi=(e,t)=>{let r=0,n=t(),o=nt,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+nt,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=nt,a=!1}}},DR=Object.freeze({fits:()=>!0,charge:()=>{}}),Zi=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 Xd=(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},Zd=(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*ep(e,t,r,n){let o=!1;for(let s=t;s<r&&!o;s+=Or){let m=Math.min(r,s+Or),u=(m-s)*De.linear;n.fits(u)||(yield),o=Kd(e.slice(s,m)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=Jd.segment(e.slice(t,r))[Symbol.iterator](),c=l.next();for(;!c.done;){let s=Math.max(Qd,c.value.segment.length);n.fits(s*De.segment)||(yield);let m=0;for(;!c.done&&m+c.value.segment.length<=s;){let{index:u,segment:f}=c.value;a.fill(t+u,u,u+f.length),i.fill(t+u+f.length,u,u+f.length),m+=f.length,c=l.next()}n.charge(m*De.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var tp=256,rp=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]},np=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=rp(r),a=Math.max(Qi-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(tp/o))},windowStarts:a}})},Fr=(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)},Ji=(e,t,r)=>{let n=Fr(e,t);return e.pieces[n>=0?n:Fr(e,r==="start"?t-1:t+1)]},es=(e,t)=>{let r=Fr(e,t);if(r<0)return ts(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},ts=(e,t)=>{let r=Fr(e,t);if(r<0)return es(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},op=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),ap=Object.freeze({kind:"done"}),zn=Object.freeze({kind:"slice"}),ip=Object.freeze({kind:"clusters"}),sp=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:c,periodic:s}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(De.run))return zn;let h=Ji(e,n.closedStart,"start"),R=Ji(e,n.closedEnd-1,"end");if(h.mapped===null)return{kind:"map",piece:h};if(R.mapped===null)return{kind:"map",piece:R};if(e.isCut&&e.clusters===void 0)return ip;let b=t(e.offset+es(e,n.closedStart)),S=t(e.offset+ts(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let A=e.clusters;A==null?a(b,S,c):a(A.clusterStarts[b-A.start],A.clusterEnds[S-1-A.start],c),o.charge(De.run);continue}if(s!==null&&n.periodicEnd>=0){if(!o.fits(nt))return zn;let{period:h,continuation:R}=s,b=n.periodicEnd,S=Math.min(i.length,b+Math.max(Qi,R.length)),A=b;for(;A+R.length<=S&&i.startsWith(R,A);)A+=R.length;let x=A+R.length>S&&S<i.length;if(!x)for(;A<i.length&&i.charCodeAt(A)===i.charCodeAt(A-h);)A++;if(o.charge((A-b)*De.scan),x){n.periodicEnd=A;continue}n.periodicEnd=-1,n.last+=Math.floor((A-n.last-l.length)/h)*h,n.from=n.last+l.length-h+1;continue}if(n.from<0){if(n.runStart<0)return ap;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(nt))return zn;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 m=n.from-n.windowStart,u=n.window.indexOf(l,m);if(u<0){o.charge((n.window.length-m)*De.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-m)*De.scan);let f=n.windowStart+u;(n.runStart<0||f>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=f),n.last=f,s===null?n.from=f+1:n.periodicEnd=f+l.length}};function*lp(e,t,r,n,o){if(t.length===0)return;let a=e.length*De.split;n.fits(a)||(yield);let i=ti(e),l=[],c=[];Fn(i.text,(m,u)=>{l.push(u),c.push(u+m.length)}),n.charge(a);let s=m=>i.rawIndex===null?m:i.rawIndex[m];for(let m=0;m<l.length;m++){let u=l[m],f=i.text.slice(u,c[m]),h=f.length*De.plan;n.fits(h)||(yield);let R=wr(f,r);n.charge(h);let b=[],S="";for(let x of R.chunks){let F="",E=[];for(let D of x){let $=(D.end-D.start)*De.normalize;n.fits($)||(yield);let M=On(D.start===0&&D.end===f.length?f:f.slice(D.start,D.end),r).text;n.charge($),M.length>0&&E.push({start:D.start,end:D.end,text:M,chunkStart:F.length}),F+=M}if(F.length!==0){S.length>0&&(S+=" ");for(let D of E)b.push({start:D.start,end:D.end,text:D.text,plainStart:S.length+D.chunkStart,mapped:null});S+=F}}if(S.length===0)continue;let A={offset:u,plain:S,pieces:b,isCut:!Zd(R,f),lastPiece:0,clusters:void 0};for(let x of t){let F=op();for(;;){let E=sp(A,s,x,F,n,o);if(E.kind==="done")break;if(E.kind==="slice"){yield;continue}if(E.kind==="clusters"){A.clusters=yield*ep(e,s(u),s(u+f.length-1)+1,n);continue}let{piece:D}=E,$=(D.end-D.start)*De.map;n.fits($)||(yield);let M=f.slice(D.start,D.end);D.mapped=Xd(oi(M,wr(M,r)),D.text),n.charge($)}}}}function*cp(e,t,r,n){let o=new Int32Array(vr.length),a=0,i=Wn;for(let l=0;l<=e;l+=Ki){let c=Math.min(e+1,l+Ki),s=(c-l)*De.sweep;r.fits(s)||(yield);for(let m=l;m<c;m++){let u=Wn;for(let f=vr.length-1;f>=0;f--){let h=vr[f];o[h]+=t[h][m],o[h]>0&&(u=h)}if(u!==i){if(i!==Wn&&!n(a,m,i))return!1;a=m,i=u}}r.charge(s)}return!0}function*up(e,t,r,n,o){let a=null;return yield*lp(e,t,r,n,(l,c,s)=>{a===null&&(a=vr.map(()=>new Int32Array(e.length+1))),a[s][l]++,a[s][c]--}),a===null?!0:yield*cp(e.length,a,n,o)}var dp=(e,t,r,n)=>{let o=np(t),a=[],i=(c,s,m)=>(a.push(c,s,m),a.length<=3*r.maxRanges);return Zi(function*(){return(yield*up(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var rs=(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)},ns=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of ho)r(Xe.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(Xe.interviewer(o,"name"),n.name),r(Xe.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(Xe.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(Xe.comment(Qr(o),"author"),n.name),r(Xe.comment(Qr(o),"content"),n.text)});for(let n of e.postedComments)r(Xe.comment(n.id,"author"),n.userName),r(Xe.comment(n.id,"content"),n.content);return t};function*pp(e,t){let r=en;for(let n=0;n<e.length;n+=Or){let o=Math.min(e.length,n+Or),a=(o-n)*De.linear;t.fits(a)||(yield),r=tn(r,e,n,o),t.charge(a)}return r}var os=async(e,t,r,n)=>{let o=0,a=0,i=async s=>{for(;!s.step();)await r(),n.startSlice();return s.result()},l=async(s,m)=>{if(!m&&a>t.maxRanges)return null;let u={};for(let{key:f,value:h}of s.fields){if(!m&&o+h.length>t.maxUnits)return null;let R=await i(Zi(pp(h,n))),b=await i(dp(h,s.alternatives,{maxLength:kn,maxRanges:t.maxFieldRanges},n));if(o+=h.length,b.dense){u[f]={fingerprint:R,dense:!0};continue}if(u[f]={fingerprint:R,ranges:b.ranges},a+=b.ranges.length/3,!m&&a>t.maxRanges)return null}return u},c=[];for(let s=0;s<e.length;s++){let m=e[s],u=await l(m,c.length===0);if(u===null)return{reports:c,deferred:e.slice(s).map(f=>f.reportHubId)};c.push({reportHubId:m.reportHubId,matchedSets:m.matchedSets,fields:u})}return{reports:c,deferred:[]}};var at=e=>Rp(e),as=ar([]),xe=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),c=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${c}:${s}`},Sp=e=>{let{length:t}=e;if(t===void 0)throw ne("tables.hub.title","a character column with a declared length",t);return te("tables.hub.title.length",t,1)},is=e=>e===""?null:e,gp=Object.freeze([]),Jn=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},Hr=(e,t)=>e.get(t)??gp,ss=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Er),bp=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 ne("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},Dp=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw Qe(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw ne(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw Qe(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw ne(`${e}: options.signal`,r,n);return n},Ap=e=>{let t=new Set;return e.filter(r=>{let n=r.toLowerCase();return t.has(n)?!1:(t.add(n),!0)})};function Qn(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:c}=e,{hub:s,internal:m,comment:u,label:f,hubLabel:h,userStatus:R}=r,b=e.externalSources??[],S=bp(e.draftLabelNames),A=S[0],x=Se(e.logger,1,"Service");Sr(e);let F=La(e.attachments),E=Sp(s.title),D=d=>fp(p=>t.transaction(y=>p(()=>d(y))),e.transactionRetry),$=e.search===void 0?null:vi(e.search,b.map(d=>d.sourceType)),M={hub:s,hubLabel:h,label:f},H=$===null?null:ji({tables:{...M,search:$.tables},draftLabelNames:S});$!==null&&Hn();let de=null,pe=async()=>{if($===null)return null;if(de===null){let d=await Hn(),p=$.externalSourceTexts;de=Gi({hub:s,tables:$.tables,loadSources:(y,g)=>js(y,g,p),inTransaction:D,normalizerVersion:d})}return de},ge=e.idsTtlMs??18e4,G="daily-report:ids:epoch",se=e.businessDateTtlMs??3e5,re="daily-report:date-epoch:",ce="daily-report:detail-epoch:",he=`${e.streamKey??"daily-report:sse-stream"}:v3`,Ke=e.streamMaxLen??1e4,oe=d=>c.incrementEpoch(d),ke=d=>qt(s.sourceType,d),Ue=(d,p)=>Lr(M,d,S,p),it=Kn`CASE WHEN ${Pr(M,S)} THEN 1 ELSE 0 END`,st=async d=>{let[p]=await t.select({id:s.id}).top(1).from(s).where(Ae(V(s.id,d),Pr(M,S)));return p!==void 0},Ee=async(d,p)=>{let y=await i?.getClient();if(!y){x.warn(`[SSE] Redis client unavailable (${p})`);return}let g=JSON.stringify(d),w=Buffer.byteLength(g);if(w>6356992){x.warn(`[SSE] Event too large (${p}): ${w} bytes > ${6356992}; not published`);return}let _=ue();try{await y.xAdd(he,"*",{data:g},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:Ke}});let I=ue()-_;I>1e3&&x.warn(`[SSE] Slow publish (${p}): ${I}ms`)}catch(I){x.error(`[SSE] Redis publish failed (${p}):`,I)}},T=async()=>{try{let d=await i?.getClient();if(d===void 0)return null;let[p]=await d.xRevRange(he,"+","-",{COUNT:1});return p===void 0?null:p.id}catch(d){return x.error("SSE stream anchor read failed",d),null}},O=d=>d==null||d===""?null:/^\d+$/.test(d)?a(Number(d)):d,N=()=>{let d={};for(let p of b)d[`ext_${p.sourceType}`]=at(p.table);return d},P=d=>{let p=d;for(let y of b)p=p.leftJoin(y.table,Ae(V(s.sourceType,y.sourceType),V(s.sourceIdNum,y.idColumn)));return p},U=d=>{let{hub:p,internal:y}=d,g=p.summary,w=[],_=null,I=null,v=null,L=null,q=null,Q=null,J=[],j=b.find(ee=>ee.sourceType===p.sourceType),Z=j?d[`ext_${j.sourceType}`]:void 0;if(j&&Z){let ee=j.mapRow(Z);ee.content!==void 0&&(g=ee.content),ee.employeeName!==void 0&&(Q=ee.employeeName),ee.category!==void 0&&(_=ee.category),ee.creationCategory!==void 0&&(I=ee.creationCategory),ee.visitTimeFrom!==void 0&&(v=ee.visitTimeFrom),ee.visitTimeTo!==void 0&&(L=ee.visitTimeTo),ee.customerName!==void 0&&(q=ee.customerName),ee.interviewers!==void 0&&(w=ee.interviewers),ee.externalComments!==void 0&&(J=ee.externalComments)}else p.sourceType==="Internal"&&y&&(g=y.body);return{content:g,author:d.creatorName??O(p.createdBy)??"",employeeName:Q??d.creatorName??O(p.createdBy),updatedBy:O(p.updatedBy),category:_,creationCategory:I,visitTimeFrom:v,visitTimeTo:L,customerName:q,interviewers:w,externalComments:J}},W=d=>{if(d===1)return!0;if(d===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${zr(d)}`)},K=d=>d.creationCategory!==null&&S.includes(d.creationCategory),z=(d,p)=>W(d.hasDraftLabel)?!0:K(p),X=d=>d.some(K)?eo():Promise.resolve(null),k=(d,p,y,g,w)=>{let{hub:_}=p,I=(p.labels??[]).map(q=>({id:q.id,name:q.name,color:q.color})),v=p.postedCommentRows??[],L=Le(d.commentable,_.sourceType);return g!==null&&K(y)&&!I.some(q=>q.id===g)&&I.push({id:g,name:A,color:null}),{reportHubId:_.id,date:xe(_.businessDate,"YYYY-MM-DD"),author:y.author,userId:_.userId?a(_.userId):"",sourceType:_.sourceType??"Internal",createdAt:xe(_.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:xe(_.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:y.updatedBy,employeeName:y.employeeName,category:y.category,creationCategory:y.creationCategory,visitTimeFrom:y.visitTimeFrom,visitTimeTo:y.visitTimeTo,customerName:y.customerName,interviewers:y.interviewers,subject:_.title,content:y.content,externalComments:L?y.externalComments:[],isRead:p.isRead??!1,isStarred:p.isStarred??!1,isDraft:z(p,y),labels:I,postedComments:v.filter(q=>Qa({authorUserId:q.userId},_.sourceType,w??null,d)).map(q=>({...q,userId:a(q.userId),isMine:w?q.userId===w:!1})),attachments:p.attachments}},ae=async(d,p)=>(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).where(Ae(kt(s.deletedAt),Ue(p,"author-or-authorless"),ke(d.visible))).orderBy(Nt(s.businessDate),Nt(s.id))).map(g=>({...g,businessDate:xe(g.businessDate,"YYYY-MM-DD")})),fe=async(d,p,y)=>{let g=await wt(p);return g?Ne(d.visible)?[]:(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(y).from(s).where(Ae(kt(s.deletedAt),Ue(g,"author-or-authorless"),ke(d.visible))).orderBy(Nt(s.businessDate),Nt(s.id))).map(_=>({..._,businessDate:xe(_.businessDate,"YYYY-MM-DD")})):[]},ye=async(d,p)=>{let y=await P(t.select({hub:at(s),internal:at(m),creatorName:n.displayName,hasDraftLabel:it,...N()}).from(s)).leftJoin(m,V(s.id,m.hubId)).leftJoin(n,V(s.userId,n.id)).where(Ae(V(s.businessDate,Kn`${p}`),kt(s.deletedAt),ke(d.visible))).orderBy(Nt(s.id)),g=await rr(y.map(I=>I.hub.id)),w=y.map(U),_=await X(w);return y.map((I,v)=>k(d,{...I,attachments:g.get(I.hub.id)??[]},w[v],_))},tr=new Map,wt=async d=>{if(!e.disableUserIdCache&&tr.has(d))return tr.get(d)??null;let p=await o(d);return p!==null&&!e.disableUserIdCache&&tr.set(d,p),p},_s=async(d,p,{forceRefresh:y=!1,snapshot:g=!1,ttlMsOverride:w,onFetchStart:_,admission:I}={})=>{let v=await wt(p);if(!v)return{items:[],streamAnchor:null,snapshot:as};if(Ne(d.visible))return{items:[],streamAnchor:await T(),snapshot:as};let L=mi(v,Yt(d)),[q]=await l.getOrFetch({cacheKey:L,fetcher:async()=>{let Q=await T(),J=await ae(d,v);if(!uo(J)){x.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let j=[...J].sort(Jr);return[{items:j,streamAnchor:Q,snapshot:ar(j)}]}return[{items:J,streamAnchor:Q,snapshot:ar(J)}]},onFetchStart:_,forceRefresh:y,snapshot:g,admission:I,ttlMsOverride:w??ge,epochKey:G,refreshAheadRatio:.5});if(q===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return q},xs=(d,p,{forceRefresh:y=!1,snapshot:g=!1,ttlMsOverride:w}={})=>{let _=ve(p);return _?Ne(d.visible)?Promise.resolve([]):l.getOrFetch({cacheKey:yi(_,Yt(d)),fetcher:()=>ye(d,_),forceRefresh:y,snapshot:g,ttlMsOverride:w??se}):Promise.resolve([])},Zn=async d=>{let[p]=await d.select({id:f.id}).top(1).from(f).where(V(f.name,A)).orderBy(Ce(f.id));return p===void 0?null:p.id},eo=()=>Zn(t),Cs=(d,p)=>p!=null?"absent":d!=null?"present":"unknown",rr=async d=>{let p=new Map,y=r.attachment;if(d.length===0||!y||F===null)return p;let g=F.idCodec,w=F.thumbnails!==null,_=await t.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where(ot(y.hubId,d)).orderBy(Ce(y.createdAt),Ce(y.id));for(let I of _){let v=I.fileType?String(I.fileType):null,L=I.fileSize!=null?Number(I.fileSize):null,q=Cs(I.objectCheckedAt,I.objectMissingAt),Q={id:g.encode(Number(I.id)),fileName:String(I.fileName),fileType:v,fileSize:L,createdAt:xe(I.createdAt,"YYYY-MM-DD HH:mm:ss"),state:q,hasThumbnail:w&&q!=="absent"&&fr({fileType:v,fileSize:L},F.maxBytes)},J=p.get(Number(I.hubId));J?J.push(Q):p.set(Number(I.hubId),[Q])}return p},Ms=async(d,p,y)=>{let g=r.attachment;return!g||Ne(d.visible)?null:(await t.select({fileName:g.fileName,filePath:g.filePath,fileType:g.fileType,fileSize:g.fileSize}).top(1).from(g).innerJoin(s,V(s.id,g.hubId)).where(Ae(V(g.id,p),kt(s.deletedAt),Ue(y,"author"),ke(d.visible))))[0]??null},Ps=async d=>{let p=r.attachment;if(!p)return;let y=new Date;try{await t.update(p).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where(V(p.id,d))}catch(g){x.error("markAttachmentMissing failed",g)}},Ls=async d=>{let p=r.attachment;if(!p)return;let y=new Date;try{await t.update(p).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where(V(p.id,d))}catch(g){x.error("markAttachmentPresent failed",g)}},Br=async(d,p,y)=>{let g=await P(t.select({hub:at(s),internal:at(m),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,hasDraftLabel:it,...N()}).from(s)).leftJoin(m,V(s.id,m.hubId)).leftJoin(R,Ae(V(s.id,R.hubId),V(R.userId,p))).leftJoin(n,V(s.userId,n.id)).where(Ae(y,kt(s.deletedAt),Ue(p,"author"),ke(d.visible))).orderBy(Nt(s.id));if(g.length===0)return[];let w=g.map(j=>j.hub.id),_=await t.select({hubId:h.hubId,id:f.id,name:f.name,color:f.color}).from(h).innerJoin(f,V(h.labelId,f.id)).where(ot(h.hubId,w)),I=await t.select({hubId:u.hubId,id:u.id,body:u.body,createdAt:u.createdAt,userId:u.userId,userName:n.displayName}).from(u).leftJoin(n,V(u.userId,n.id)).where(ot(u.hubId,w)).orderBy(Ce(u.createdAt)),v=await rr(w),L=new Map,q=new Map;for(let j of _){let Z=L.get(j.hubId);Z||(Z=[],L.set(j.hubId,Z)),Z.push({id:j.id,name:j.name,color:j.color})}for(let j of I){let Z=q.get(j.hubId);Z||(Z=[],q.set(j.hubId,Z)),Z.push({id:j.id,content:j.body,createdAt:xe(j.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:j.userId,userName:j.userName||""})}let Q=g.map(U),J=await X(Q);return g.map((j,Z)=>{let ee=j.hub.id;return k(d,{...j,attachments:v.get(ee)??[],labels:L.get(ee)||[],postedCommentRows:q.get(ee)||[]},Q[Z],J,p)})},Ns=async(d,p,y,{forceRefresh:g=!1,snapshot:w=!1,ttlMsOverride:_,admission:I}={})=>{let v=await wt(y);if(!v)return[];let L=ve(p);if(!L)return[];if(Ne(d.visible))return[];let q=hi(L,v,Yt(d));return l.getOrFetch({cacheKey:q,fetcher:()=>Br(d,v,V(s.businessDate,Kn`${L}`)),forceRefresh:g,snapshot:w,admission:I,ttlMsOverride:_??se,epochKey:`${re}${L}`})},vt=async(d,p,y,{forceRefresh:g=!1,snapshot:w=!1,ttlMsOverride:_,admission:I}={})=>{if(Ne(d.visible))return null;let v=fi(p,y,Yt(d));return(await l.getOrFetch({cacheKey:v,fetcher:async()=>{let q=await P(t.select({hub:at(s),internal:at(m),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,hasDraftLabel:it,...N()}).from(s)).leftJoin(m,V(s.id,m.hubId)).leftJoin(R,Ae(V(s.id,R.hubId),V(R.userId,y))).leftJoin(n,V(s.userId,n.id)).where(Ae(V(s.id,p),kt(s.deletedAt),Ue(y,"author"),ke(d.visible)));if(q.length===0)return[];let Q=q[0].hub.id,J=await t.select({id:f.id,name:f.name,color:f.color}).from(h).innerJoin(f,V(h.labelId,f.id)).where(V(h.hubId,Q)),j=await t.select({id:u.id,body:u.body,createdAt:u.createdAt,userId:u.userId,userName:n.displayName}).from(u).leftJoin(n,V(u.userId,n.id)).where(V(u.hubId,Q)).orderBy(Ce(u.createdAt)),Z=await rr([Q]),ee=J.map(Je=>({id:Je.id,name:Je.name,color:Je.color})),Yr=j.map(Je=>({id:Je.id,content:Je.body,createdAt:xe(Je.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Je.userId,userName:Je.userName||""})),oo=U(q[0]),nl=await X([oo]);return[k(d,{...q[0],attachments:Z.get(Q)??[],labels:ee,postedCommentRows:Yr},oo,nl,y)]},forceRefresh:g,snapshot:w,admission:I,ttlMsOverride:_??se,epochKey:`${ce}${p}`}))[0]??null},ks=async(d,p,y,g={})=>{let w=await wt(y);return w?vt(d,p,w,g):null},vs=async(d,p,y)=>{if(p.length>_e.maxDetailIds)throw ne("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${_e.maxDetailIds} ids`,p.length);let g=await wt(y);return!g||p.length===0?[]:Ne(d.visible)?[]:Br(d,g,ot(s.id,[...p]))},Os=async(d,p)=>{let[y]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).where(Ae(V(s.id,d),Ue(p,"author")));return y??null},Vr=async(d,p,y)=>{let g=await Os(p,y);if(!g||g.deletedAt||!Le(d.visible,g.sourceType))throw new Error("Not Found")},Fs=async(d,p,y,g,w,_)=>{await Vr(d,y,p);let I=await t.select().top(1).from(R).where(Ae(V(R.hubId,y),V(R.userId,p))),v;if(I.length>0?I[0].isStarred!==w?v=(await t.update(R).set({isStarred:w,updatedAt:new Date,updatedBy:String(p)}).output().where(Ae(V(R.hubId,y),V(R.userId,p))))[0]:v=I[0]:v=(await t.insert(R).output().values({hubId:y,userId:p,isStarred:w,isRead:!1,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)}))[0],g){let L=ve(g);L&&(l.invalidatePrefix(Lt(L,p)),await oe(`${re}${L}`))}return l.invalidatePrefix(Cr(y,p)),await oe(`${ce}${y}`),await Ee(cr.parse({type:"status-update",reportHubId:y,recipientRawUserId:p,statusType:"star",value:w,clientTempId:_}),"setStarStatus"),v},Hs=async(d,p,y,g,w,_)=>{await Vr(d,y,p);let I=await t.select().top(1).from(R).where(Ae(V(R.hubId,y),V(R.userId,p))),v;if(I.length>0?I[0].isRead!==w?v=(await t.update(R).set({isRead:w,updatedAt:new Date,updatedBy:String(p)}).output().where(Ae(V(R.hubId,y),V(R.userId,p))))[0]:v=I[0]:v=(await t.insert(R).output().values({hubId:y,userId:p,isRead:w,isStarred:!1,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)}))[0],g){let L=ve(g);L&&(l.invalidatePrefix(Lt(L,p)),await oe(`${re}${L}`))}return l.invalidatePrefix(Cr(y,p)),await oe(`${ce}${y}`),await Ee(cr.parse({type:"status-update",reportHubId:y,recipientRawUserId:p,statusType:"read",value:w,clientTempId:_}),"setReadStatus"),v},to=async(d,p)=>{if(p!==null)return await st(d)?p:void 0},Us=async(d,p,y,g,w,_)=>{let[I]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where(V(s.id,y));if(!I||I.deletedAt)throw new Error("Not Found");if(await Vr(d,y,p),!Le(d.commentable,I.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(I.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let v=await to(y,I.userId),L=await pe(),q=await D(async Z=>{let[ee]=await Z.insert(u).output().values({hubId:y,userId:p,body:g,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)});return L!==null&&await L.writeHubs(Z,[y]),ee}),[Q]=await t.select({displayName:n.displayName}).top(1).from(n).where(V(n.id,p)),J=Q?.displayName??"";if(w){let Z=ve(w);Z&&(l.invalidatePrefix(Kt(Z)),await oe(`${re}${Z}`))}l.invalidatePrefix(Ge(y)),await oe(`${ce}${y}`);let j={id:q.id,userId:a(q.userId),userName:J,content:q.body,createdAt:xe(q.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await Ee(sn.parse({type:"comment-add",reportHubId:y,comment:j,clientTempId:_,recipientRawUserId:v,sourceType:I.sourceType}),"addComment"),j},$s=async(d,p)=>await d.select().top(1).from(u).where(V(u.id,p)),Bs=async(d,p,y,g,w,_)=>{let I=await $s(t,g);if(I.length===0)throw new Error("Not Found");if(I[0].hubId!==y)throw new Error("Not Found");let[v]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where(V(s.id,I[0].hubId));if(!(v&&Le(d.visible,v.sourceType)))throw new Error("Not Found");if(I[0].userId!==p)throw new Error("Unauthorized");let L=await to(y,v.userId),q=await pe();if(await D(async Q=>{await Q.delete(u).where(V(u.id,g)),q!==null&&await q.writeHubs(Q,[y])}),w){let Q=ve(w);Q&&(l.invalidatePrefix(Kt(Q)),await oe(`${re}${Q}`))}l.invalidatePrefix(Ge(y)),await oe(`${ce}${y}`),await Ee(ln.parse({type:"comment-delete",reportHubId:y,commentId:g,clientTempId:_,recipientRawUserId:L,sourceType:v?.sourceType}),"deleteComment")},Vs=async(d,p)=>{let y=new Map,g=r.attachment;if(!g||F===null)return y;let w=await d.select({hubId:g.hubId,fileName:g.fileName}).from(g).where(ot(g.hubId,[...p])).orderBy(Ce(g.hubId),Ce(g.createdAt),Ce(g.id));for(let _ of w)Jn(y,Number(_.hubId),String(_.fileName));return y},qs=async(d,p,y)=>{let g=new Map;for(let[w,_]of y){let I=new Map;for(let{hub:L}of p)L.sourceType===w&&L.sourceIdNum!==null&&I.set(L.sourceIdNum,L.id);if(I.size===0)continue;let v=await _(d,[...I.keys()]);for(let[L,q]of v){let Q=I.get(L);if(Q===void 0)throw ne(`search.externalSourceTexts.${w} answer key`,"a source id that was asked for",L);if(!(Array.isArray(q)&&q.every(J=>typeof J=="string")))throw ne(`search.externalSourceTexts.${w} answer for ${L}`,"an array of strings",q);g.set(Q,q)}}return g},Ys=(d,p)=>{let y=U(d),g=[["subject",d.hub.title],["content",y.content],["author",y.author],["employeeName",y.employeeName],["updatedBy",y.updatedBy],["category",y.category],["creationCategory",y.creationCategory],["customerName",y.customerName]];for(let _ of y.interviewers)g.push(["interviewerName",_.name??null],["interviewerAffiliation",_.affiliation??null]);for(let _ of p.labelNames)g.push(["label",_]);for(let _ of p.attachmentNames)g.push(["attachment",_]);for(let _ of p.extraTexts)g.push(["extra",_]);let w=[];for(let _ of y.externalComments)w.push({authorUserId:null,text:ss(_.name,_.text)});for(let _ of p.postedComments)w.push({authorUserId:_.userId,text:ss(_.userName,_.body)});return{hubId:d.hub.id,fields:g,comments:w,filterValues:{authorName:y.employeeName,customerName:y.customerName}}},js=async(d,p,y)=>{let g=[];for(let w of yp(p,hp)){let _=await P(d.select({hub:at(s),internal:at(m),creatorName:n.displayName,...N()}).from(s)).leftJoin(m,V(s.id,m.hubId)).leftJoin(n,V(s.userId,n.id)).where(ot(s.id,[...w])).orderBy(Ce(s.id)),I=new Map,v=await d.select({hubId:h.hubId,name:f.name}).from(h).innerJoin(f,V(h.labelId,f.id)).where(ot(h.hubId,[...w])).orderBy(Ce(h.hubId),Ce(f.id));for(let j of v)Jn(I,j.hubId,j.name);let L=new Map,q=await d.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,V(u.userId,n.id)).where(ot(u.hubId,[...w])).orderBy(Ce(u.hubId),Ce(u.createdAt),Ce(u.id));for(let j of q)Jn(L,j.hubId,j);let Q=await Vs(d,w),J=await qs(d,_,y);for(let j of _){let Z=j.hub.id;g.push(Ys(j,{labelNames:Hr(I,Z),postedComments:Hr(L,Z),attachmentNames:Hr(Q,Z),extraTexts:Hr(J,Z)}))}}return g},Ws=(d,p,y)=>H===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):H.search(t,{criteria:y,viewerUserId:p,scope:d}),ro=Object.freeze(Ap(["Internal",...b.map(d=>d.sourceType)])),zs=async(d,p)=>{if(H===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let y=ro.filter(_=>Le(d.visible,_)),g=await H.facetValues(t,{column:"authorName",viewerUserId:p,scope:d}),w=await H.facetValues(t,{column:"customerName",viewerUserId:p,scope:d});return{sourceTypes:y,authors:g,customers:w}},Gs=async(d,p,y,g,w)=>{let _=Dp("markDailyReportSearchHits",w);if(H===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(g.length>_e.maxDetailIds)throw ne("markDailyReportSearchHits: reportHubIds",`at most ${_e.maxDetailIds} ids`,g.length);let I=ir(Wt(y));if(g.length===0||Ne(d.visible))return{wordsDigest:I,reports:[],deferred:[]};_.throwIfAborted();let v=await Br(d,p,ot(s.id,[...g]));_.throwIfAborted();let L=y.combine==="union"&&y.sets.length>=2&&v.length>0?await H.matchedSets(t,{plan:y,viewerUserId:p,scope:d,ids:v.map(j=>j.reportHubId)}):null,q=v.map(j=>{let Z=L===null?null:L.get(j.reportHubId),ee=Z===void 0?0:Z;return{reportHubId:j.reportHubId,matchedSets:ee,alternatives:rs(y,ee).flatMap(Yr=>Yr.alternatives),fields:ns(j)}}),J=await os(q,Gn,async()=>{await new Promise(j=>setImmediate(j)),_.throwIfAborted()},Xi(Gn,ue));return{wordsDigest:I,reports:J.reports,deferred:J.deferred}},Ks=async d=>{let p=await pe();if(p===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return p.reconcile(t,d)},Js=async(d,p,y)=>{if(!or(p))throw ne("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",p);x.info("createDailyReport called",{userId:d,businessDate:p});let[g]=await t.select({displayName:n.displayName}).from(n).where(V(n.id,d)),w=g?.displayName??a(d),_=await pe();try{let I=await D(async L=>{x.info("Starting transaction");let q=await Zn(L);if(q===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(A)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let Q=`internal-temp-${Date.now()}-${Math.random()}`,[J]=await L.insert(s).output().values({sourceType:"Internal",sourceId:Q,businessDate:new Date(`${p}T00:00:00Z`),userId:d,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)});await L.update(s).set({sourceId:String(J.id)}).where(V(s.id,J.id)),x.info("Hub created",J),await L.insert(m).values({hubId:J.id,body:"",createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}),x.info("Internal created"),await L.insert(h).values({hubId:J.id,labelId:q,createdAt:new Date,createdBy:String(d)});let j=[{id:q,name:A,color:null}];return x.info("Label assigned"),_!==null&&await _.writeHubs(L,[J.id]),{reportHubId:J.id,date:p,createdAt:xe(J.createdAt,"YYYY-MM-DD HH:mm:ss"),author:w,userId:a(d),sourceType:"Internal",employeeName:w,updatedBy:a(d),updatedAt:xe(J.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:J.title,content:"",externalComments:[],isRead:!0,isStarred:!1,isDraft:!0,labels:j,postedComments:[],attachments:[]}});l.invalidatePrefix(Lt(p,d)),l.invalidatePrefix(bt),l.invalidatePrefix(Un(d)),await oe(G),await oe(`${re}${p}`);let v=await vt(He.unrestricted("post-write self read: the writer always sees the row they just wrote"),I.reportHubId,d,{forceRefresh:!0});if(v){let L=await st(v.reportHubId);await Ee(cn.parse({type:"report-create",reportHubId:v.reportHubId,report:v,clientTempId:y,recipientRawUserId:L?d:void 0}),"createDailyReport")}return v??I}catch(I){throw x.error("Error in createDailyReport",I),I}},nr=async(d,p)=>await d.select().top(1).from(s).where(V(s.id,p)),qr=async(d,p,y)=>{await d.update(s).set(y).where(V(s.id,p))},no=async(d,p,y)=>{await d.update(m).set(y).where(V(m.hubId,p))},Qs=async(d,p,y)=>{await d.delete(h).where(Ae(V(h.hubId,p),V(h.labelId,y)))},Xs=async(d,p,y)=>{let g=await nr(t,d);if(!g.length||g[0].deletedAt)throw new Error("Not Found");if(g[0].userId!==p)throw new Error("Unauthorized");if(await D(async w=>{await qr(w,d,{deletedAt:new Date,deletedBy:String(p),updatedAt:new Date,updatedBy:String(p)})}),l.invalidatePrefix(Ge(d)),l.invalidatePrefix(bt),l.invalidatePrefix(gt),await oe(G),g[0].businessDate){let w=ve(xe(g[0].businessDate,"YYYY-MM-DD"));w&&await oe(`${re}${w}`)}await Ee(pn.parse({type:"report-delete",reportHubId:d,clientTempId:y,sourceType:g[0].sourceType}),"deleteDailyReport")},Zs=async(d,p,y,g)=>{let w=await nr(t,d);if(!w.length||w[0].deletedAt)throw new Error("Not Found");if(w[0].userId!==p)throw new Error("Unauthorized");let _=await pe();await D(async L=>{y.title!==void 0&&await qr(L,d,{title:is(y.title),updatedAt:new Date,updatedBy:String(p)}),y.content!==void 0&&await no(L,d,{body:is(y.content),updatedAt:new Date,updatedBy:String(p)}),_!==null&&await _.writeHubs(L,[d])}),l.invalidatePrefix(Ge(d)),l.invalidatePrefix(bt),await oe(`${ce}${d}`);let I=ve(xe(w[0].businessDate,"YYYY-MM-DD"));I&&(l.invalidatePrefix(Kt(I)),await oe(`${re}${I}`));let v=await vt(He.unrestricted("post-write self read: the writer always sees the row they just wrote"),d,p,{forceRefresh:!0});if(v){let L=await st(d);await Ee(un.parse({type:"report-update",reportHubId:v.reportHubId,report:v,clientTempId:g,recipientRawUserId:L?p:void 0}),"updateDailyReport")}},el=async(d,p,y)=>{let g=await nr(t,d);if(!g.length)throw new Error("Not Found");if(g[0].userId!==p)throw new Error("Unauthorized");let w=await pe();if(await D(async v=>{await v.delete(h).where(Ae(V(h.hubId,d),Li(M,S))),w!==null&&await w.writeHubs(v,[d])}),l.invalidatePrefix(Ge(d)),l.invalidatePrefix(bt),l.invalidatePrefix(gt),await oe(G),g[0].businessDate){let v=ve(xe(g[0].businessDate,"YYYY-MM-DD"));v&&await oe(`${re}${v}`)}let _=ve(xe(g[0].businessDate,"YYYY-MM-DD"));_&&l.invalidatePrefix(Lt(_,p));let I=await vt(He.unrestricted("post-write self read: the writer always sees the row they just wrote"),d,p,{forceRefresh:!0});if(I){let v=await st(d);await Ee(dn.parse({type:"report-publish",reportHubId:I.reportHubId,report:I,clientTempId:y,recipientRawUserId:v?p:void 0}),"publishDailyReport")}return I??null},tl=async(d,p)=>{l.invalidatePrefix(bt),l.invalidatePrefix(gt),await oe(G);for(let y of new Set(d))l.invalidatePrefix(Ge(y)),await oe(`${ce}${y}`);for(let y of new Set(p)){let g=ve(y);g&&await oe(`${re}${g}`)}},rl=async()=>{l.clearAll(),tr.clear(),c&&await oe(G),x.info("Server-side DB/SQL caches cleared successfully.")};return{streamKey:he,streamMaxLen:Ke,attachmentDelivery:F,titleMaxLength:E,searchLimits:$===null?null:{concurrency:$.concurrency,rateLimitPerMinute:$.rateLimitPerMinute},searchFilterSourceTypes:ro,clearCache:rl,invalidateHubReadCaches:tl,getUserIdByExternalId:wt,getDailyReportIdsByExternalId:_s,getDailyReportIdsFirstPageByExternalId:fe,readSseStreamAnchor:T,getDailyReportsByBusinessDate:xs,getDailyReportsByBusinessDateByExternalId:Ns,getDailyReportDetailById:vt,getDailyReportDetailByIdByExternalId:ks,getDailyReportDetailsByIdsByExternalId:vs,getDraftLabelId:eo,searchDailyReports:Ws,markDailyReportSearchHits:Gs,listDailyReportSearchFacets:zs,reconcileSearchIndex:Ks,getAttachmentsByHubIds:rr,getAttachmentForUser:Ms,markAttachmentMissing:Ps,markAttachmentPresent:Ls,setStarStatus:Fs,setReadStatus:Hs,addComment:Us,deleteComment:Bs,createDailyReport:Js,updateDailyReport:Zs,publishDailyReport:el,deleteDailyReport:Xs,findDailyReportHubById:nr,updateDailyReportHub:qr,updateDailyReportInternal:no,deleteDailyReportLabel:Qs}}var Tp=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(Se(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return Se(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};import{desc as ls,sql as Ep}from"drizzle-orm";import{bigint as Te,bit as cs,date as wp,datetime2 as Ie,foreignKey as Ye,index as yt,int as Ip,mssqlSchema as _p,nvarchar as le,primaryKey as Et,uniqueIndex as xp}from"drizzle-orm/mssql-core";function Cp(e,t){let r=_p(e),n=t.userTable,o=r.table("DailyReportHub",{id:Te("id",{mode:"number"}).identity().notNull(),sourceType:le("source_type",{length:20}).notNull(),sourceId:le("source_id",{length:100}).notNull(),sourceIdNum:Te("source_id_num",{mode:"number"}).generatedAlwaysAs(Ep`TRY_CAST(source_id AS BIGINT)`),businessDate:wp("business_date"),userId:Te("user_id",{mode:"number"}),title:le("title",{length:200}),summary:le("summary",{length:"max"}),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull(),deletedAt:Ie("deleted_at"),deletedBy:le("deleted_by",{length:50})},u=>[Et({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),Ye({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),yt(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),yt(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),yt(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),yt(`${e}_DailyReportHub_user_id_index`).on(u.userId),yt(`${e}_DailyReportHub_business_date_id_index`).on(ls(u.businessDate),ls(u.id)),yt(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:Te("hub_id",{mode:"number"}).notNull(),body:le("body",{length:"max"}),metadata:le("metadata",{length:"max"}),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Et({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),Ye({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:Te("id",{mode:"number"}).identity().notNull(),hubId:Te("hub_id",{mode:"number"}).notNull(),userId:Te("user_id",{mode:"number"}).notNull(),body:le("body",{length:"max"}).notNull(),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Et({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),Ye({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Ye({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),yt(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:Te("id",{mode:"number"}).identity().notNull(),userId:Te("user_id",{mode:"number"}),name:le("name",{length:50}).notNull(),color:le("color",{length:20}),sortOrder:Ip("sort_order"),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Et({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),Ye({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),c=r.table("DailyReportHub_Label",{hubId:Te("hub_id",{mode:"number"}).notNull(),labelId:Te("label_id",{mode:"number"}).notNull(),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull()},u=>[Et({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),Ye({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Ye({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),s=r.table("DailyReportUserStatus",{hubId:Te("hub_id",{mode:"number"}).notNull(),userId:Te("user_id",{mode:"number"}).notNull(),isRead:cs("is_read").default(!1).notNull(),isStarred:cs("is_starred").default(!1).notNull(),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Et({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),Ye({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Ye({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),m=r.table("DailyReportAttachment",{id:Te("id",{mode:"number"}).identity().notNull(),hubId:Te("hub_id",{mode:"number"}).notNull(),uploadedBy:Te("uploaded_by",{mode:"number"}),sourceKey:le("source_key",{length:200}).notNull(),fileName:le("file_name",{length:255}).notNull(),filePath:le("file_path",{length:"max"}).notNull(),fileType:le("file_type",{length:100}),fileSize:Te("file_size",{mode:"number"}),objectCheckedAt:Ie("object_checked_at"),objectMissingAt:Ie("object_missing_at"),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Et({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),Ye({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Ye({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),xp(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),yt(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:m,label:l,hubLabel:c,userStatus:s}}import{bigint as Xn,binary as us,datetime2 as Mp,int as Pp,mssqlSchema as Lp,nvarchar as Ur,primaryKey as ds,varchar as Np}from"drizzle-orm/mssql-core";function kp(e){let t=Lp(e),r=t.table("DailyReportSearchDocument",{hubId:Xn("hub_id",{mode:"number"}).notNull(),searchText:Ur("search_text",{length:"max"}).notNull(),sourceDigest:us("source_digest",{length:32}).notNull(),normalizerVersion:Np("normalizer_version",{length:64}).notNull(),indexedAt:Mp("indexed_at").notNull(),rowVersion:us("row_version",{length:8}).notNull(),authorName:Ur("author_name",{length:Ze.maxValueLength}),customerName:Ur("customer_name",{length:Ze.maxValueLength})},o=>[ds({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:Xn("hub_id",{mode:"number"}).notNull(),ordinal:Pp("ordinal").notNull(),authorUserId:Xn("author_user_id",{mode:"number"}),commentText:Ur("comment_text",{length:"max"}).notNull()},o=>[ds({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var vp=5e7,As=2e8,Op=1,Ts=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})})}),ps=125,ms=4,ys=16,hs=50,fs=2,$r=Object.freeze({renderMs:Pe.renderMs,nanosecondsPerBlockVisit:ps,margin:ms,maxBlockVisits:Math.floor(Pe.renderMs*1e6/(ps*ms)),walkBudgetMs:ys,nanosecondsPerWalkStep:hs,walkMargin:fs,maxWalkSteps:Math.floor(ys*1e6/(hs*fs))}),Fp=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Rs=75,Ss=4,gs="#ffffff",Hp=1,Up={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},$p=[/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/],bs=Object.freeze({ok:!1,reason:"failed"}),Ds=Object.freeze({ok:!1,reason:"unsupported"}),Es=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:ma(e)}),ws=(e,t)=>{switch(t){case"jpeg":{let r=Cn(e);return r===null?null:Es(r)}case"png":{let r=fa(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Ra(e,$r.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},Is=(e,t)=>{let r=Fp.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Ts,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},Bp=(e,t,r)=>{let n=ws(e,t);return n===null?null:Is(n,r)},Vp=e=>e!==null&&e<=As,qp=(e,t)=>{if(t!=="jpeg")return ws(e,t);let r=ya(e,$r);return r===null||r.blockVisits>$r.maxBlockVisits?null:Es(r.header)},Yp=e=>{let t=e instanceof Error?e.message:"";return $p.some(r=>r.test(t))?"failed":"unsupported"},jp=e=>{e.cache(!1),e.concurrency(Op),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Up)});let t=async(n,o,a,i,l)=>{let c=qp(n,o);if(c===null)return Ds;try{let s=e(n,{limitInputPixels:vp,animated:!1});if(!Vp(Is(c,await s.metadata())))return Ds;if(l.aborted)return bs;let m=await s.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:gs}).webp({quality:Rs,effort:Ss}).toBuffer();return{ok:!0,bytes:new Uint8Array(m),contentType:"image/webp"}}catch(s){return{ok:!1,reason:Yp(s)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?bs:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Rs}-e${Ss}/flatten-${gs}/v${Hp}`,render:r}};var Wp=4096,zp=512*1024*1024,Gp=6e4;function cS(e){e.redis||Se(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=Kr(e.redis),r=new Ht({defaultTtlMs:te("cacheDefaultTtlMs",e.cacheDefaultTtlMs??Gp,1),maxBuckets:te("cacheMaxBuckets",e.cacheMaxBuckets??Wp,1),maxBytes:te("cacheMaxBytes",e.cacheMaxBytes??zp,1)},t),n=Qn({...e,cache:r,epochs:t}),o=new Jt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Bn({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(i=>i.sourceType)])],...a}}export{Pn as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,Mn as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,As as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,$r as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,Ts as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,$n as DAILY_REPORT_SSE_CATCH_UP_BATCH,bi as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,Jt as DailyReportSseReader,He as DailyReportViewerScope,Ht as SqlResultCache,Bn as createDailyReportHandlers,cS as createDailyReportServer,Qn as createDailyReportService,Kr as createEpochStore,jp as createSharpThumbnailRenderer,Cp as defineDailyReportSchema,kp as defineDailyReportSearchSchema,_t as encodeIdsStreamRows,dt as isStreamIdLte,yn as parseClientTempId,Bp as predictSharpThumbnailWorkingSetBytes,Gt as readDailyReportSseStreamEntry,Tp as transformJsonArray};
12
12
  /* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */