@aiquants/daily-report 0.43.0 → 0.44.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +178 -0
- package/README.md +211 -86
- package/dist/client.d.mts +11 -25
- package/dist/client.d.ts +11 -25
- package/dist/client.js +5 -5
- package/dist/client.mjs +5 -5
- package/dist/index.d.mts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/instrumentation-CobsTeyw.d.mts +70 -0
- package/dist/instrumentation-Dz7Uh7dT.d.ts +70 -0
- package/dist/{search-marks-wire-BSS2d1t6.d.ts → search-marks-wire-BiImBos8.d.mts} +16 -1
- package/dist/{search-marks-wire-BSS2d1t6.d.mts → search-marks-wire-C_vjmxwf.d.ts} +16 -1
- package/dist/server.d.mts +9 -5
- package/dist/server.d.ts +9 -5
- package/dist/server.js +10 -10
- package/dist/server.mjs +10 -10
- package/dist/{source-types-Bu-_yfcY.d.ts → source-types-Cg7T2dm6.d.ts} +1 -1
- package/dist/{source-types-NkQm-gNO.d.mts → source-types-Hy_znWJl.d.mts} +1 -1
- package/dist/{sse-schema-Br0b278w.d.mts → sse-schema-BcjRPJjN.d.ts} +2 -75
- package/dist/{sse-schema-Br0b278w.d.ts → sse-schema-sKBorzg9.d.mts} +2 -75
- package/dist/styles/daily-report.standalone.css +1 -1
- package/dist/testing.d.mts +39 -0
- package/dist/testing.d.ts +39 -0
- package/dist/testing.js +1 -0
- package/dist/testing.mjs +1 -0
- package/dist/types-BP1kIGMo.d.mts +75 -0
- package/dist/types-BP1kIGMo.d.ts +75 -0
- package/package.json +8 -3
package/dist/server.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
"use strict";var mn=Object.defineProperty;var sc=Object.getOwnPropertyDescriptor;var lc=Object.getOwnPropertyNames;var cc=Object.prototype.hasOwnProperty;var Lo=e=>{throw TypeError(e)};var uc=(e,t)=>{for(var r in t)mn(e,r,{get:t[r],enumerable:!0})},dc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of lc(t))!cc.call(e,o)&&o!==r&&mn(e,o,{get:()=>t[o],enumerable:!(n=sc(t,o))||n.enumerable});return e};var pc=e=>dc(mn({},"__esModule",{value:!0}),e);var ko=(e,t,r)=>t.has(e)||Lo("Cannot "+r);var Xt=(e,t,r)=>(ko(e,t,"read from private field"),r?r.call(e):t.get(e)),yn=(e,t,r)=>t.has(e)?Lo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),hn=(e,t,r,n)=>(ko(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var km={};uc(km,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>Hr,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>Fr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>_o,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Dr,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>xo,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>Xr,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>ho,DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS:()=>Co,DailyReportSseReader:()=>zt,DailyReportViewerScope:()=>Be,SqlResultCache:()=>Ot,buildDailyReportSseStreamKey:()=>Io,createDailyReportHandlers:()=>Zr,createDailyReportServer:()=>Lm,createDailyReportService:()=>un,createDailyReportVisibilityCache:()=>jl,createEpochStore:()=>Ar,createSharpThumbnailRenderer:()=>Yl,dailyReportSseStreamMessageSchema:()=>_r,defineDailyReportSchema:()=>xl,defineDailyReportSearchSchema:()=>Cl,encodeIdsStreamRows:()=>_t,isStreamIdLte:()=>pt,parseClientTempId:()=>Lr,predictSharpThumbnailWorkingSetBytes:()=>ql,readDailyReportSseStreamEntry:()=>Yt,transformJsonArray:()=>_l});module.exports=pc(km);var Et=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,Q=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Et(r)}`),Qe=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),fn=(e,t,r)=>Q(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),se=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw Q(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},xe=(e,t,r,n)=>t===void 0?n:se(e,t,r),Zt=(e,t)=>{if(t===void 0)throw Qe(e,"a function");if(typeof t!="function")throw Q(e,"a function",t);return t};var le=()=>Math.floor(performance.now());var Rn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),Ye=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},Ar=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{}}}),er=(e,t)=>t?e.map(r=>structuredClone(r)):e,mc=8,yc=32,hc=24,fc=16,Rc=-(2**30),Sc=2**30-1,gc=e=>Number.isInteger(e)&&e>=Rc&&e<=Sc&&!Object.is(e,-0),bc=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=yc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=mc*a.length;for(let i of a)typeof i=="string"?r+=hc+2*i.length:typeof i=="number"&&!gc(i)?r+=fc:typeof i=="object"&&i!==null&&n.push(i)}return r},Ot=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-le())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:c,expireAt:le()+a,epoch:s}),c})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&s===null)throw new Ye(o.signal.aborted?"aborted":"busy");try{for(let d of r)d();let c=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:c,expireAt:le()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),c}finally{s?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new Ye("aborted");return this.dropBucket(r),er(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>le())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),er(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),er(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return er(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new Ye("aborted");return er(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 Ye&&(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=xe("cacheDefaultTtlMs",t.defaultTtlMs,1,Rn.defaultTtlMs),this.maxBuckets=xe("cacheMaxBuckets",t.maxBuckets,1,Rn.maxBuckets),this.maxBytes=xe("cacheMaxBytes",t.maxBytes,1,Rn.maxBytes),this.lastSweepAt=le()}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=bc(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=le();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 vs=require("@aiquants/request-isolation");var Dc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var No=e=>e<10?`0${e}`:`${e}`,Ac=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=No(e.getMonth()+1),n=No(e.getDate());return`${t}-${r}-${n}`},Ft=e=>{let t=Dc.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let s=new Date(0);return s.setUTCFullYear(a,i-1,l),s.getUTCFullYear()!==a||s.getUTCMonth()!==i-1||s.getUTCDate()!==l?null:`${r}-${n}-${o}`},Tr=e=>Ft(e)===e;var Ne=e=>e==null?null:e instanceof Date?Ac(e):Ft(e);var vo=require("zod/v3"),Xe=e=>Number.isSafeInteger(e)&&e>0,je=vo.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var ne=require("zod/v3");var Er=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;var wt=Symbol("daily-report wire mismatch"),Ze=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),wt),Uo=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,It=(e,t)=>({code:"invalid_type",expected:e,received:Uo(t)}),Tc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ec=e=>{let t=0;for(let r in e)t+=1;return t},Oo=(e,t,r)=>{let n={};for(let o=0;o<r;o+=1){let a=t[o];a in e&&(n[a]=e[a])}return n},Ht=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!Tc(n))return Ze(o,null,It("object",n));let a=null,i=!1,l=0;for(let s=0;s<t.length;s+=1){let c=t[s],d=n[c];d!==void 0&&(l+=1);let u=r[s](d,o,c);if(u===wt){i=!0;continue}a===null&&u!==d&&(a=Oo(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?wt:a!==null?a:Ec(n)===l?n:Oo(n,t,t.length)}},tr=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},rr=e=>(t,r,n)=>{if(!Array.isArray(t))return Ze(r,n,It("array",t));r.path.push(n);let o=t,a=!1;for(let i=0;i<t.length;i+=1){let l=t[i],s=e(l,r,i);s===wt?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?wt:o},ue=(e,t,r)=>e==null||typeof e=="string"?e:Ze(t,r,It("string",e)),Fo=(e,t,r)=>e===null||typeof e=="string"?e:Ze(t,r,It("string",e)),Ho=(e,t,r)=>typeof e=="string"?e:Ze(t,r,It("string",e)),wc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:Ze(t,r,It("number",e)),nr=(e,t,r)=>typeof e=="boolean"?e:Ze(t,r,It("boolean",e)),Sn=(e,t,r)=>{if(typeof e=="number"&&Xe(e))return e;for(let{message:n,path:o,...a}of je.safeParse(e).error.issues)Ze(t,r,a);return wt},$o={present:!0,absent:!0,unknown:!0},Bo=Object.keys($o),Ic=Bo.map(e=>`'${e}'`).join(" | "),_c=(e,t,r)=>typeof e!="string"?Ze(t,r,{code:"invalid_type",expected:Ic,received:Uo(e)}):Object.hasOwn($o,e)?e:Ze(t,r,{code:"invalid_enum_value",received:e,options:[...Bo]}),Vo=Ht({name:ue,affiliation:ue}),qo=Ht({name:ue,text:ue,color:ue}),Yo=Ht({id:Sn,name:ue,color:ue}),jo=Ht({id:Sn,userId:ue,userName:ue,content:ue,createdAt:ue,isMine:nr}),xc=Ht({id:Ho,fileName:Ho,fileType:Fo,fileSize:wc,createdAt:Fo,state:_c,hasThumbnail:nr}),Cc=Ht({reportHubId:Sn,date:ue,createdAt:ue,author:ue,userId:ue,sourceType:ue,employeeName:ue,updatedBy:ue,updatedAt:ue,category:ue,creationCategory:ue,visitTimeFrom:ue,visitTimeTo:ue,customerName:ue,interviewers:rr(tr(Vo)),subject:ue,content:ue,externalComments:rr(tr(qo)),isRead:nr,isStarred:nr,isDraft:nr,labels:rr(tr(Yo)),postedComments:rr(tr(jo)),attachments:rr(tr(xc))}),or=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===wt?{ok:!1,issues:r.issues}:{ok:!0,value:n}},Wo=e=>or(Cc,e),zo=e=>or(Vo,e),Go=e=>or(qo,e),Ko=e=>or(Yo,e),Jo=e=>or(jo,e);var Qo=15e3,Xo="lastEventId",Mc=/^\d{1,15}-\d{1,15}$/,Zo=e=>Mc.test(e),ar=e=>ne.z.unknown().transform((t,r)=>{let n=e(t);if(n.ok)return n.value;for(let o of n.issues)r.addIssue({...o,fatal:!0});return ne.z.NEVER}),Gm=ar(zo),Km=ar(Go),Jm=ar(Ko),Pc=ar(Jo),Lc=ar(Wo),ir=ne.z.string().regex(Er),ea=ne.z.object({type:ne.z.literal("connected")}),ta=ne.z.object({type:ne.z.literal("status-update"),reportHubId:je,statusType:ne.z.enum(["star","read"]),value:ne.z.boolean(),clientTempId:ir}),gn=ne.z.string(),ra=ne.z.object({type:ne.z.literal("comment-add"),reportHubId:je,comment:Pc,clientTempId:ir,sourceType:gn}),na=ne.z.object({type:ne.z.literal("comment-delete"),reportHubId:je,commentId:je,clientTempId:ir,sourceType:gn}),wr={recipientRawUserId:je.optional()},bn=ta.extend(wr),Dn=ra.extend(wr),An=na.extend(wr),Ut={reportHubId:je,report:Lc,clientTempId:ir},Tn={...wr,actorRawUserId:je},En={viewerIsActor:ne.z.boolean()},kc=ne.z.object({type:ne.z.literal("report-create"),...Ut,...En}),Nc=ne.z.object({type:ne.z.literal("report-update"),...Ut,...En}),vc=ne.z.object({type:ne.z.literal("report-publish"),...Ut,...En}),wn=ne.z.object({type:ne.z.literal("report-create"),...Ut,...Tn}),In=ne.z.object({type:ne.z.literal("report-update"),...Ut,...Tn}),_n=ne.z.object({type:ne.z.literal("report-publish"),...Ut,...Tn}),Ir=ne.z.object({type:ne.z.literal("report-delete"),reportHubId:je,clientTempId:ir,sourceType:gn}),Qm=ne.z.discriminatedUnion("type",[ea,ta,ra,na,kc,Nc,vc,Ir]),_r=ne.z.discriminatedUnion("type",[ea,bn,Dn,An,wn,In,_n,Ir]);var oa="ids-columns";var Oc=/^[0-9a-f]{1,16}$/,aa=e=>Xe(e.reportHubId)&&(e.businessDate===null||Tr(e.businessDate)),ia=e=>typeof e=="string"&&Oc.test(e),ty=Object.freeze({kind:"absent"}),ry=Object.freeze({kind:"value",value:null});var _t=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:R}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let p=R===void 0?null:R,m=s.get(p);m===void 0&&(m=i.length,i.push(p),s.set(p,m)),l.push(m)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},xr=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+(?=.)/,"")},sa=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Fc=(e,t,r,n)=>sa(e,t,r,n)<0,xn=(e,t)=>sa(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),la=e=>{for(let t=1;t<e.length;t++)if(!Fc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},ca=(e,t)=>{let r=e.findIndex(n=>xn({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var ce=Object.freeze({businessDate:"business-date",idsStream:oa,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),ge=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var ua=(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)}}},iy=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),da=e=>`[DailyReport${e}]`,be=(e,t,r)=>e===void 0?ua(t,da(r)):ua(0,da(r),e);var Hc="legacy-",Cn=e=>`${Hc}${e}`;var Uc=/^[1-9][0-9]*$/,$c=/^(?:0|[1-9][0-9]*)$/,We=e=>{if(e===null||!Uc.test(e))return null;let t=Number(e);return Xe(t)?t:null},Mn=e=>{if(e===null||!$c.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Pn=e=>e==="true"?!0:e==="false"?!1:null,sr=e=>e===null?!1:Pn(e);var pa=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),it=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var Bc=16777619,Ln=2166136261,kn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,Bc);return o>>>0},ma=e=>kn(Ln,e,0,e.length),Vc=String.fromCodePoint(3),qc=String.fromCodePoint(2),Yc=String.fromCodePoint(1),Cr=e=>ma(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Vc)).join(qc)).join(Yc));var ya=e=>e==="intersection"||e==="union",Ie=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Nn=2,Mr=2,xt=Object.freeze({word:0,reading:1});var vn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var py=2*(1+Nn);var jc=require("zod/v3");var $e=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var Pr=Math.max(1,Math.floor(10.556701030927835));var ze=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Me=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(c=>[c,0]))};o.set(i,l),ze(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var st=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var gy=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),Wc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,On=e=>{let t=e.trim();return t.length===0?null:t.replace(Wc,"\uFFFD")},zc=e=>{let t=On(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>st.maxValueLength?"filter-value-too-long":null},Gc=e=>{if(e.length>st.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=zc(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},Kc=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},ha=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Gc(t);if(r!==null)return r}return Kc(e)>st.maxTotalValueLength?"filters-too-long":null};var fa=e=>e.trim().length===0;var Lr=e=>e!==null&&Er.test(e)?e:null,Fn=e=>ya(e)?e:null,Hn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Ie.maxDetailIds)return null;let r=[];for(let n of t){let o=We(n);if(o===null||r.includes(o))return null;r.push(o)}return r},Ra=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},Sa=(e,t)=>{let r={authors:e.getAll(ge.searchAuthor),sourceTypes:e.getAll(ge.searchSourceType),customers:e.getAll(ge.searchCustomer)},n=ha(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:Ra(r.authors),customers:Ra(r.customers)}}},ga=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Da=Object.freeze({status:400,error:"Invalid form"}),Aa=e=>({status:413,error:"Form too large",measuredBy:e}),Jc=(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)}}))},Qc=async e=>{let t=Mn(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Aa("declared")};let r=!1,n=e.body===null?null:Jc(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?Aa("counted"):Da}}let l=ga(i);return l===null?{refusal:Da}:{fields:l}},Ta=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=Pn(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},wa=Object.freeze({update:(e,t,r)=>{let n=e.get($e.title),o=e.get($e.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:Ta("toggleStar",$e.isStarred),toggleRead:Ta("toggleRead",$e.isRead),addComment:(e,t)=>{let r=e.get($e.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=We(e.get($e.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Xc=e=>Object.hasOwn(wa,e),Zc=(e,t)=>{let r=e.get($e.intent),n=e.get($e.businessDate),o=n===null?null:Ft(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get($e.operationTimestamp),i=Mn(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get($e.clientTempId);if(!l)return{error:"clientTempId required"};let s=Lr(l);if(s===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:i}};let c=We(e.get($e.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!Xc(r)?{error:"Invalid intent"}:wa[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Ia=async(e,t)=>{let r=await Qc(e);if("refusal"in r)return r;let n=Zc(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},eu=6e4,tu="form_too_large",Ea=["declared","counted"],_a=e=>{let t=Me({windowMs:eu,tallies:Ea,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Ea.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(tu,r,n)}};var Ct=Object.freeze({[ce.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ce.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[ce.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ce.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[ce.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[ce.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[ce.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),xa=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Un=e=>e!==void 0&&Object.hasOwn(Ct,e);var $n=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Ca=e=>Object.hasOwn($n,e);var ru="download",nu="thumbnail",ou="1";var Bn=e=>{let t=e.getAll(nu),r=e.getAll(ru);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Ca(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===ou?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var Na=require("@aiquants/request-isolation");var Ma=require("crypto"),Vn=e=>`"${(0,Ma.createHash)("sha256").update(e).digest("hex")}"`,Pa=e=>Vn(JSON.stringify(e));var et=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),qn=(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},La=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=Vn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...et});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&qn(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},Yn=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...et});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},jn=e=>(t,r,n,o)=>{if(o!==200)return Yn(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)},au=5e3/1e3,iu=new Map([[503,au]]),De=e=>{let t=iu.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var zn="Cross-site request rejected",su="Not Found",ka=["api","action","sse","attachment"],va=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...et}}),lu=()=>va(403,zn),kr=()=>va(404,su),lr=Object.freeze({...Na.NO_CROSS_ORIGIN_NAVIGATION,frameworkDataRefusal:()=>null,crossSiteRejection:lu}),Oa=e=>new URL(e.url).pathname.endsWith(".data"),cu=6e4,uu="refusals",du=32,pu=/^[a-z-]+$/,Wn=e=>{if(e===null)return"-";let t=e.slice(0,du);return pu.test(t)&&t===e?e:JSON.stringify(t)},Fa=e=>{let t=Me({windowMs:cu,tallies:ka,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${ka.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n,o)=>{let a=()=>{let{headers:i}=o;e.warn(`cross_site_rejected route=${r} reason=${n} site=${Wn(i.get("Sec-Fetch-Site"))} mode=${Wn(i.get("Sec-Fetch-Mode"))} dest=${Wn(i.get("Sec-Fetch-Dest"))} method=${o.method}`)};t.record(uu,r,a)}};var Ha=(e,t)=>(r,n)=>{let o=n?"markAttachmentPresent":"markAttachmentMissing";e[o](r).catch(a=>{t.error(`${o} failed attachment=${r} message=${a instanceof Error?a.message:"unknown"}`)})};var mu="same-origin",yu="SAMEORIGIN",$t=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":mu,"X-Frame-Options":yu}),Nr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...$t});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Ua=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),hu=/^[\x20-\x7E]+$/,fu=/^[\w.+-]+\/[\w.+-]+/,Gn=e=>e&&hu.test(e)&&fu.test(e)?e:null,Ru=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,$a=e=>encodeURIComponent(e.replace(Ru,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Ba=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),cr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},Va={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},vr=e=>typeof e=="string"&&Object.hasOwn(Va,e),Or=e=>Va[e],lt="Attachment request failed";var tt=e=>{let t=se("limit",e.limit,1),r=se("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:se("queue.max",e.queue.max,0),maxPerOwner:se("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:se("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(y,S)=>y.get(S)??0,c=(y,S,T)=>{let D=s(y,S)+T;D<=0?y.delete(S):y.set(S,D)},d=y=>s(l,y)<r,u=y=>o<t&&d(y),R=y=>(o+=1,c(l,y,1),h(y)),p=()=>{let y=-1,S=r;for(let[T,D]of a.entries()){let f=s(l,D.owner);if(f<S&&(y=T,S=f,f===0))break}return y},m=()=>{for(;o<t;){let y=p();if(y<0)return;let[S]=a.splice(y,1);c(i,S.owner,-1),S.grant(R(S.owner))}},h=y=>{let S=!1;return()=>{S||(S=!0,o-=1,c(l,y,-1),m())}};return{canAcquire:u,acquire:(y,S)=>{if(S.aborted)return Promise.resolve(null);if(u(y))return Promise.resolve(R(y));if(n===null||a.length>=n.max||s(i,y)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:T}=n,D=f=>{let b=()=>{let V=a.indexOf(_);V<0||(a.splice(V,1),c(i,y,-1),I(),f(null))},M=ze(b,T),I=()=>{clearTimeout(M),S.removeEventListener("abort",b)},_={owner:y,grant:V=>{I(),f(V)}};a.push(_),c(i,y,1),S.addEventListener("abort",b,{once:!0})};return new Promise(D)}}};var Su=1024,Kn="Too many requests",gu=(e,t)=>{se("limitPerWindow",e,1),se("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let s=l??{tokens:e,lastRefillMs:i};n(s,i),r.set(a,s);for(let c of r.keys()){if(r.size<=Su)break;r.delete(c)}return s};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let s=r.get(a);s&&(n(s,i),s.tokens=Math.min(e,s.tokens+l))}}},ct=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(se("windowMs",r,1e3)%1e3!==0)throw Q("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=gu(e.limitPerWindow,r),i=Object.freeze({status:429,message:Kn,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Me({windowMs:r,tallies:[t],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`${t}_suppressed count=${c} since=${d} ${o(s)}`)}});return{spend:(s,c)=>a.consume(s,le())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,le(),c)}}};var Du=256*1024,qa=6e4,Au=e=>Math.ceil(e/2),Tu=new Uint8Array(new ArrayBuffer(0)),Eu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Tu,t()},i=l=>{clearTimeout(o),o=ze(()=>{l.error(new Error(`attachment body idle for ${qa} ms`)),a()},qa)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Du,r.byteLength);if(s>n&&l.enqueue(r.slice(n,s)),n=s,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},Ya=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=ct({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=tt({limit:e.concurrency,maxHeldPerOwner:Au(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:R,readAttachment:p,cookie:m,fail:h}=s,y=e.maxBytes,S=i.spend(R,`attachment=${u} viewer=${R}`);if(S)return h(S.status,S.message,S.headers);let T=await n(c,"initial");if(!T.ok)return h(503,cr[503],De(503));let D=await t.getAttachmentForUser(T.scope,u,R);if(!D)return o.warn(`404 attachment=${u} viewer=${R} reason=not_visible`),h(404,"Attachment not found");if(D.fileSize!=null&&D.fileSize>y)return o.warn(`413 attachment=${u} viewer=${R} reason=db_size`),h(413,"Attachment too large");let f=Gn(D.fileType),b=`filename="${Ba(D.fileName)}"; filename*=UTF-8''${$a(D.fileName)}`,M=await l.acquire(R,c.signal);if(!M)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${R} reason=aborted`),h(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${R} reason=concurrency`),h(503,"Too many concurrent downloads",De(503)));let I=!1;try{let _=await p(D.filePath,{maxBytes:y,head:c.method==="HEAD",principal:r(R),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${R} reason=aborted`),h(503,"Attachment request aborted");if(!_.ok){if(!vr(_.reason))return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=failure_reason`),h(500,lt);let $=Or(_.reason);return _.reason==="not_found"&&a(u,!1),o.warn(`${$} attachment=${u} viewer=${R} reason=${_.reason} code=${_.code??"-"}`),h($,cr[$],De($))}if(_.bytes.byteLength>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),h(500,lt);let V=c.method==="HEAD";if(V&&_.size!==void 0&&_.size>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),h(500,lt);if(!V&&_.size!==void 0&&_.size!==_.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=size_mismatch`),h(500,lt);let v=f??Gn(_.contentType),O=v!==null&&Ua.has(v),k=O?v:"application/octet-stream",H=O&&d.kind!=="download"?"inline":"attachment",E=V?_.size:_.bytes.byteLength,x=new Headers({"Content-Type":k,"Content-Disposition":`${H}; ${b}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...$t});return E!==void 0&&x.set("Content-Length",String(E)),m&&x.append("Set-Cookie",m),a(u,!0),o.info(`200 attachment=${u} viewer=${R} type=${k} disposition=${H} bytes=${E??"-"}`),V?new Response(null,{status:200,headers:x}):(I=!0,new Response(Eu(_.bytes,M),{status:200,headers:x}))}finally{I||M()}}};var ve=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),ih=ve.queueWaitMs+ve.readMs+ve.renderMs+ve.transferMarginMs;var za=require("buffer"),Ga=new Set([194,198,202,206]),wu=new Set([192,193,194,195]),Ka=216,Iu=217,Ja=218,_u=4,xu=64,Cu=2,ja=8,Wa=28,ft=12,Jn=8,Mu=20,Qa=ft+Jn+10,Pu=2,ut=(e,t)=>e[t]<<8|e[t+1],Bt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},rt=(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},Xa=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Za=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),ei=e=>(e.stepsLeft-=1,e.stepsLeft>=0),ti=e=>e[0]===255&&e[1]===Ka,ri=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!ei(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let o=e[n];if(n+=1,o===Iu)return"eoi";if(o===0||o===Ka)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=ut(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")}},Lu=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!ei(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}},ni=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=ut(e,r+1),a=ut(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let s=0;s<i;s+=1){let c=e[r+7+3*s],d=c>>4,u=c&15;if(d<1||d>4||u<1||u>4)return null;l.push({id:e[r+6+3*s],horizontal:d,vertical:u})}return{marker:t,width:a,height:o,components:l}},oi=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>_u||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},ai=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:Ga.has(e.marker)||t<e.components.length}),Qn=e=>{if(!ti(e))return null;let t=Za(e.byteLength),r=null;for(let n=2;;){if(ri(e,n,t)!=="segment")return null;if(Xa(t.marker)){if(r!==null||(r=ni(e,t),r===null))return null}else if(t.marker===Ja){if(r===null)return null;let o=oi(e,t);return o===null?null:ai(r,o.length)}n=t.end}},ii=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:o})=>{let a=Math.ceil(e.width*n/(t*ja)),i=Math.ceil(e.height*o/(r*ja));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},si=e=>e.multiScan?ii(e).reduce((r,n)=>r+n,0)*xu*Cu:0,ku=896,li=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!ti(e))return null;let n=za.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=Za(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let R=ri(e,u,o);if(R===null)return null;if(R==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,Xa(o.marker)){if(a!==null||!wu.has(o.marker)||(a=ni(e,o),a===null))return null;let p=ii(a);l=new Map;for(let[m,h]of a.components.entries()){let y=l.get(h.id);l.set(h.id,y===void 0?p[m]:Math.max(y,p[m]))}s=a.components.length*(Ga.has(a.marker)?ku:1)}else if(o.marker===Ja){if(a===null||d===s)return null;let p=oi(e,o);if(p===null)return null;for(let h of p){let y=l.get(h);if(y===void 0)return null;c+=y}if(d+=1,i===null&&(i=ai(a,p.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let m=Lu(n,o.end,o);if(m===null)return null;u=m}}},ci=e=>{if(e.byteLength<24||ut(e,8)!==0||ut(e,10)!==13||!rt(e,12,"IHDR"))return null;let t=ut(e,16)*65536+ut(e,18),r=ut(e,20)*65536+ut(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Nu=e=>{if(rt(e,ft,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Bt(e,26,2)&16383,r=Bt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(rt(e,ft,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Bt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return rt(e,ft,"VP8X")?e.byteLength<Qa?null:{width:Bt(e,24,3)+1,height:Bt(e,27,3)+1}:null},ui=e=>{if(ci(e)===null||e.byteLength<=Wa)return null;switch(e[Wa]){case 0:return!1;case 1:return!0;default:return null}},di=(e,t)=>{if(rt(e,ft,"VP8 "))return"lossy";if(rt(e,ft,"VP8L"))return"lossless";if(!rt(e,ft,"VP8X")||e.byteLength<Qa)return null;if((e[Mu]&Pu)!==0)return"animated";let r=!1,n=t;for(let o=ft;o+Jn<=e.byteLength;){if(n-=1,n<0)return null;if(rt(e,o,"VP8L"))return"lossless";if(rt(e,o,"VP8 "))return r?"lossy-alpha":"lossy";rt(e,o,"ALPH")&&(r=!0);let a=Bt(e,o+4,4);o+=Jn+a+a%2}return null},pi={png:ci,jpeg:Qn,webp:Nu};var Fr=Object.freeze(["image/webp","image/jpeg","image/png"]),Hr=1024*1024;var vu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Ou={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Fu=new Set(Fr),Hu=e=>typeof e=="string"&&Fu.has(e),Uu=256,Ur=(e,t)=>e.fileType===null||!vu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,$u=[137,80,78,71,13,10,26,10],Bu=[255,216,255],Vu=[[71,73,70,56,55,97],[71,73,70,56,57,97]],qu=[82,73,70,70],Yu=[87,69,66,80],ur=(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},Xn=e=>{if(ur(e,$u,0))return"png";if(ur(e,Bu,0))return"jpeg";for(let t of Vu)if(ur(e,t,0))return"gif";return ur(e,qu,0)&&ur(e,Yu,8)?"webp":null},mi=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:Pa([t])}},yi=(e,t)=>{if(!Hu(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Hr)return"too_large";let r=Ou[e.contentType];if(Xn(e.bytes)!==r)return"signature";let n=pi[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},hi=e=>{se("maxBytes",e.maxBytes,0),se("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)+Uu;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let s of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(s)}}}};var Zn=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=le(),l=new AbortController,s=!1,c,d,u=()=>{a(le()-i)},R=f=>{c=ze(()=>{s=!0,f({timedOut:!0}),d=ze(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},p=new Promise(R),m=AbortSignal.any([r,l.signal]),h=f=>{f(n(m))},y=new Promise(h),S=f=>(clearTimeout(c),clearTimeout(d),s&&o(le()-i,f.kind==="error"?{error:f.error}:null),f),T=y.then(f=>S({kind:"value",value:f}),f=>S({kind:"error",error:f}));return{outcome:Promise.race([y.then(f=>({timedOut:!1,value:f})),p]),settled:T}};var dt={404:"Attachment not found",500:lt,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},fi=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=yi(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},ju=e=>{let t=new AbortController,r=()=>{t.abort()},n=ze(r,ve.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Ri=()=>{},Wu=(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)}),Si=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(p,m)=>{let h=m.then(Ri,Ri);l.set(p,h);let y=()=>{l.get(p)===h&&l.delete(p)};h.then(y)},c=async(p,m)=>{let h=l.get(p.key);if(h===void 0)return t.acquire(p.owner,m);let y=ju(m);try{if(await Wu(h,y.signal),y.signal.aborted)return null;let S=r.get(p.key);return S!==void 0?{...S,identity:"verified"}:await t.acquire(p.owner,y.signal)}finally{y.end()}},d=(p,m)=>{if(p.fileSize===null)return m.kind==="exact"?"verified":"unrecorded";if(m.kind==="exact"?m.bytes===p.fileSize:p.fileSize>m.maxBytes)return"verified";let y=m.kind==="exact"?String(m.bytes):`>${m.maxBytes}`;return i.warn(`size_mismatch expected=${p.fileSize} got=${y} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`),"unverified"},u=(p,m)=>(h,y)=>{let S=y===null?"":` message=${y.error instanceof Error?y.error.message:"unknown"}`;i.warn(`${p}_overrun ms=${h} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail${S}`)},R=(p,m)=>h=>{i.warn(`${p}_stuck ms=${h} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`)};return async(p,m)=>{let h=await c(p,m);if(h===null)return{kind:"failure",status:503,reason:m.aborted?"aborted":"queue"};if(typeof h!="function")return h;let y=h,S=null;try{if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let T=r.get(p.key);if(T!==void 0)return{...T,identity:"verified"};let D=Zn({budgetMs:ve.readMs,flightSignal:m,call:$=>p.readAttachment(p.filePath,{maxBytes:n,head:!1,principal:o(p.owner),signal:$}),onOverrun:u("read",p),onStuck:R("read",p)}),f=await D.outcome;if(f.timedOut)return S=D.settled,m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let b=f.value;if(!b.ok&&b.reason!=="too_large")return vr(b.reason)?(b.reason==="not_found"&&a(p.attachmentId,!1),{kind:"failure",status:Or(b.reason),reason:b.reason,code:b.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(b.ok&&b.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let M=d(p,b.ok?{kind:"exact",bytes:b.bytes.byteLength}:{kind:"over",maxBytes:n}),I=$=>{M==="verified"&&r.set(p.key,$)},_=$=>(I($),{...$,identity:M});if(!b.ok)return _({kind:"unrenderable",reason:"too_large"});let V=Xn(b.bytes);if(V===null)return _({kind:"unrenderable",reason:"signature"});let v=Zn({budgetMs:ve.renderMs,flightSignal:m,call:$=>p.renderer.render(b.bytes,{format:V,maxWidth:p.box.maxWidth,maxHeight:p.box.maxHeight,signal:$}),onOverrun:u("render",p),onStuck:R("render",p)}),O=$=>{if($.kind==="error")return;let K=fi($.value,p.box);"entry"in K&&I(K.entry)},k=null,H=()=>(k===null&&(k=v.settled.then(O),s(p.key,k)),k);m.addEventListener("abort",H,{once:!0});let E=await v.outcome.finally(()=>m.removeEventListener("abort",H));if(E.timedOut||m.aborted)return S=H(),m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let x=fi(E.value,p.box);return"entry"in x?_(x.entry):x.failure}finally{S===null?y():S.then(y,y)}}};var gi=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let s=new AbortController,c=()=>{e.get(t)?.controller===s&&e.delete(t)},u={promise:n(s.signal).finally(c),controller:s,waiters:0};return e.set(t,u),u},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var Ai=10,zu=1/Ai,bi=1-zu,Gu=1024,Ku=64,Ju=8,Di="private, no-cache",Qu="no-store",Xu=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Zu=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Ti=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(f,b)=>ct({reason:f,limitPerWindow:b,windowMs:6e4,logger:o,windowFields:M=>`viewer=${M} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*Ai),R=tt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Ku,maxPerOwner:Ju,maxWaitMs:ve.queueWaitMs}}),p=hi({maxBytes:l.cacheBytes,maxEntries:Gu}),m=gi(),h=Si({gate:R,cache:p,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),y=(f,b,M,I)=>{let _=`attachment=${f.attachmentId} viewer=${f.internalUserId} variant=thumbnail cache=${I}`;if(b.kind==="failure")return o[Zu(b)](`${b.status} ${_} reason=${b.reason} code=${b.code??"-"}`),f.fail(b.status,dt[b.status],De(b.status));let V=Xu[b.identity];if(b.kind==="unrenderable")return o.info(`404 ${_} reason=${b.reason}${V}`),f.fail(404,dt[404]);let v=b.identity==="verified"?{"Cache-Control":Di,ETag:M}:{"Cache-Control":Qu},O=new Headers({"Content-Type":b.contentType,"Content-Length":String(b.bytes.byteLength),...v,"Content-Security-Policy":"default-src 'none'; sandbox",...$t});return f.cookie&&O.append("Set-Cookie",f.cookie),o.info(`200 ${_} type=${b.contentType} bytes=${b.bytes.byteLength}${V}`),new Response(b.bytes,{status:200,headers:O})},S=(f,b)=>{let M=f.spend(b.internalUserId,`attachment=${b.attachmentId} viewer=${b.internalUserId} variant=thumbnail`);return M===null?null:b.fail(M.status,M.message,M.headers)},T=f=>S(d,f),D=(f,b)=>b?S(u,f):T(f);return async(f,b)=>{let{request:M,attachmentId:I,internalUserId:_,readAttachment:V,cookie:v,fail:O}=f,k=$n[b],H=M.headers.get("If-None-Match"),E=H!==null,x=D(f,E);if(x)return x;let $=await n(M,"initial");if(!$.ok)return O(503,dt[503],De(503));let K=await t.getAttachmentForUser($.scope,I,_),J=K!==null&&Ur(K,i)?mi({rendererId:s.id,box:k,attachmentId:I,filePath:K.filePath,fileType:K.fileType,fileSize:K.fileSize}):null;if(J&&qn(H,J.etag)){let g=new Headers({"Cache-Control":Di,ETag:J.etag,...$t});return v&&g.append("Set-Cookie",v),o.info(`304 attachment=${I} viewer=${_} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:g})}if(E){let g=T(f);if(g)return g}if(!K)return o.warn(`404 attachment=${I} viewer=${_} variant=thumbnail reason=not_visible`),O(404,dt[404]);if(!J)return d.refund(_,bi),o.info(`404 attachment=${I} viewer=${_} variant=thumbnail reason=not_eligible`),O(404,dt[404]);let{key:ye,etag:Se}=J,te=p.get(ye);if(te)return d.refund(_,bi),y(f,{...te,identity:"verified"},Se,"hit");let Ue=g=>h({key:ye,attachmentId:I,filePath:K.filePath,fileSize:K.fileSize,box:k,owner:_,readAttachment:V,renderer:s},g),F;try{F=await m.join(ye,M.signal,Ue)}catch(g){return o.error(`500 attachment=${I} viewer=${_} variant=thumbnail cache=miss reason=port_exception message=${g instanceof Error?g.message:"unknown"}`),O(500,dt[500])}return y(f,F,Se,"miss")}};var ed='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',td=()=>Nr(403,zn,{cookie:null}),Ei=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Bn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Nr(404,cr[404],{cookie:null}),crossSiteRejection:td}),wi=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,i=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:Ha(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Ya({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Ti({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,R=(p,m,h={})=>Nr(p,m,{cookie:u,extraHeaders:h});try{let{user:p,cookie:m}=await t(c,{failureRedirect:null});if(u=m??null,!p)return R(401,"Unauthorized");let h=Bn(new URL(c.url).searchParams);if(h.kind==="invalid")return R(400,"Invalid attachment request");if(h.kind==="thumbnail"&&c.method!=="GET")return R(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return R(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return R(404,"Attachment not found");if(d.token===void 0)throw new Error(ed);let y=s.idCodec.decode(d.token);if(y===null||!Xe(y))return R(400,"Invalid attachment token");let S=await r.getUserIdByExternalId(p.id);if(!S)return R(403,"Forbidden");let T={request:c,delivery:h,attachmentId:y,internalUserId:S,readAttachment:s.read,cookie:u,fail:R};return h.kind!=="thumbnail"?await s.serveOriginal(T):s.serveThumbnail===null?R(404,dt[404]):await s.serveThumbnail(T,h.variant)}catch(p){if(p instanceof Response)throw p;return a.error(`500 attachment=? viewer=? reason=unexpected message=${p instanceof Error?p.message:"unknown"}`),R(500,lt)}}};var rd=32*1024*1024,nd=60,od=4,ad=120,id=2,sd=8*1024*1024,$r=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ld=e=>{if(e===void 0)throw Qe("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!$r(e))throw Q("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 Q("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Q("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},cd=e=>{if(e===void 0)return null;if(!$r(e))throw Q("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:ld(e.renderer),rateLimitPerMinute:xe("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,ad),concurrency:xe("attachments.thumbnails.concurrency",e.concurrency,1,id),cacheBytes:xe("attachments.thumbnails.cacheBytes",e.cacheBytes,0,sd)})},Ii=e=>{let t=e;if(t===void 0)return null;if(!$r(t))throw Q("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(!$r(r)||typeof r.encode!="function"||typeof r.decode!="function")throw Q("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Qe("attachments.read","injected when attachments is given");if(typeof n!="function")throw Q("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:xe("attachments.maxBytes",t.maxBytes,1,rd),rateLimitPerMinute:xe("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,nd),concurrency:xe("attachments.concurrency",t.concurrency,1,od),thumbnails:cd(t.thumbnails)})},ud=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),Br=e=>{for(let[t,r]of ud)if(Object.hasOwn(e,t))throw Qe(r,`given in place of the flat key ${t}`)};var xi=8,dd=8*xi,pd=128,md=2,Ci=md*pd,yd=4*Ci,hd=6e4,fd=6e4,Rd="Too many reads",_i=Object.freeze(Object.keys(Ct).filter(e=>Ct[e].admission.includes("miss-gate"))),Mi=e=>{let t=tt({limit:dd,maxHeldPerOwner:xi,queue:{max:yd,maxPerOwner:Ci,maxWaitMs:hd}}),r=Me({windowMs:fd,tallies:_i,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${_i.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}})}},Vr=(e,t,r)=>{let n=e(t,r,{error:{message:Rd}},503);for(let[o,a]of Object.entries(De(503)))n.headers.set(o,a);return n};var Pi=e=>{let t=e.get(ge.cursorReportHubId),r=e.get(ge.cursorBusinessDate),n=e.get(ge.cursorSnapshot),o=ia(n)?n:null,a=null;if(t!==null){let l=We(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!aa(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=sr(e.get(ge.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var qr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Sd=2,gd=16,bd=Sd*gd,Dd=6e4,Li=()=>{},Ad=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},ki=e=>{let t=tt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:bd,queue:null}),r=Me({windowMs:Dd,tallies:["sse","ids-stream"],writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`streams_per_viewer_suppressed count=${o} since=${a} viewer=${n} routes=sse:${i.sse},ids-stream:${i["ids-stream"]}`)}});return{admit:async(n,o,a)=>{if(n===null)return Li;if(a.aborted){if(t.canAcquire(n))return Li}else{let i=await t.acquire(n,a);if(i!==null)return Ad(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var Yr=30,Hi=4e3,Td="stream interrupted by server error",Ed="Too many streams",wd=15e3,Ui=Symbol("ids-stream-heartbeat"),Ni=()=>{},vi=e=>e.return(void 0).then(Ni,Ni),Id=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Ui),wd)}),stop:()=>clearTimeout(e)}};async function*Oi(e,t,r,n){let o=t?ca(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Hi),e.length),l=_t(e,o,i),s=i>o?e[i-1]:void 0;o=i;let c=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:c||s===void 0?null:{businessDate:s.businessDate,reportHubId:s.reportHubId},isLast:c,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,c)return}}var $i=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...et});return e&&t.append("Set-Cookie",e),t},Fi=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await vi(t);try{d.close()}catch{}},i=new TextEncoder,l=!1,s=null,c=new ReadableStream({async pull(d){if(l||r.aborted){await a(d,!0);return}let u=Id();try{s===null&&(s=t.next());let R=await Promise.race([s,u.fired]);if(u.stop(),R===Ui){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
1
|
+
"use strict";var En=Object.defineProperty;var fc=Object.getOwnPropertyDescriptor;var Rc=Object.getOwnPropertyNames;var Sc=Object.prototype.hasOwnProperty;var jo=e=>{throw TypeError(e)};var gc=(e,t)=>{for(var r in t)En(e,r,{get:t[r],enumerable:!0})},bc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Rc(t))!Sc.call(e,o)&&o!==r&&En(e,o,{get:()=>t[o],enumerable:!(n=fc(t,o))||n.enumerable});return e};var Dc=e=>bc(En({},"__esModule",{value:!0}),e);var zo=(e,t,r)=>t.has(e)||jo("Cannot "+r);var sr=(e,t,r)=>(zo(e,t,"read from private field"),r?r.call(e):t.get(e)),wn=(e,t,r)=>t.has(e)?jo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),In=(e,t,r,n)=>(zo(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var qm={};gc(qm,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>Jr,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>Kr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>$o,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Lr,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>Bo,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>dn,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>Io,DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS:()=>Vo,DailyReportSseReader:()=>nr,DailyReportViewerScope:()=>ze,SqlResultCache:()=>jt,buildDailyReportSseStreamKey:()=>Uo,createDailyReportHandlers:()=>pn,createDailyReportServer:()=>Vm,createDailyReportService:()=>An,createDailyReportVisibilityCache:()=>ac,createEpochStore:()=>vr,createSharpThumbnailRenderer:()=>oc,dailyReportSseStreamMessageSchema:()=>Ur,defineDailyReportSchema:()=>Vl,defineDailyReportSearchSchema:()=>ql,encodeIdsStreamRows:()=>Ft,isStreamIdLte:()=>dt,parseClientTempId:()=>Yr,predictSharpThumbnailWorkingSetBytes:()=>nc,readDailyReportSseStreamEntry:()=>er,transformJsonArray:()=>Bl});module.exports=Dc(qm);var Nt=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,Q=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Nt(r)}`),at=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),_n=(e,t,r)=>Q(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),le=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw Q(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},ke=(e,t,r,n)=>t===void 0?n:le(e,t,r),lr=(e,t)=>{if(t===void 0)throw at(e,"a function");if(typeof t!="function")throw Q(e,"a function",t);return t};var ce=()=>Math.floor(performance.now());var xn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),Qe=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},vr=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),cr=(e,t)=>t?e.map(r=>structuredClone(r)):e,Ac=8,Tc=32,Ec=24,wc=16,Ic=-(2**30),_c=2**30-1,xc=e=>Number.isInteger(e)&&e>=Ic&&e<=_c&&!Object.is(e,-0),Cc=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=Tc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=Ac*a.length;for(let i of a)typeof i=="string"?r+=Ec+2*i.length:typeof i=="number"&&!xc(i)?r+=wc:typeof i=="object"&&i!==null&&n.push(i)}return r},jt=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-ce())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:c,expireAt:ce()+a,epoch:s}),c})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&s===null)throw new Qe(o.signal.aborted?"aborted":"busy");try{for(let d of r)d();let c=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:c,expireAt:ce()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),c}finally{s?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new Qe("aborted");return this.dropBucket(r),cr(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ce())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),cr(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),cr(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return cr(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new Qe("aborted");return cr(await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};this.readOwnOrRetry=async(t,r)=>{try{return await t}catch(n){let{admission:o}=r;if(!(n instanceof Qe&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.totalBytes=0,this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.dropBucket(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=ke("cacheDefaultTtlMs",t.defaultTtlMs,1,xn.defaultTtlMs),this.maxBuckets=ke("cacheMaxBuckets",t.maxBuckets,1,xn.maxBuckets),this.maxBytes=ke("cacheMaxBytes",t.maxBytes,1,xn.maxBytes),this.lastSweepAt=ce()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=Cc(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=ce();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};var Ks=require("@aiquants/request-isolation");var Mc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Go=e=>e<10?`0${e}`:`${e}`,Pc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Go(e.getMonth()+1),n=Go(e.getDate());return`${t}-${r}-${n}`},zt=e=>{let t=Mc.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let s=new Date(0);return s.setUTCFullYear(a,i-1,l),s.getUTCFullYear()!==a||s.getUTCMonth()!==i-1||s.getUTCDate()!==l?null:`${r}-${n}-${o}`},Nr=e=>zt(e)===e;var Be=e=>e==null?null:e instanceof Date?Pc(e):zt(e);var Ko=require("zod/v3"),it=e=>Number.isSafeInteger(e)&&e>0,Le=Ko.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var ne=require("zod/v3");var Or=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;var Ot=Symbol("daily-report wire mismatch"),st=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),Ot),Zo=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,Ht=(e,t)=>({code:"invalid_type",expected:e,received:Zo(t)}),kc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Lc=e=>{let t=0;for(let r in e)t+=1;return t},Jo=(e,t,r)=>{let n={};for(let o=0;o<r;o+=1){let a=t[o];a in e&&(n[a]=e[a])}return n},Gt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!kc(n))return st(o,null,Ht("object",n));let a=null,i=!1,l=0;for(let s=0;s<t.length;s+=1){let c=t[s],d=n[c];d!==void 0&&(l+=1);let u=r[s](d,o,c);if(u===Ot){i=!0;continue}a===null&&u!==d&&(a=Jo(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?Ot:a!==null?a:Lc(n)===l?n:Jo(n,t,t.length)}},ur=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},dr=e=>(t,r,n)=>{if(!Array.isArray(t))return st(r,n,Ht("array",t));r.path.push(n);let o=t,a=!1;for(let i=0;i<t.length;i+=1){let l=t[i],s=e(l,r,i);s===Ot?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?Ot:o},de=(e,t,r)=>e==null||typeof e=="string"?e:st(t,r,Ht("string",e)),Qo=(e,t,r)=>e===null||typeof e=="string"?e:st(t,r,Ht("string",e)),Xo=(e,t,r)=>typeof e=="string"?e:st(t,r,Ht("string",e)),vc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:st(t,r,Ht("number",e)),pr=(e,t,r)=>typeof e=="boolean"?e:st(t,r,Ht("boolean",e)),Cn=(e,t,r)=>{if(typeof e=="number"&&it(e))return e;for(let{message:n,path:o,...a}of Le.safeParse(e).error.issues)st(t,r,a);return Ot},ea={present:!0,absent:!0,unknown:!0},ta=Object.keys(ea),Nc=ta.map(e=>`'${e}'`).join(" | "),Oc=(e,t,r)=>typeof e!="string"?st(t,r,{code:"invalid_type",expected:Nc,received:Zo(e)}):Object.hasOwn(ea,e)?e:st(t,r,{code:"invalid_enum_value",received:e,options:[...ta]}),ra=Gt({name:de,affiliation:de}),na=Gt({name:de,text:de,color:de}),oa=Gt({id:Cn,name:de,color:de}),aa=Gt({id:Cn,userId:de,userName:de,content:de,createdAt:de,isMine:pr}),Hc=Gt({id:Xo,fileName:Xo,fileType:Qo,fileSize:vc,createdAt:Qo,state:Oc,hasThumbnail:pr}),Fc=Gt({reportHubId:Cn,date:de,createdAt:de,author:de,userId:de,sourceType:de,employeeName:de,updatedBy:de,updatedAt:de,category:de,creationCategory:de,visitTimeFrom:de,visitTimeTo:de,customerName:de,interviewers:dr(ur(ra)),subject:de,content:de,externalComments:dr(ur(na)),isRead:pr,isStarred:pr,isDraft:pr,labels:dr(ur(oa)),postedComments:dr(ur(aa)),attachments:dr(ur(Hc))}),mr=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===Ot?{ok:!1,issues:r.issues}:{ok:!0,value:n}},ia=e=>mr(Fc,e),sa=e=>mr(ra,e),la=e=>mr(na,e),ca=e=>mr(oa,e),ua=e=>mr(aa,e);var da=15e3,pa="lastEventId",Uc=/^\d{1,15}-\d{1,15}$/,ma=e=>Uc.test(e),It="0-0",yr=e=>ne.z.unknown().transform((t,r)=>{let n=e(t);if(n.ok)return n.value;for(let o of n.issues)r.addIssue({...o,fatal:!0});return ne.z.NEVER}),oy=yr(sa),ay=yr(la),iy=yr(ca),$c=yr(ua),hr=yr(ia),fr=ne.z.string().regex(Or),ya=ne.z.object({type:ne.z.literal("connected")}),ha=ne.z.object({type:ne.z.literal("status-update"),reportHubId:Le,statusType:ne.z.enum(["star","read"]),value:ne.z.boolean(),clientTempId:fr}),Mn=ne.z.string(),fa=ne.z.object({type:ne.z.literal("comment-add"),reportHubId:Le,comment:$c,clientTempId:fr,sourceType:Mn}),Ra=ne.z.object({type:ne.z.literal("comment-delete"),reportHubId:Le,commentId:Le,clientTempId:fr,sourceType:Mn}),Hr={recipientRawUserId:Le.optional()},Pn=ha.extend(Hr),kn=fa.extend(Hr),Ln=Ra.extend(Hr),Kt={reportHubId:Le,report:hr,clientTempId:fr},vn={...Hr,actorRawUserId:Le},Nn={viewerIsActor:ne.z.boolean()},Bc=ne.z.object({type:ne.z.literal("report-create"),...Kt,...Nn}),Vc=ne.z.object({type:ne.z.literal("report-update"),...Kt,...Nn}),qc=ne.z.object({type:ne.z.literal("report-publish"),...Kt,...Nn}),On=ne.z.object({type:ne.z.literal("report-create"),...Kt,...vn}),Hn=ne.z.object({type:ne.z.literal("report-update"),...Kt,...vn}),Fn=ne.z.object({type:ne.z.literal("report-publish"),...Kt,...vn}),Fr=ne.z.object({type:ne.z.literal("report-delete"),reportHubId:Le,clientTempId:fr,sourceType:Mn}),sy=ne.z.discriminatedUnion("type",[ya,ha,fa,Ra,Bc,Vc,qc,Fr]),Ur=ne.z.discriminatedUnion("type",[ya,Pn,kn,Ln,On,Hn,Fn,Fr]);var Sa="ids-columns";var Yc=/^[0-9a-f]{1,16}$/,ga=e=>it(e.reportHubId)&&(e.businessDate===null||Nr(e.businessDate)),ba=e=>typeof e=="string"&&Yc.test(e),dy=Object.freeze({kind:"absent"}),py=Object.freeze({kind:"value",value:null});var Ft=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:R}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let p=R===void 0?null:R,m=s.get(p);m===void 0&&(m=i.length,i.push(p),s.set(p,m)),l.push(m)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},$r=e=>{let t=2166136261,r=-624069552;for(let n of e){let o=n.reportHubId;t^=o&255,t=Math.imul(t,16777619),t^=o>>>8&255,t=Math.imul(t,16777619),t^=o>>>16&255,t=Math.imul(t,16777619),t^=o>>>24&255,t=Math.imul(t,16777619),r^=o>>>24&255,r=Math.imul(r,16777619),r^=o>>>16&255,r=Math.imul(r,16777619),r^=o>>>8&255,r=Math.imul(r,16777619),r^=o&255,r=Math.imul(r,16777619);let a=n.businessDate;if(a===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let i=0;i<a.length;i++){let l=a.charCodeAt(i);t^=l&255,t=Math.imul(t,16777619),r^=l&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},Da=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Wc=(e,t,r,n)=>Da(e,t,r,n)<0,Un=(e,t)=>Da(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Aa=e=>{for(let t=1;t<e.length;t++)if(!Wc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},Ta=(e,t)=>{let r=e.findIndex(n=>Un({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var ue=Object.freeze({businessDate:"business-date",idsStream:Sa,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),De=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var Ea=(e,t,r=console)=>{let n=o=>typeof o=="string"?[`${t} ${o}`]:[t,o];return{debug:(o,...a)=>{e<=0&&r.debug(...n(o),...a)},info:(o,...a)=>{e<=1&&r.info(...n(o),...a)},warn:(o,...a)=>{e<=2&&r.warn(...n(o),...a)},error:(o,...a)=>{e<=3&&r.error(...n(o),...a)}}},fy=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),wa=e=>`[DailyReport${e}]`,Ae=(e,t,r)=>e===void 0?Ea(t,wa(r)):Ea(0,wa(r),e);var _t=require("zod/v3");var Rr=e=>({reportHubId:e,outcome:"not_found"}),by=_t.z.discriminatedUnion("outcome",[_t.z.object({reportHubId:Le,outcome:_t.z.literal("ok"),report:hr}).strict(),_t.z.object({reportHubId:Le,outcome:_t.z.literal("not_found")}).strict(),_t.z.object({reportHubId:Le,outcome:_t.z.literal("failed")}).strict()]);var jc="legacy-",$n=e=>`${jc}${e}`;var zc=/^[1-9][0-9]*$/,Gc=/^(?:0|[1-9][0-9]*)$/,Xe=e=>{if(e===null||!zc.test(e))return null;let t=Number(e);return it(t)?t:null},Bn=e=>{if(e===null||!Gc.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Vn=e=>e==="true"?!0:e==="false"?!1:null,Sr=e=>e===null?!1:Vn(e);var Ia=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),ft=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var Kc=16777619,qn=2166136261,Yn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,Kc);return o>>>0},_a=e=>Yn(qn,e,0,e.length),Jc=String.fromCodePoint(3),Qc=String.fromCodePoint(2),Xc=String.fromCodePoint(1),Br=e=>_a(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Jc)).join(Qc)).join(Xc));var xa=e=>e==="intersection"||e==="union",xe=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Wn=2,Vr=2,Ut=Object.freeze({word:0,reading:1});var jn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var Iy=2*(1+Wn);var Zc=require("zod/v3");var Ca=e=>e.issues.map(t=>`${t.path.length===0?"(root)":t.path.join(".")}: ${t.code}`).join("; ");var je=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var qr=Math.max(1,Math.floor(10.556701030927835));var Ze=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Ce=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(c=>[c,0]))};o.set(i,l),Ze(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var Rt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var vy=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),eu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,zn=e=>{let t=e.trim();return t.length===0?null:t.replace(eu,"\uFFFD")},tu=e=>{let t=zn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>Rt.maxValueLength?"filter-value-too-long":null},ru=e=>{if(e.length>Rt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=tu(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},nu=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Ma=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=ru(t);if(r!==null)return r}return nu(e)>Rt.maxTotalValueLength?"filters-too-long":null};var Pa=e=>e.trim().length===0;var Yr=e=>e!==null&&Or.test(e)?e:null,Gn=e=>xa(e)?e:null,Kn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>xe.maxDetailIds)return null;let r=[];for(let n of t){let o=Xe(n);if(o===null||r.includes(o))return null;r.push(o)}return r},ka=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},La=(e,t)=>{let r={authors:e.getAll(De.searchAuthor),sourceTypes:e.getAll(De.searchSourceType),customers:e.getAll(De.searchCustomer)},n=Ma(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:ka(r.authors),customers:ka(r.customers)}}},va=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Oa=Object.freeze({status:400,error:"Invalid form"}),Ha=e=>({status:413,error:"Form too large",measuredBy:e}),ou=(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)}}))},au=async e=>{let t=Bn(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Ha("declared")};let r=!1,n=e.body===null?null:ou(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let i;try{i=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?Ha("counted"):Oa}}let l=va(i);return l===null?{refusal:Oa}:{fields:l}},Fa=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=Vn(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},$a=Object.freeze({update:(e,t,r)=>{let n=e.get(je.title),o=e.get(je.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:Fa("toggleStar",je.isStarred),toggleRead:Fa("toggleRead",je.isRead),addComment:(e,t)=>{let r=e.get(je.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Xe(e.get(je.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),iu=e=>Object.hasOwn($a,e),su=(e,t)=>{let r=e.get(je.intent),n=e.get(je.businessDate),o=n===null?null:zt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(je.operationTimestamp),i=Bn(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(je.clientTempId);if(!l)return{error:"clientTempId required"};let s=Yr(l);if(s===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:i}};let c=Xe(e.get(je.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!iu(r)?{error:"Invalid intent"}:$a[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Ba=async(e,t)=>{let r=await au(e);if("refusal"in r)return r;let n=su(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},lu=6e4,cu="form_too_large",Ua=["declared","counted"],Va=e=>{let t=Ce({windowMs:lu,tallies:Ua,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Ua.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(cu,r,n)}};var $t=Object.freeze({[ue.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ue.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[ue.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ue.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[ue.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[ue.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[ue.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),qa=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Jn=e=>e!==void 0&&Object.hasOwn($t,e);var Qn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Ya=e=>Object.hasOwn(Qn,e);var uu="download",du="thumbnail",pu="1";var Xn=e=>{let t=e.getAll(du),r=e.getAll(uu);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Ya(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===pu?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var Ka=require("@aiquants/request-isolation");var Wa=require("crypto"),Zn=e=>`"${(0,Wa.createHash)("sha256").update(e).digest("hex")}"`,ja=e=>Zn(JSON.stringify(e));var lt=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),eo=(e,t)=>{if(e===null)return!1;for(let r of e.split(",")){let n=r.trim();if((n.startsWith("W/")?n.slice(2):n)===t)return!0}return!1},za=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=Zn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...lt});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&eo(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},to=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...lt});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},ro=e=>(t,r,n,o)=>{if(o!==200)return to(r,n,o);if(e===null||n===null)throw new Error(`[daily-report] API route: a 200 JSON answer needs an answer of a JSON 200 and a body; got ${e===null?"a responder without one":"an answer"} and ${n===null?"no body":"a body"}`);return e(t,r,n)},mu=5e3/1e3,yu=new Map([[503,mu]]),Ee=e=>{let t=yu.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var oo="Cross-site request rejected",hu="Not Found",Ga=["api","action","sse","attachment"],Ja=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...lt}}),fu=()=>Ja(403,oo),Wr=()=>Ja(404,hu),gr=Object.freeze({...Ka.NO_CROSS_ORIGIN_NAVIGATION,frameworkDataRefusal:()=>null,crossSiteRejection:fu}),Qa=e=>new URL(e.url).pathname.endsWith(".data"),Ru=6e4,Su="refusals",gu=32,bu=/^[a-z-]+$/,no=e=>{if(e===null)return"-";let t=e.slice(0,gu);return bu.test(t)&&t===e?e:JSON.stringify(t)},Xa=e=>{let t=Ce({windowMs:Ru,tallies:Ga,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${Ga.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n,o)=>{let a=()=>{let{headers:i}=o;e.warn(`cross_site_rejected route=${r} reason=${n} site=${no(i.get("Sec-Fetch-Site"))} mode=${no(i.get("Sec-Fetch-Mode"))} dest=${no(i.get("Sec-Fetch-Dest"))} method=${o.method}`)};t.record(Su,r,a)}};var Za=(e,t)=>(r,n)=>{let o=n?"markAttachmentPresent":"markAttachmentMissing";e[o](r).catch(a=>{t.error(`${o} failed attachment=${r} message=${a instanceof Error?a.message:"unknown"}`)})};var Du="same-origin",Au="SAMEORIGIN",Jt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Du,"X-Frame-Options":Au}),jr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Jt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},ei=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Tu=/^[\x20-\x7E]+$/,Eu=/^[\w.+-]+\/[\w.+-]+/,ao=e=>e&&Tu.test(e)&&Eu.test(e)?e:null,wu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,ti=e=>encodeURIComponent(e.replace(wu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),ri=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),br={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},ni={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},zr=e=>typeof e=="string"&&Object.hasOwn(ni,e),Gr=e=>ni[e],St="Attachment request failed";var ct=e=>{let t=le("limit",e.limit,1),r=le("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:le("queue.max",e.queue.max,0),maxPerOwner:le("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:le("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(y,S)=>y.get(S)??0,c=(y,S,T)=>{let D=s(y,S)+T;D<=0?y.delete(S):y.set(S,D)},d=y=>s(l,y)<r,u=y=>o<t&&d(y),R=y=>(o+=1,c(l,y,1),h(y)),p=()=>{let y=-1,S=r;for(let[T,D]of a.entries()){let f=s(l,D.owner);if(f<S&&(y=T,S=f,f===0))break}return y},m=()=>{for(;o<t;){let y=p();if(y<0)return;let[S]=a.splice(y,1);c(i,S.owner,-1),S.grant(R(S.owner))}},h=y=>{let S=!1;return()=>{S||(S=!0,o-=1,c(l,y,-1),m())}};return{canAcquire:u,acquire:(y,S)=>{if(S.aborted)return Promise.resolve(null);if(u(y))return Promise.resolve(R(y));if(n===null||a.length>=n.max||s(i,y)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:T}=n,D=f=>{let g=()=>{let Y=a.indexOf(C);Y<0||(a.splice(Y,1),c(i,y,-1),x(),f(null))},k=Ze(g,T),x=()=>{clearTimeout(k),S.removeEventListener("abort",g)},C={owner:y,grant:Y=>{x(),f(Y)}};a.push(C),c(i,y,1),S.addEventListener("abort",g,{once:!0})};return new Promise(D)}}};var Iu=1024,io="Too many requests",_u=(e,t)=>{le("limitPerWindow",e,1),le("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let s=l??{tokens:e,lastRefillMs:i};n(s,i),r.set(a,s);for(let c of r.keys()){if(r.size<=Iu)break;r.delete(c)}return s};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let s=r.get(a);s&&(n(s,i),s.tokens=Math.min(e,s.tokens+l))}}},gt=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(le("windowMs",r,1e3)%1e3!==0)throw Q("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=_u(e.limitPerWindow,r),i=Object.freeze({status:429,message:io,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Ce({windowMs:r,tallies:[t],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`${t}_suppressed count=${c} since=${d} ${o(s)}`)}});return{spend:(s,c)=>a.consume(s,ce())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,ce(),c)}}};var Cu=256*1024,oi=6e4,Mu=e=>Math.ceil(e/2),Pu=new Uint8Array(new ArrayBuffer(0)),ku=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Pu,t()},i=l=>{clearTimeout(o),o=Ze(()=>{l.error(new Error(`attachment body idle for ${oi} ms`)),a()},oi)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Cu,r.byteLength);if(s>n&&l.enqueue(r.slice(n,s)),n=s,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},ai=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=gt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=ct({limit:e.concurrency,maxHeldPerOwner:Mu(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:R,readAttachment:p,cookie:m,fail:h}=s,y=e.maxBytes,S=i.spend(R,`attachment=${u} viewer=${R}`);if(S)return h(S.status,S.message,S.headers);let T=await n(c,"initial");if(!T.ok)return h(503,br[503],Ee(503));let D=await t.getAttachmentForUser(T.scope,u,R);if(!D)return o.warn(`404 attachment=${u} viewer=${R} reason=not_visible`),h(404,"Attachment not found");if(D.fileSize!=null&&D.fileSize>y)return o.warn(`413 attachment=${u} viewer=${R} reason=db_size`),h(413,"Attachment too large");let f=ao(D.fileType),g=`filename="${ri(D.fileName)}"; filename*=UTF-8''${ti(D.fileName)}`,k=await l.acquire(R,c.signal);if(!k)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${R} reason=aborted`),h(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${R} reason=concurrency`),h(503,"Too many concurrent downloads",Ee(503)));let x=!1;try{let C=await p(D.filePath,{maxBytes:y,head:c.method==="HEAD",principal:r(R),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${R} reason=aborted`),h(503,"Attachment request aborted");if(!C.ok){if(!zr(C.reason))return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=failure_reason`),h(500,St);let V=Gr(C.reason);return C.reason==="not_found"&&a(u,!1),o.warn(`${V} attachment=${u} viewer=${R} reason=${C.reason} code=${C.code??"-"}`),h(V,br[V],Ee(V))}if(C.bytes.byteLength>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),h(500,St);let Y=c.method==="HEAD";if(Y&&C.size!==void 0&&C.size>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),h(500,St);if(!Y&&C.size!==void 0&&C.size!==C.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=size_mismatch`),h(500,St);let v=f??ao(C.contentType),N=v!==null&&ei.has(v),L=N?v:"application/octet-stream",B=N&&d.kind!=="download"?"inline":"attachment",E=Y?C.size:C.bytes.byteLength,I=new Headers({"Content-Type":L,"Content-Disposition":`${B}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Jt});return E!==void 0&&I.set("Content-Length",String(E)),m&&I.append("Set-Cookie",m),a(u,!0),o.info(`200 attachment=${u} viewer=${R} type=${L} disposition=${B} bytes=${E??"-"}`),Y?new Response(null,{status:200,headers:I}):(x=!0,new Response(ku(C.bytes,k),{status:200,headers:I}))}finally{x||k()}}};var Ve=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Dh=Ve.queueWaitMs+Ve.readMs+Ve.renderMs+Ve.transferMarginMs;var li=require("buffer"),ci=new Set([194,198,202,206]),Lu=new Set([192,193,194,195]),ui=216,vu=217,di=218,Nu=4,Ou=64,Hu=2,ii=8,si=28,xt=12,so=8,Fu=20,pi=xt+so+10,Uu=2,bt=(e,t)=>e[t]<<8|e[t+1],Qt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},ut=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},mi=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,yi=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),hi=e=>(e.stepsLeft-=1,e.stepsLeft>=0),fi=e=>e[0]===255&&e[1]===ui,Ri=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!hi(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let o=e[n];if(n+=1,o===vu)return"eoi";if(o===0||o===ui)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=bt(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")}},$u=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!hi(r))return null;if(a+1>=n)return n;let i=e[a+1];if(i===255)a+=1;else if(i===0||i>=208&&i<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},Si=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=bt(e,r+1),a=bt(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let s=0;s<i;s+=1){let c=e[r+7+3*s],d=c>>4,u=c&15;if(d<1||d>4||u<1||u>4)return null;l.push({id:e[r+6+3*s],horizontal:d,vertical:u})}return{marker:t,width:a,height:o,components:l}},gi=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>Nu||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},bi=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:ci.has(e.marker)||t<e.components.length}),lo=e=>{if(!fi(e))return null;let t=yi(e.byteLength),r=null;for(let n=2;;){if(Ri(e,n,t)!=="segment")return null;if(mi(t.marker)){if(r!==null||(r=Si(e,t),r===null))return null}else if(t.marker===di){if(r===null)return null;let o=gi(e,t);return o===null?null:bi(r,o.length)}n=t.end}},Di=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:o})=>{let a=Math.ceil(e.width*n/(t*ii)),i=Math.ceil(e.height*o/(r*ii));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},Ai=e=>e.multiScan?Di(e).reduce((r,n)=>r+n,0)*Ou*Hu:0,Bu=896,Ti=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!fi(e))return null;let n=li.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=yi(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let R=Ri(e,u,o);if(R===null)return null;if(R==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,mi(o.marker)){if(a!==null||!Lu.has(o.marker)||(a=Si(e,o),a===null))return null;let p=Di(a);l=new Map;for(let[m,h]of a.components.entries()){let y=l.get(h.id);l.set(h.id,y===void 0?p[m]:Math.max(y,p[m]))}s=a.components.length*(ci.has(a.marker)?Bu:1)}else if(o.marker===di){if(a===null||d===s)return null;let p=gi(e,o);if(p===null)return null;for(let h of p){let y=l.get(h);if(y===void 0)return null;c+=y}if(d+=1,i===null&&(i=bi(a,p.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let m=$u(n,o.end,o);if(m===null)return null;u=m}}},Ei=e=>{if(e.byteLength<24||bt(e,8)!==0||bt(e,10)!==13||!ut(e,12,"IHDR"))return null;let t=bt(e,16)*65536+bt(e,18),r=bt(e,20)*65536+bt(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Vu=e=>{if(ut(e,xt,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Qt(e,26,2)&16383,r=Qt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(ut(e,xt,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Qt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return ut(e,xt,"VP8X")?e.byteLength<pi?null:{width:Qt(e,24,3)+1,height:Qt(e,27,3)+1}:null},wi=e=>{if(Ei(e)===null||e.byteLength<=si)return null;switch(e[si]){case 0:return!1;case 1:return!0;default:return null}},Ii=(e,t)=>{if(ut(e,xt,"VP8 "))return"lossy";if(ut(e,xt,"VP8L"))return"lossless";if(!ut(e,xt,"VP8X")||e.byteLength<pi)return null;if((e[Fu]&Uu)!==0)return"animated";let r=!1,n=t;for(let o=xt;o+so<=e.byteLength;){if(n-=1,n<0)return null;if(ut(e,o,"VP8L"))return"lossless";if(ut(e,o,"VP8 "))return r?"lossy-alpha":"lossy";ut(e,o,"ALPH")&&(r=!0);let a=Qt(e,o+4,4);o+=so+a+a%2}return null},_i={png:Ei,jpeg:lo,webp:Vu};var Kr=Object.freeze(["image/webp","image/jpeg","image/png"]),Jr=1024*1024;var qu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Yu={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Wu=new Set(Kr),ju=e=>typeof e=="string"&&Wu.has(e),zu=256,Qr=(e,t)=>e.fileType===null||!qu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Gu=[137,80,78,71,13,10,26,10],Ku=[255,216,255],Ju=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Qu=[82,73,70,70],Xu=[87,69,66,80],Dr=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,o]of t.entries())if(e[r+n]!==o)return!1;return!0},co=e=>{if(Dr(e,Gu,0))return"png";if(Dr(e,Ku,0))return"jpeg";for(let t of Ju)if(Dr(e,t,0))return"gif";return Dr(e,Qu,0)&&Dr(e,Xu,8)?"webp":null},xi=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:ja([t])}},Ci=(e,t)=>{if(!ju(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Jr)return"too_large";let r=Yu[e.contentType];if(co(e.bytes)!==r)return"signature";let n=_i[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Mi=e=>{le("maxBytes",e.maxBytes,0),le("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+zu;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let s of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(s)}}}};var uo=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ce(),l=new AbortController,s=!1,c,d,u=()=>{a(ce()-i)},R=f=>{c=Ze(()=>{s=!0,f({timedOut:!0}),d=Ze(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},p=new Promise(R),m=AbortSignal.any([r,l.signal]),h=f=>{f(n(m))},y=new Promise(h),S=f=>(clearTimeout(c),clearTimeout(d),s&&o(ce()-i,f.kind==="error"?{error:f.error}:null),f),T=y.then(f=>S({kind:"value",value:f}),f=>S({kind:"error",error:f}));return{outcome:Promise.race([y.then(f=>({timedOut:!1,value:f})),p]),settled:T}};var Dt={404:"Attachment not found",500:St,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Pi=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=Ci(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Zu=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ze(r,Ve.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},ki=()=>{},ed=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),Li=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(p,m)=>{let h=m.then(ki,ki);l.set(p,h);let y=()=>{l.get(p)===h&&l.delete(p)};h.then(y)},c=async(p,m)=>{let h=l.get(p.key);if(h===void 0)return t.acquire(p.owner,m);let y=Zu(m);try{if(await ed(h,y.signal),y.signal.aborted)return null;let S=r.get(p.key);return S!==void 0?{...S,identity:"verified"}:await t.acquire(p.owner,y.signal)}finally{y.end()}},d=(p,m)=>{if(p.fileSize===null)return m.kind==="exact"?"verified":"unrecorded";if(m.kind==="exact"?m.bytes===p.fileSize:p.fileSize>m.maxBytes)return"verified";let y=m.kind==="exact"?String(m.bytes):`>${m.maxBytes}`;return i.warn(`size_mismatch expected=${p.fileSize} got=${y} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`),"unverified"},u=(p,m)=>(h,y)=>{let S=y===null?"":` message=${y.error instanceof Error?y.error.message:"unknown"}`;i.warn(`${p}_overrun ms=${h} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail${S}`)},R=(p,m)=>h=>{i.warn(`${p}_stuck ms=${h} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`)};return async(p,m)=>{let h=await c(p,m);if(h===null)return{kind:"failure",status:503,reason:m.aborted?"aborted":"queue"};if(typeof h!="function")return h;let y=h,S=null;try{if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let T=r.get(p.key);if(T!==void 0)return{...T,identity:"verified"};let D=uo({budgetMs:Ve.readMs,flightSignal:m,call:V=>p.readAttachment(p.filePath,{maxBytes:n,head:!1,principal:o(p.owner),signal:V}),onOverrun:u("read",p),onStuck:R("read",p)}),f=await D.outcome;if(f.timedOut)return S=D.settled,m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=f.value;if(!g.ok&&g.reason!=="too_large")return zr(g.reason)?(g.reason==="not_found"&&a(p.attachmentId,!1),{kind:"failure",status:Gr(g.reason),reason:g.reason,code:g.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(g.ok&&g.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let k=d(p,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),x=V=>{k==="verified"&&r.set(p.key,V)},C=V=>(x(V),{...V,identity:k});if(!g.ok)return C({kind:"unrenderable",reason:"too_large"});let Y=co(g.bytes);if(Y===null)return C({kind:"unrenderable",reason:"signature"});let v=uo({budgetMs:Ve.renderMs,flightSignal:m,call:V=>p.renderer.render(g.bytes,{format:Y,maxWidth:p.box.maxWidth,maxHeight:p.box.maxHeight,signal:V}),onOverrun:u("render",p),onStuck:R("render",p)}),N=V=>{if(V.kind==="error")return;let J=Pi(V.value,p.box);"entry"in J&&x(J.entry)},L=null,B=()=>(L===null&&(L=v.settled.then(N),s(p.key,L)),L);m.addEventListener("abort",B,{once:!0});let E=await v.outcome.finally(()=>m.removeEventListener("abort",B));if(E.timedOut||m.aborted)return S=B(),m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let I=Pi(E.value,p.box);return"entry"in I?C(I.entry):I.failure}finally{S===null?y():S.then(y,y)}}};var vi=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let s=new AbortController,c=()=>{e.get(t)?.controller===s&&e.delete(t)},u={promise:n(s.signal).finally(c),controller:s,waiters:0};return e.set(t,u),u},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var Hi=10,td=1/Hi,Ni=1-td,rd=1024,nd=64,od=8,Oi="private, no-cache",ad="no-store",id=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),sd=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Fi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(f,g)=>gt({reason:f,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:k=>`viewer=${k} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*Hi),R=ct({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:nd,maxPerOwner:od,maxWaitMs:Ve.queueWaitMs}}),p=Mi({maxBytes:l.cacheBytes,maxEntries:rd}),m=vi(),h=Li({gate:R,cache:p,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),y=(f,g,k,x)=>{let C=`attachment=${f.attachmentId} viewer=${f.internalUserId} variant=thumbnail cache=${x}`;if(g.kind==="failure")return o[sd(g)](`${g.status} ${C} reason=${g.reason} code=${g.code??"-"}`),f.fail(g.status,Dt[g.status],Ee(g.status));let Y=id[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${C} reason=${g.reason}${Y}`),f.fail(404,Dt[404]);let v=g.identity==="verified"?{"Cache-Control":Oi,ETag:k}:{"Cache-Control":ad},N=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...v,"Content-Security-Policy":"default-src 'none'; sandbox",...Jt});return f.cookie&&N.append("Set-Cookie",f.cookie),o.info(`200 ${C} type=${g.contentType} bytes=${g.bytes.byteLength}${Y}`),new Response(g.bytes,{status:200,headers:N})},S=(f,g)=>{let k=f.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return k===null?null:g.fail(k.status,k.message,k.headers)},T=f=>S(d,f),D=(f,g)=>g?S(u,f):T(f);return async(f,g)=>{let{request:k,attachmentId:x,internalUserId:C,readAttachment:Y,cookie:v,fail:N}=f,L=Qn[g],B=k.headers.get("If-None-Match"),E=B!==null,I=D(f,E);if(I)return I;let V=await n(k,"initial");if(!V.ok)return N(503,Dt[503],Ee(503));let J=await t.getAttachmentForUser(V.scope,x,C),z=J!==null&&Qr(J,i)?xi({rendererId:s.id,box:L,attachmentId:x,filePath:J.filePath,fileType:J.fileType,fileSize:J.fileSize}):null;if(z&&eo(B,z.etag)){let b=new Headers({"Cache-Control":Oi,ETag:z.etag,...Jt});return v&&b.append("Set-Cookie",v),o.info(`304 attachment=${x} viewer=${C} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:b})}if(E){let b=T(f);if(b)return b}if(!J)return o.warn(`404 attachment=${x} viewer=${C} variant=thumbnail reason=not_visible`),N(404,Dt[404]);if(!z)return d.refund(C,Ni),o.info(`404 attachment=${x} viewer=${C} variant=thumbnail reason=not_eligible`),N(404,Dt[404]);let{key:ye,etag:Re}=z,X=p.get(ye);if(X)return d.refund(C,Ni),y(f,{...X,identity:"verified"},Re,"hit");let ve=b=>h({key:ye,attachmentId:x,filePath:J.filePath,fileSize:J.fileSize,box:L,owner:C,readAttachment:Y,renderer:s},b),Z;try{Z=await m.join(ye,k.signal,ve)}catch(b){return o.error(`500 attachment=${x} viewer=${C} variant=thumbnail cache=miss reason=port_exception message=${b instanceof Error?b.message:"unknown"}`),N(500,Dt[500])}return y(f,Z,Re,"miss")}};var ld='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',cd=()=>jr(403,oo,{cookie:null}),Ui=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Xn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>jr(404,br[404],{cookie:null}),crossSiteRejection:cd}),$i=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,i=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:Za(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:ai({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Fi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,R=(p,m,h={})=>jr(p,m,{cookie:u,extraHeaders:h});try{let{user:p,cookie:m}=await t(c,{failureRedirect:null});if(u=m??null,!p)return R(401,"Unauthorized");let h=Xn(new URL(c.url).searchParams);if(h.kind==="invalid")return R(400,"Invalid attachment request");if(h.kind==="thumbnail"&&c.method!=="GET")return R(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return R(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return R(404,"Attachment not found");if(d.token===void 0)throw new Error(ld);let y=s.idCodec.decode(d.token);if(y===null||!it(y))return R(400,"Invalid attachment token");let S=await r.getUserIdByExternalId(p.id);if(!S)return R(403,"Forbidden");let T={request:c,delivery:h,attachmentId:y,internalUserId:S,readAttachment:s.read,cookie:u,fail:R};return h.kind!=="thumbnail"?await s.serveOriginal(T):s.serveThumbnail===null?R(404,Dt[404]):await s.serveThumbnail(T,h.variant)}catch(p){if(p instanceof Response)throw p;return a.error(`500 attachment=? viewer=? reason=unexpected message=${p instanceof Error?p.message:"unknown"}`),R(500,St)}}};var ud=32*1024*1024,dd=60,pd=4,md=120,yd=2,hd=8*1024*1024,Xr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fd=e=>{if(e===void 0)throw at("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Xr(e))throw Q("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 Q("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Q("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Rd=e=>{if(e===void 0)return null;if(!Xr(e))throw Q("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:fd(e.renderer),rateLimitPerMinute:ke("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,md),concurrency:ke("attachments.thumbnails.concurrency",e.concurrency,1,yd),cacheBytes:ke("attachments.thumbnails.cacheBytes",e.cacheBytes,0,hd)})},Bi=e=>{let t=e;if(t===void 0)return null;if(!Xr(t))throw Q("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(!Xr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw Q("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw at("attachments.read","injected when attachments is given");if(typeof n!="function")throw Q("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:ke("attachments.maxBytes",t.maxBytes,1,ud),rateLimitPerMinute:ke("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,dd),concurrency:ke("attachments.concurrency",t.concurrency,1,pd),thumbnails:Rd(t.thumbnails)})},Sd=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),Zr=e=>{for(let[t,r]of Sd)if(Object.hasOwn(e,t))throw at(r,`given in place of the flat key ${t}`)};var qi=8,gd=8*qi,bd=128,Dd=2,Yi=Dd*bd,Ad=4*Yi,Td=6e4,Ed=6e4,wd="Too many reads",Vi=Object.freeze(Object.keys($t).filter(e=>$t[e].admission.includes("miss-gate"))),Wi=e=>{let t=ct({limit:gd,maxHeldPerOwner:qi,queue:{max:Ad,maxPerOwner:Yi,maxWaitMs:Td}}),r=Ce({windowMs:Ed,tallies:Vi,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Vi.map(l=>`${l}:${i[l]}`).join(",")}`)}});return{admissionFor:(n,o,a)=>({signal:a,acquire:async i=>{let l=await t.acquire(n,i);return l===null&&!i.aborted&&r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=cache_miss_admission`)),l}})}},en=(e,t,r)=>{let n=e(t,r,{error:{message:wd}},503);for(let[o,a]of Object.entries(Ee(503)))n.headers.set(o,a);return n};var ji=e=>{let t=e.get(De.cursorReportHubId),r=e.get(De.cursorBusinessDate),n=e.get(De.cursorSnapshot),o=ba(n)?n:null,a=null;if(t!==null){let l=Xe(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!ga(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=Sr(e.get(De.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var tn=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Id=2,_d=16,xd=Id*_d,Cd=6e4,zi=()=>{},Md=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Gi=e=>{let t=ct({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:xd,queue:null}),r=Ce({windowMs:Cd,tallies:["sse","ids-stream"],writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`streams_per_viewer_suppressed count=${o} since=${a} viewer=${n} routes=sse:${i.sse},ids-stream:${i["ids-stream"]}`)}});return{admit:async(n,o,a)=>{if(n===null)return zi;if(a.aborted){if(t.canAcquire(n))return zi}else{let i=await t.acquire(n,a);if(i!==null)return Md(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var rn=30,Zi=4e3,Pd="stream interrupted by server error",kd="Too many streams",Ld=15e3,es=Symbol("ids-stream-heartbeat"),Ki=()=>{},Ji=e=>e.return(void 0).then(Ki,Ki),vd=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(es),Ld)}),stop:()=>clearTimeout(e)}};async function*Qi(e,t,r,n){let o=t?Ta(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Zi),e.length),l=Ft(e,o,i),s=i>o?e[i-1]:void 0;o=i;let c=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:c||s===void 0?null:{businessDate:s.businessDate,reportHubId:s.reportHubId},isLast:c,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,c)return}}var ts=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...lt});return e&&t.append("Set-Cookie",e),t},Xi=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await Ji(t);try{d.close()}catch{}},i=new TextEncoder,l=!1,s=null,c=new ReadableStream({async pull(d){if(l||r.aborted){await a(d,!0);return}let u=vd();try{s===null&&(s=t.next());let R=await Promise.race([s,u.fired]);if(u.stop(),R===es){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
2
2
|
`));return}s=null;let{value:p,done:m}=R;if(m){await a(d,!1);return}if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`${JSON.stringify(p)}
|
|
3
|
-
`))}catch(R){if(u.stop(),s=null,o(),l||r.aborted)return;R instanceof
|
|
4
|
-
`)),d.close()}catch{}}},cancel(){l=!0,o(),
|
|
5
|
-
`,
|
|
6
|
-
`)},
|
|
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`],ep=["","\u30A2","\u4F50"," "],tp=()=>JSON.stringify(Zd.map(e=>Kr(e,8))),rp=e=>`dr-search-v${Ld};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var np=async()=>{let e=(0,Ji.createHash)("sha256");e.update(JSON.stringify(he.DEFAULT_NORMALIZE_OPTIONS));for(let t of ep)await(0,ro.setImmediate)(),e.update("\0"),e.update(oo(Xd(t)));return await(0,ro.setImmediate)(),e.update("\0"),e.update(tp()),rp(e.digest("hex"))},op=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},co=op(np);var ap=/^-+/u,ip=/\s+/u,ss=e=>{let t=ap.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},sp=(e,t)=>{let r=[...ss(e).map(n=>({text:n,tier:xt.word})),...t.flatMap(n=>ss(n).map(o=>({text:o,tier:xt.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},lp=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),Jr=(e,t)=>{if(e.length>Ie.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of(0,ls.parseQuerySets)(Gr(e),t).sets){let i=[],l=new Set;for(let c of a.split(ip)){let d=Wr(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>Ie.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=sp(d,es(c)),R=lp(u);l.has(R)||(l.add(R),i.push({alternatives:u}))}if(i.length>Ie.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let s=JSON.stringify([...l].sort());n.has(s)||(n.add(s),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>Ie.maxSets?{ok:!1,reason:"too-many-sets"}:o>Ie.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},mr=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var xf=Object.freeze({sourceTypes:null,authors:null,customers:null}),cp=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,cs=(e,t,r)=>{if(fa(e)&&cp(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=Jr(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var us=6e4,up=1,dp=3200,ds=2e3,pp=Object.freeze({search:dp,reports:ds,"search-marks":ds,"search-facets":null}),mp=(e,t)=>{let r=pp[e];return r===null?null:{max:t,maxPerOwner:Mr,maxWaitMs:r}},yr=e=>{let{concurrency:t,route:r,logger:n}=e,o=ct({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:us,logger:n,windowFields:()=>`route=${r}`}),a=tt({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:mp(r,t)}),i=Object.freeze({status:429,message:Kn,headers:Object.freeze({"Retry-After":String(up)})}),l=Me({windowMs:us,tallies:["busy"],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`busy_suppressed count=${c} since=${d} route=${r} concurrency=${t}`)}});return{admit:async(s,c)=>{let d=o.spend(s,r);if(d!==null)return{refusal:d};let u=await a.acquire(s,c);return u!==null?{release:u}:(o.refund(s,1),c.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};var Is=require("@aiquants/sse"),St=require("@aiquants/sse/server");var Yt=(e,t)=>{let r=e.message.data;if(!r)return{entry:{id:e.id,message:null},json:void 0};let n;try{n=JSON.parse(r)}catch(i){return t.error(`SSE message ${e.id} is not JSON:`,i),{entry:{id:e.id,message:null},json:void 0}}let o=_r.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n});return{entry:Object.freeze({id:e.id,message:a}),json:n}},ps=new WeakMap,ms=(e,t,r)=>{let n=ps.get(e);n===void 0&&(n=new Map,ps.set(e,n));let o=n.get(t);if(o!==void 0)return o;let a=r();return n.set(t,a),a},uo=e=>e,yp=e=>{switch(e.type){case"connected":case"report-delete":return uo(e);case"status-update":case"comment-add":case"comment-delete":{let{recipientRawUserId:t,...r}=e;return uo(r)}}},hp=(e,t,r)=>{let{recipientRawUserId:n,actorRawUserId:o,...a}=e,i=r?{...a.report,externalComments:[],postedComments:[]}:a.report;return uo({...a,report:i,viewerIsActor:t})},ys=(e,t,r)=>{let{parsed:n}=e;if(n.type!=="report-create"&&n.type!=="report-update"&&n.type!=="report-publish")return ms(e,"every-viewer",()=>JSON.stringify(yp(n)));let o=n.actorRawUserId===t;return ms(e,`${o?"actor":"observer"}${r?"-comments-redacted":""}`,()=>JSON.stringify(hp(n,o,r)))};var Ss=require("@aiquants/sse"),gs=require("@aiquants/sse/shared-source");var Rt="daily-report:ids:",po=(e,t)=>`${e}st:${t}`,mo=e=>`${Rt}user:${e}:`,hs=(e,t)=>po(mo(e),t),jt=e=>`daily-report:date:${e}:user:`,Wt=(e,t)=>`${jt(e)}${t}:`,fs=(e,t,r)=>po(Wt(e,t),r),Ve=e=>`daily-report:detail:${e}:user:`,yo=(e,t)=>`${Ve(e)}${t}:`,Rs=(e,t,r)=>po(yo(e,t),r);var pt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},fp=5e3,Rp=Pr,zt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=be(t.logger,1,"SseReader"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return(0,gs.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Ss.systemSseRuntime,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",i=>{this._logger.error("Redis client error:",i)});let o=!1,a=this._readLoop(n,t,r,()=>o);return async()=>{if(o=!0,n.isOpen)try{await n.quit()}catch{}await a}}async _readLoop(t,r,n,o){let a=n;try{for(;!o()&&t.isOpen;){let i=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:fp,COUNT:Rp});if(i)for(let l of i)for(let s of l.messages){a=s.id;let{entry:c,json:d}=Yt(s,this._logger);this._invalidateCaches(d),r.next(c)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(Rt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ve(n))}};var Sp=6e4,hr="Report visibility is unavailable",bs=["initial","refresh"],Ds=Object.freeze({ok:!1}),gp=e=>e===null?"null":Array.isArray(e)?"array":typeof e,As=(e,t)=>{let r=Me({windowMs:Sp,tallies:bs,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{t.error(`visibility_unavailable_suppressed count=${o} since=${a} cause=${n} reasons=${bs.map(l=>`${l}:${i[l]}`).join(",")}`)}});return async(n,o)=>{let a;try{a=await e(n,{reason:o})}catch(l){return r.record("port_failure",o,()=>t.error(`visibility unavailable cause=port_failure reason=${o}`,l)),Ds}let i=ji(a);return i===null?(r.record("port_contract",o,()=>t.error(`visibility unavailable cause=port_contract reason=${o} answer=${gp(a)}`)),Ds):{ok:!0,scope:i}}},Ts=(e,t,r)=>{let n=e(t,r,{error:{message:hr}},503);for(let[o,a]of Object.entries(De(503)))n.headers.set(o,a);return n};var _s=Object.freeze({...lr,route:"sse",frameworkDataRefusal:kr}),Es=864e5,bp={baseMs:2e3,jitterMs:8e3},ho=6e4,Xr=Pr,xs=JSON.stringify({type:"connected"}),ws="0-0",Dp=(e,t,r)=>{if(t===null&&r===null)return!0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Te(t,e.report.sourceType);case"comment-add":case"comment-delete":return Te(r,e.sourceType);case"report-delete":return Te(t,e.sourceType)}},Ap=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Te(t,e.report.sourceType),Tp=(e,t)=>{e.writeEvent({event:null,id:t,data:xs})},Ep=(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||!Dp(o,r.visibleSet,r.commentableSet)){Tp(e,t.id);return}e.writeEvent({event:null,id:t.id,data:ys(n,r.internalUserId,Ap(o,r.commentableSet))})},Cs=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:s}=e,c=async(d,u)=>{let{request:R,internalUserId:p,cursor:m}=u,h=u.initialScope.visible,y=u.initialScope.commentable,S=0,T=setInterval(()=>{let k=++S;n(R,"refresh").then(H=>{if(k===S){if(!H.ok){d.close();return}h=H.scope.visible,y=H.scope.commentable}})},ho);d.onClose(()=>clearInterval(T));let D=m===null?ws:m,f=m!==null&&o!==void 0,b=[],M=null,I=k=>{pt(k.id,D)||(D=k.id,Ep(d,k,{internalUserId:p,visibleSet:h,commentableSet:y}))},_=async(k,H)=>{let[E]=await k.xRange(i,"-","+",{COUNT:1});return E!==void 0&&!pt(E.id,H)},V=async(k,H)=>{if(await _(k,H))return!1;let E=H;for(;;){let x=await k.xRange(i,E,"+",{COUNT:Xr}),$=x[0];if($!==void 0&&$.id!==E&&await _(k,E))return!1;for(let ee of x){if(M!==null&&pt(M,ee.id))return!0;pt(ee.id,D)||I(Yt(ee,s).entry)}let K=x.at(-1);if(x.length<Xr||K===void 0||d.isClosed())return!0;E=K.id}},v=a.subscribe(k=>{if(!f){I(k);return}pt(k.id,D)||(M===null&&(M=k.id),b.push(k))},k=>{s.error(`[SSE:${p}] Fan-Out reader error:`,k),d.close()});if(d.onClose(v),m===null){await a.ready();try{let k=await o?.getClient();if(k){let H=await k.xRevRange(i,"+","-",{COUNT:1});H.length>0&&!pt(H[0].id,D)&&(D=H[0].id)}}catch{}}if(d.writeEvent({event:null,id:D===ws?null:D,data:xs}),(0,St.startSseHeartbeat)(d,{intervalMs:Qo,retry:bp,runtime:Is.systemSseRuntime}),m===null||o===void 0)return;await a.ready();let O=await o.getClient();if(O===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await V(O,m)){d.writeRetry(Es),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}f=!1;for(let k of b.splice(0))I(k)};return async({request:d,params:u})=>{let R,p=()=>{let h=new Headers;R!==void 0&&h.append("Set-Cookie",R);for(let[y,S]of Object.entries(et))h.set(y,S);return h},m=h=>(0,St.terminalStreamResponse)(h,{data:"",retryMs:Es,headers:p()});try{let h=await t(d,{failureRedirect:null});R=h.cookie;let{user:y}=h;if(!y)return m("auth-required");let S=await r.getUserIdByExternalId(y.id);if(!S)return m("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:p()});let T=(0,St.readLastEventId)(d,Xo);if(T!==null&&!Zo(T))return s.warn(`[SSE:${S}] malformed resume cursor; asking the client to resync`),m("resync-required");let D=qr(d),f=await l.admit(S,"sse",D);if(f===null){let M=p();for(let[I,_]of Object.entries(De(503)))M.set(I,_);return new Response("Too many streams",{status:503,headers:M})}let b=!1;try{let M=await n(d,"initial");if(!M.ok){let _=p();for(let[V,v]of Object.entries(De(503)))_.set(V,v);return new Response(hr,{status:503,headers:_})}let I=M.scope;return(0,St.createSseResponse)({requestSignal:D,headers:p(),onError:(_,V)=>s.error(`[SSE:${S}] ${V} failed:`,_),produce:_=>(b=!0,_.onClose(f),c(_,{request:d,internalUserId:S,cursor:T,initialScope:I}))})}finally{b||f()}}catch(h){if(h instanceof Response)throw h;let y=h instanceof Error?h:new Error(String(h));return s.error(`500 sse name=${y.name} message=${y.message}`),new Response("Internal Server Error",{status:500,headers:p()})}}};var Ms=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...et});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},wp=Object.freeze({...lr,route:"api",frameworkDataRefusal:({params:e})=>Un(e.endpoint)&&Ct[e.endpoint].body==="stream"?kr():null}),Ip=Object.freeze({...lr,route:"action"}),_p=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),Os=6e4,Fs=5,xp=Fs*Math.ceil(Os/500),Cp=2,Mp=6,Pp=6e4,Lp=Fs*Cp*Mp,kp=2,Np=10,vp=2,Op=10,Ps=(e,t)=>Math.max(e,Mr)*t,Hs=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},Fp=Object.freeze({etag:(e,t,r)=>La(e,t,r,200),"no-store":(e,t,r)=>Yn(t,r,200)}),Hp=e=>jn(e.body==="json"?Fp[e.cache]:null),Ls=jn(null),ks=(e,t,r,n)=>Hs(e(t,r,{error:{message:n.message}},n.status),n.headers),Ns=(e,t,r)=>Hs(e(t,r,null,503),De(503));function Zr(e){Br(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:se("service.titleMaxLength",r.titleMaxLength,1)},{loginRedirectPath:s}=e;if(typeof s!="string"||s.trim()==="")throw Q("loginRedirectPath","the non-blank path of the host's sign-in route",s);let c=be(e.logger,3,"API"),d=be(e.logger,3,"Visibility"),u=As(Zt("resolveVisibleSourceTypes",e.resolveVisibleSourceTypes),d),R=be(e.logger,1,"SSE"),p=be(e.logger,1,"Attachment"),m=be(e.logger,2,"Isolation"),h=be(e.logger,2,"Action"),y=be(e.logger,2,"Search"),S=be(e.logger,2,"Refresh"),T=be(e.logger,2,"Streams"),D=be(e.logger,2,"Reads"),f=ct({reason:"refresh_rate_limit",limitPerWindow:Lp,windowMs:Pp,logger:S,windowFields:()=>"route=api"}),b=ki(T),M=Mi(D),I=async(g,C,w,L,N,q)=>{let W=await r.getUserIdByExternalId(C.id);try{return await q(W===null?void 0:M.admissionFor(W,g,w.signal))}catch(U){if(U instanceof Ye)return Vr(N,w,L);throw U}},_=(g,C,w,L,N)=>{let q=f.spend(C.id,`endpoint=${g}`);return q===null?null:ks(N,w,L,q)},V=async({request:g})=>{let{user:C,cookie:w}=await t(g,{failureRedirect:s}),L=new Headers;w&&L.append("Set-Cookie",w);let N=await r.getUserIdByExternalId(C.id),q=N?n(N):null;return{data:{user:C,userId:q},headers:L}},v=g=>{let{limiter:C}=g;return async(w,L,N,q,W,U)=>{if(C===null)return U(N,L,{error:{message:"Unknown endpoint"}},404);let G=g.parse(w);if(!G.ok)return U(N,L,G.invalid,400);let P=await r.getUserIdByExternalId(q.id);if(!P)return U(N,L,g.emptyAnswer(G.parsed),200);let{signal:X}=N,j=await C.admit(P,X);if("refusal"in j)return X.aborted?Ns(U,N,L):ks(U,N,L,j.refusal);try{X.throwIfAborted();let Z=await g.read(G.parsed,{userId:P,user:q,scope:W},X);return X.throwIfAborted(),U(N,L,Z,200)}catch(Z){if(X.aborted&&Z===X.reason)return Ns(U,N,L);throw Z}finally{j.release()}}},O=r.searchLimits===null?null:yr({...r.searchLimits,route:ce.search,logger:y}),k=r.searchLimits===null?null:yr({concurrency:Ps(r.searchLimits.concurrency,kp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Np,route:ce.reports,logger:y}),H=r.searchLimits===null?null:yr({concurrency:Ps(r.searchLimits.concurrency,vp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Op,route:ce.searchMarks,logger:y}),E=r.searchLimits===null?null:yr({...r.searchLimits,route:ce.searchFacets,logger:y}),x={[ce.businessDate]:async(g,C,w,L,N,q)=>{let W=g.searchParams.get(ge.businessDate),U=W===null?null:Ft(W);if(U===null)return q(w,C,{error:{message:"Invalid business date"}},400);let G=sr(g.searchParams.get(ge.forceRefresh));if(G===null)return q(w,C,{error:{message:"Invalid forceRefresh"}},400);let P=G?_(ce.businessDate,L,w,C,q):null;return P!==null?P:I(ce.businessDate,L,w,C,q,async X=>{let j=await r.getDailyReportsByBusinessDateByExternalId(N,U,L.id,{forceRefresh:G,admission:X});return q(w,C,{businessDate:U,reports:j},200)})},[ce.idsStream]:Bi({service:r,logger:c,streamSlots:b,missGate:M,refuseForcedRead:(g,C,w,L)=>_(ce.idsStream,g,C,w,L)}),[ce.report]:async(g,C,w,L,N,q)=>{let W=We(g.searchParams.get(ge.reportHubId));if(W===null)return q(w,C,{error:{message:"Invalid reportHubId"}},400);let U=sr(g.searchParams.get(ge.forceRefresh));if(U===null)return q(w,C,{error:{message:"Invalid forceRefresh"}},400);let G=U?_(ce.report,L,w,C,q):null;return G!==null?G:I(ce.report,L,w,C,q,async P=>{let X=await r.getDailyReportDetailByIdByExternalId(N,W,L.id,{snapshot:!0,forceRefresh:U,admission:P});return X?q(w,C,{report:X},200):q(w,C,{error:{message:"Report not found"}},404)})},[ce.search]:v({limiter:O,parse:g=>{let C=g.searchParams.get(ge.searchQuery),w=Fn(g.searchParams.get(ge.searchCombine));if(C===null||w===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let L=Sa(g.searchParams,r.searchFilterSourceTypes);if(!L.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:L.reason}}};let N=cs(C,w,L.filters);if(!N.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:N.reason}}};let{criteria:q}=N;return{ok:!0,parsed:{criteria:q,words:q.plan===null?[]:mr(q.plan)}}},emptyAnswer:({words:g})=>vn([],g),read:async({criteria:g,words:C},{userId:w,scope:L})=>vn(await r.searchDailyReports(L,w,g),C)}),[ce.reports]:v({limiter:k,parse:g=>{let C=Hn(g.searchParams.get(ge.reportIds));return C===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:C}},emptyAnswer:()=>({reports:[]}),read:async(g,{user:C,scope:w})=>({reports:await r.getDailyReportDetailsByIdsByExternalId(w,g,C.id)})}),[ce.searchMarks]:v({limiter:H,parse:g=>{let C=g.searchParams.get(ge.searchQuery),w=Fn(g.searchParams.get(ge.searchCombine));if(C===null||w===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let L=Jr(C,w);if(!L.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:L.reason}}};let N=Hn(g.searchParams.get(ge.reportIds));return N===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:L.plan,ids:N}}},emptyAnswer:({plan:g})=>({wordsDigest:Cr(mr(g)),reports:[],deferred:[]}),read:({plan:g,ids:C},{userId:w,scope:L},N)=>r.markDailyReportSearchHits(L,w,g,C,{signal:N})}),[ce.searchFacets]:v({limiter:E,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(g,{userId:C,scope:w})=>r.listDailyReportSearchFacets(w,C)})},$=async({request:g,params:C})=>{let{user:w,cookie:L}=await t(g,{failureRedirect:null}),N=L??null;if(!w)return Ls(g,N,{error:{message:"Unauthorized"}},401);let q=C.endpoint;if(!Un(q))return Ls(g,N,{error:{message:"Unknown endpoint"}},404);let W=Ct[q],U=Hp(W),G=xa[W.body];if(!G.includes(g.method)){let X=U(g,N,{error:{message:"Method not allowed"}},405);return X.headers.set("Allow",G.join(", ")),X}let P=le();try{let X=new URL(g.url),j=await u(g,"initial"),Z=j.ok?await x[q](X,N,g,w,j.scope,U):Ts(U,g,N);return W.body==="json"&&c.debug(Z.headers.has("ETag")?`${Z.status} endpoint=${q} etag_match=${Z.status===304}`:`${Z.status} endpoint=${q}`),Z}catch(X){let j=le()-P,Z=X instanceof Error?X:new Error(String(X));return c.error(`500 endpoint=${q} elapsed=${j}ms name=${Z.name} code=${"code"in Z?Z.code:"N/A"} message=${Z.message}`,Z),U(g,N,{error:{message:"Internal Server Error"}},500)}},K=_a(h),ee=ct({reason:"rate_limit",limitPerWindow:xp,windowMs:Os,logger:h,windowFields:()=>"route=action"}),J=async(g,C,w,L,N)=>{let{clientTempId:q}=g;if(g.intent==="create")try{let P=await r.createDailyReport(w,C,g.businessDate,q);return N(g,P.reportHubId,{report:P})}catch(P){if(P instanceof Error&&P.message==="Forbidden")return L({error:"Creating reports is restricted"},{status:403});throw P}let{reportHubId:W,businessDate:U}=g,G=async(P,X)=>{try{let j=await X(P.value);return N(P,W,{updatedStatus:{isStarred:j.isStarred,isRead:j.isRead},operationTimestamp:P.operationTimestamp})}catch(j){if(j instanceof Error&&j.message==="Not Found")return L({error:"Report not found"},{status:404});throw j}};switch(g.intent){case"update":try{return await r.updateDailyReport(w,W,C,g.changes,q),N(g,W,{})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return L({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return L({error:"Report not found"},{status:404})}throw P}case"publish":try{let P=await r.publishDailyReport(w,W,C,q);return N(g,W,{report:P})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return L({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return L({error:"Report not found"},{status:404})}throw P}case"delete":try{return await r.deleteDailyReport(w,W,C,q),N(g,W,{})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return L({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return L({error:"Report not found"},{status:404})}throw P}case"toggleStar":return await G(g,P=>r.setStarStatus(w,C,W,U,P,q));case"toggleRead":return await G(g,P=>r.setReadStatus(w,C,W,U,P,q));case"addComment":try{let P=await r.addComment(w,C,W,g.content,U,q);return N(g,W,{newComment:P})}catch(P){if(P instanceof Error){if(P.message==="Not Found")return L({error:"Report not found"},{status:404});if(P.message.startsWith("Comments are restricted"))return L({error:"Comments are restricted for this report"},{status:403})}throw P}case"deleteComment":try{return await r.deleteComment(w,C,W,g.commentId,U,q),N(g,W,{deletedCommentId:g.commentId})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return L({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return L({error:"Comment not found"},{status:404})}throw P}}},ye=async({request:g,params:C})=>{let{user:w,cookie:L}=await t(g,{failureRedirect:null}),N=(U,G)=>Ms(U,{...G,setCookie:L}),q=(U,G,P)=>Ms(_p(U,G,P),{setCookie:L});if(!w)return N({error:"Unauthorized"},{status:401});let W=le();try{if(C.endpoint!==ce.action)return N({error:"Unknown endpoint"},{status:404});let U=ee.spend(w.id,"action");if(U!==null)return N({error:U.message},{status:U.status,headers:U.headers});let G=await Ia(g,l);if("refusal"in G){let{refusal:Z}=G;return Z.status===413&&K(Z.measuredBy),N({error:Z.error},{status:Z.status})}let{command:P}=G;if(P.intent==="clearCache"&&!e.enableDevCacheClear)return N({error:"Invalid intent"},{status:400});let X=await u(g,"initial");if(!X.ok)return N({error:hr},{status:503,headers:{...De(503),"Cache-Control":"no-store"}});let j=await r.getUserIdByExternalId(w.id);return j?P.intent==="clearCache"?(await r.clearCache(),N({status:"OK",intent:"clearCache"})):await J(P,j,X.scope,N,q):N({error:"User not found"},{status:404})}catch(U){if(U instanceof Response)throw U;let G=le()-W,P=U instanceof Error?U:new Error(String(U));return c.error(`500 action elapsed=${G}ms name=${P.name} message=${P.message}`,P),N({error:"Internal Server Error"},{status:500})}},Se=Cs({authenticate:t,service:r,resolveViewerScope:u,redis:o,sseReader:a,streamKey:i,streamSlots:b,logger:R}),te=wi({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:u,logger:p}),Ue=Fa(m),F=(g,C)=>async w=>{let L=Oa(w.request)?g.frameworkDataRefusal(w):null;if(L!==null)throw L;let N=(0,vs.crossOriginRefusal)(w.request,g);return N===void 0?C(w):(Ue(g.route,N,w.request),g.crossSiteRejection())};return{index:{loader:V},api:{loader:F(wp,$),action:F(Ip,ye)},sse:{loader:F(_s,Se)},attachment:{loader:F(Ei,te)}}}var Kt=require("@aiquants/mssql"),Re=require("drizzle-orm");var Up=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],$p=["document","comment"],Bp=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],Vp=["hubId","ordinal","authorUserId","commentText"],fo=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Us=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw fn(e,n,r)},$s=(e,t,r)=>{if(typeof t!="object"||t===null)throw Q(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw Q(`${e}.${o}`,"a column",n[o])},Bs=(e,t)=>{if(!fo(e))throw Q("search","a plain object",e);Us("search key",e,Up);let{tables:r}=e;if(!fo(r))throw Q("search.tables","a plain object with document and comment",r);Us("search.tables key",r,$p),$s("search.tables.document",r.document,Bp),$s("search.tables.comment",r.comment,Vp);let n=new Map;if(e.externalSourceTexts!==void 0){if(!fo(e.externalSourceTexts))throw Q("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw fn("search.externalSourceTexts key",o,t);if(typeof a!="function")throw Q(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:se("search.concurrency",e.concurrency,1),rateLimitPerMinute:se("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var gt=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},Pt=(e,t)=>{let r=typeof e=="string"?We(e):typeof e=="number"&&Xe(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},Lt=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};var B=require("drizzle-orm");var mt=require("drizzle-orm"),Vs=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 mt.sql.join(e.map(t=>mt.sql`${t}`),mt.sql`, `)},en=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return mt.sql`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${Vs(t)}))`},qs=(e,t)=>{let{hubLabel:r,label:n}=e;return mt.sql`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${Vs(t)}))`},tn=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?mt.sql`${o.userId} = ${t} OR ${o.userId} IS NULL`:mt.sql`${o.userId} = ${t}`;return mt.sql`(${a} OR NOT ${en(e,r)})`};var qp=/[[%_]/gu,Yp=e=>e.replace(qp,t=>`[${t}]`),Ys=e=>`%${Yp(e)}%`;var Ke=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),kt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),Rr=Object.freeze({value:"value"}),_e=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),Y=e=>B.sql`${B.sql.identifier(e.name)}`,fr=e=>B.sql.join(e.map(t=>B.sql`${t}`),B.sql`, `),js=(e,t)=>B.sql`SELECT ${Y(e.id)} AS ${B.sql.identifier(_e.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${fr(t)}) ORDER BY ${e.id}`,jp=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>Ys(u.text)),l=B.sql.join(i.map(u=>B.sql`${o.searchText} LIKE ${u}`),B.sql` OR `),s=B.sql.join(i.map(u=>B.sql`${a.commentText} LIKE ${u}`),B.sql` OR `),c=pr(n.sourceType,r.scope.commentable),d=c===void 0?B.sql``:B.sql` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return B.sql`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},Ws=(e,t,r)=>B.sql`(${B.sql.join(t.words.map(n=>jp(e,n,r)),B.sql` AND `)})`,Ro=(e,t,r,n)=>{let{hub:o}=e,a=[B.sql`${o.deletedAt} IS NULL`,tn(e,t.userId,r,"author")],i=pr(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(B.sql`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},Wp=(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.sql`LOWER(${r.sourceType}) IN (${fr([...t.sourceTypes])})`)}return t.authors!==null&&o.push(B.sql`${n.authorName} IN (${fr(t.authors)})`),t.customers!==null&&o.push(B.sql`${n.customerName} IN (${fr(t.customers)})`),o},zs=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...Ro(e,r,n,o),...Wp(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?B.sql` AND `:B.sql` OR `;s.push(B.sql`(${B.sql.join(l.sets.map(d=>Ws(e,d,r)),c)})`)}return B.sql`SELECT ${Y(a.id)} AS ${B.sql.identifier(Ke.reportHubId)}, CONVERT(char(10), ${Y(a.businessDate)}, 23) AS ${B.sql.identifier(Ke.businessDate)}, ${Y(a.sourceType)} AS ${B.sql.identifier(Ke.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.sql.join(s,B.sql` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},Gs=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=B.sql.join(t.sets.map((s,c)=>B.sql`(CASE WHEN ${Ws(e,s,r)} THEN ${2**c} ELSE 0 END)`),B.sql` + `);return B.sql`SELECT ${Y(a.id)} AS ${B.sql.identifier(kt.reportHubId)}, ${l} AS ${B.sql.identifier(kt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.sql.join(Ro(e,r,n,o),B.sql` AND `)}`},Ks=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...Ro(e,r,n),B.sql`${i} IS NOT NULL`];return B.sql`SELECT ${i} AS ${B.sql.identifier(Rr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${B.sql.join(l,B.sql` AND `)} GROUP BY ${i} ORDER BY ${i}`},Js=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(s=>({[n.hubId.name]:s.hubId,[n.searchText.name]:s.searchText,[n.sourceDigest.name]:s.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:s.authorName,[n.customerName.name]:s.customerName}))),i=JSON.stringify(t.flatMap(s=>s.comments.map(c=>({[o.hubId.name]:s.hubId,[o.ordinal.name]:c.ordinal,[o.authorUserId.name]:c.authorUserId,[o.commentText.name]:c.commentText})))),l=JSON.stringify(t.map(s=>s.hubId));return B.sql`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.${
|
|
9
|
-
WHEN NOT MATCHED THEN INSERT (${
|
|
3
|
+
`))}catch(R){if(u.stop(),s=null,o(),l||r.aborted)return;R instanceof Qe||n.error(`ids-stream emission failed: ${R instanceof Error?R.message:String(R)}`);try{let p={kind:"error",error:Pd};d.enqueue(i.encode(`${JSON.stringify(p)}
|
|
4
|
+
`)),d.close()}catch{}}},cancel(){l=!0,o(),Ji(t)}});return new Response(c,{status:200,headers:ts(e)})},rs=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,s,c,d,u,R,p)=>{let m=!1,h=null,y=null,S=new Promise((f,g)=>{h=f,y=g});S.catch(()=>{});let T=t.getDailyReportIdsByExternalId(c,s.id,{forceRefresh:l.forceRefresh,admission:p,onFetchStart:l.cursor?void 0:()=>{m=!0,t.readSseStreamAnchor().then(f=>t.getDailyReportIdsFirstPageByExternalId(c,s.id,rn).then(g=>({items:g,streamAnchor:f}))).then(f=>h?.(f),f=>y?.(f))}});if(T.catch(()=>{}),l.cursor){let{items:f,streamAnchor:g,snapshot:k}=await T,x=l.snapshot!==null&&l.snapshot===k;return Xi(d,Qi(f,x?l.cursor:null,rn,{snapshot:k,restarted:!x,streamAnchor:g}),u,r,R)}let D=(async function*(){let f=await Promise.race([T.then(x=>({kind:"full",source:x}),x=>({kind:"full-error",error:x})),S.then(x=>({kind:"page",page:x}),()=>({kind:"page-error"}))]),g=null,k=!1;if(f.kind==="full")g=f.source;else if(f.kind==="page"){let{items:x,streamAnchor:C}=f.page;if(x.length<rn){yield{kind:"chunk",...Ft(x,0,x.length),nextCursor:null,isLast:!0,total:x.length,streamAnchor:C};return}yield{kind:"chunk",...Ft(x,0,x.length),nextCursor:null,isLast:!1,provisional:!0},k=!0}else if(f.kind==="full-error"&&m){let x=await S.catch(()=>null);x&&x.items.length>0&&(yield{kind:"chunk",...Ft(x.items,0,x.items.length),nextCursor:null,isLast:!1,provisional:!0})}g===null&&(g=await T),yield*Qi(g.items,null,k?Zi:rn,{snapshot:g.snapshot,streamAnchor:g.streamAnchor})})();return Xi(d,D,u,r,R)};return async(l,s,c,d,u,R)=>{let p=ji(l.searchParams);if("refused"in p)return R(c,s,{error:{message:p.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:m}=p;if(m.forceRefresh){let T=a(d,c,s,R);if(T!==null)return T}let h=tn(c),y=await t.getUserIdByExternalId(d.id),S=await n.admit(y,"ids-stream",h);if(S===null){let T=R(c,s,{error:{message:kd}},503);for(let[D,f]of Object.entries(Ee(503)))T.headers.set(D,f);return T}if(h.aborted)return new Response(null,{status:200,headers:ts(s)});try{return await i(m,d,u,s,h,S,y===null?void 0:o.admissionFor(y,ue.idsStream,h))}catch(T){if(S(),T instanceof Qe)return en(R,c,s);throw T}}};var Bt=require("drizzle-orm");var et="Internal",ns=e=>e.trim().toLowerCase();var Nd="",Od=64,Hd=e=>e.toLowerCase(),os=e=>{let t=new Set;if(!Array.isArray(e))return t;for(let r of e){if(typeof r!="string")continue;let n=ns(r);n.length>0&&t.add(n)}return t};function Ie(e,t){return e===null?!0:t==null?!1:e.has(Hd(t))}function Ne(e){return e!==null&&e.size===0}var Fd=4e3,mo=e=>{let t=e.getSQLType();if(!t.startsWith("nvarchar("))throw Q("tables.hub.sourceType","an nvarchar(n) column with a declared length (source types compare as UTF-16 bytes)",t);return le("tables.hub.sourceType.length",e.length,1,Fd)};function Tr(e,t){if(t===null)return;let r=mo(e),n=[...t].filter(a=>a.length<=r);if(n.length===0)return Bt.sql`1 = 0`;let o=Bt.sql.raw(`VARBINARY(${2*r})`);return(0,Bt.inArray)(Bt.sql`CAST(LOWER(${e}) AS ${o})`,n.map(a=>Bt.sql`CAST(${a} AS ${o})`))}var Xt,Zt,Ar=class Ar{constructor(t,r){wn(this,Xt);wn(this,Zt);In(this,Xt,t),In(this,Zt,r)}get visible(){return sr(this,Xt)===null?null:new Set(sr(this,Xt))}get commentable(){return sr(this,Zt)===null?null:new Set(sr(this,Zt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=os(r?t.read:t);if(!r||t.comment===void 0)return new Ar(n,n);let o=new Set;for(let a of os(t.comment))n.has(a)&&o.add(a);return new Ar(n,o)}static unrestricted(t){return new Ar(null,null)}};Xt=new WeakMap,Zt=new WeakMap;var ze=Ar,po=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),Ud=new Set(["read","comment"]),is=e=>{if(po(e))return ze.restrictTo(e);if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=Object.keys(e);if("unrestricted"in e){let o=e.unrestricted;return t.length===1&&typeof o=="string"&&o.trim().length>0?ze.unrestricted(o):null}let{read:r,comment:n}=e;return t.every(o=>Ud.has(o))&&po(r)?n===void 0?ze.restrictTo({read:r}):po(n)?ze.restrictTo({read:r,comment:n}):null:null};function nn(e){let t=as(e.visible),r=as(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function as(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Nd);if(t.length<=Od)return`s:${t}`;let r=2166136261;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return`sh:${(r>>>0).toString(16)}`}var ss=(e,t,r,n)=>Ie(n.commentable,t)||e.authorUserId===r;var Ts=require("@aiquants/fuzzy-search");var ds=require("crypto"),yo=require("timers/promises"),Se=require("@aiquants/fuzzy-search/normalize");var an=`
|
|
5
|
+
`,ho=4e3,$d=1,ps=new Set([8203,8288,65279,173]),Bd=new RegExp(`[${String.fromCodePoint(...ps)}]`,"gu"),ms=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),ys=/(\s+)/u,Vd=/^\s+$/u,qd=new RegExp(ys.source,"gu"),Yd=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,Wd=new Set([8205,1536,1537,1538,1539,1540,1541,1757,1807,2192,2193,2274,69821,69837,70082,70083,71999,72001,72250,72324,72325,72326,72327,72328,72329,73030,73474]),sn=e=>e.replace(Bd,"");var fo=e=>(0,Se.normalizeText)(e,Se.DEFAULT_NORMALIZE_OPTIONS),on=e=>fo(sn(e)),jd=(0,Se.resolveNormalizeOptions)({...Se.DEFAULT_NORMALIZE_OPTIONS,convertRomaji:!0},"[daily-report] search reading options"),zd=3,Gd=/^[-ー]+/u,Kd=/[^\p{L}\p{M}]/gu,Jd=/ー{2,}/gu,Qd=/\p{Script=Latin}/u,ls=/(?=\p{L})\p{Script=Latin}/u,Xd=e=>(0,Se.clusterCountOf)(e.replace(Gd,"").replace(Kd,"").replace(Jd,"\u30FC")),Zd=(e,t)=>{for(let r of t)if(!(0,Se.isAnswerTier)(r.tier)||r.splitTier!==null)throw new Error(`[daily-report] search readings: queryNeedles gave an unfinished needle for the word ${JSON.stringify(e)} (text ${JSON.stringify(r.text)}, tier ${r.tier}, splitTier ${r.splitTier})`)},hs=e=>{if(!ls.test(e))return[];let t=on(e);if(!ls.test(t))return[];let r=(0,Se.queryNeedles)(t,jd,!1);Zd(t,r);let n=[];for(let o of r){if(o.tier===Ut.word)continue;let a=on(o.text);if(!(a.length===0||a.length>xe.maxWordLength)&&!(a===t||Qd.test(a))&&!(Xd(a)<zd||n.includes(a))&&(n.push(a),n.length===Wn))break}return n},Ro=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},fs=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&Ro(e,t-1)?t-2:t-1;return Yd.test(String.fromCodePoint(r))&&!Wd.has(e.codePointAt(n))},ep=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!fs(e,i);)i--;i===a&&(i=a+r,Ro(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}},So=(e,t)=>{if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let r=[],n=0,o=0,a=0,i=0,l=()=>{i>0&&r.push([{start:a,end:a+i}]),i=0};for(let s of e.split(ys)){let c=o;if(o+=s.length,i+s.length<=t){i===0&&(a=c),i+=s.length;continue}if(l(),Vd.test(s))continue;if(s.length<=t){a=c,i=s.length;continue}let d=ep(s,c,t);n+=d.forcedCuts,r.push(d.pieces)}return l(),{chunks:r,forcedCuts:n}},go=(e,t)=>{let r=So(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>fo(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},tp=(e,t)=>{let r=0;for(let n of e.matchAll(ms))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},rp=(e,t)=>{if(e.partialReadings!==null)throw new Error(`[daily-report] search marks: the mapped forms of the piece ${JSON.stringify(t)} carry partial readings`);return e.canonical},Rs=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],s=[];for(let c of a){let d=e.slice(c.start,c.end),u=rp((0,Se.toMappedFormsInto)(d,Se.DEFAULT_NORMALIZE_OPTIONS,new Se.InteriorPairs(0)),d),[R,p]=(0,Se.trimmedRange)(u.text);i+=u.text.slice(R,p);for(let m=R;m<p;m++)l.push(c.start+u.start[m]),s.push(c.start+u.end[m])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let c=0;c<l.length;c++)n.push(l[c]),o.push(s[c])}}return{text:r,start:n,end:o}},ln=(e,t=ho)=>{let r=[],n=0;return tp(sn(e),o=>{let a=go(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(an),forcedCuts:n}},Ss=e=>e.filter(t=>t.length>0).join(an),bo=(e,t)=>{let r=null;return{advance:n=>{if(r!==null)return 0;e.units=le("search text steps: units",n,1);let o=t.next();return o.done===!0&&(r={result:o.value}),n-e.units},done:()=>r!==null,result:()=>{if(r===null)throw new Error("[daily-report] search text: the steps are not done (advance until done() is true)");return r.result}}},cs=4096;function*np(e,t){let r=[],n=new Uint32Array(e.length),o=0,a=!1;for(let i=0;i<e.length;){for(;t.units===0;)yield;let l=Math.min(e.length,i+t.units);t.units-=l-i;let s=o,c=new Uint16Array(l-i);for(let d=i;d<l;d++){let u=e.charCodeAt(d);ps.has(u)||(c[o-s]=u,n[o++]=d)}if(o-s===l-i)a&&r.push(e.slice(i,l));else{a||r.push(e.slice(0,i)),a=!0;for(let d=s;d<o;d+=cs)r.push(Reflect.apply(String.fromCharCode,null,c.subarray(d-s,Math.min(o,d+cs)-s)))}i=l}return a?{text:r.join(""),rawIndex:n.subarray(0,o)}:{text:e,rawIndex:null}}var gs=e=>{let t={units:0};return bo(t,np(e,t))};function*op(e,t,r){let n=0;for(let o=0;o<e.length;){for(;r.units===0;)yield;let a=Math.min(e.length,o+r.units);r.units-=a-o;let i=a;for(let l of e.slice(o,Math.min(e.length,a+1)).matchAll(ms)){let s=o+l.index;if(s>=a)break;t(e.slice(n,s),n),n=s+l[0].length,i=Math.max(i,n)}o=i}t(e.slice(n),n)}var bs=(e,t)=>{let r={units:0};return bo(r,op(e,t,r))};function*us(e,t,r,n,o){let a=[],i=0,l=t;for(;r-l>n;){let s=l+n;for(;s>l;s--){for(;o.units===0;)yield;if(o.units-=1,fs(e,s))break}s===l&&(s=l+n,Ro(e,s)&&s--,i++),a.push({start:l,end:s}),l=s}return a.push({start:l,end:r}),{pieces:a,forcedCuts:i}}function*ap(e,t,r){if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let n=[],o=0,a=0,i=0,l=0,s=0,c=!1,d=(p,m,h)=>{let y=m-p;return i+y<=t?(i===0&&(a=p),i+=y,!1):(i>0&&n.push([{start:a,end:a+i}]),i=0,h?!1:y<=t?(a=p,i=y,!1):!0)},u=p=>{c&&(d(l,s,!0),l=s),c=!1,s=p},R=p=>{let m=-1;return!c&&s>l&&(d(l,s,!1)&&(m=l),l=s),c=!0,s=p,m};for(let p=0;p<e.length;){for(;r.units===0;)yield;let m=Math.min(e.length,p+r.units);r.units-=m-p;let h=p;for(let y of e.slice(p,m).matchAll(qd)){let S=p+y.index;S>h&&u(S),h=S+y[0].length;let T=R(h);if(T>=0){let D=yield*us(e,T,S,t,r);o+=D.forcedCuts,n.push(D.pieces)}}m>h&&u(m),p=m}if(d(l,s,c)){let p=yield*us(e,l,s,t,r);o+=p.forcedCuts,n.push(p.pieces)}return i>0&&n.push([{start:a,end:a+i}]),{chunks:n,forcedCuts:o}}var Ds=(e,t)=>{let r={units:0};return bo(r,ap(e,t,r))},ip=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
|
|
6
|
+
`)},sp=[`\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`],lp=["","\u30A2","\u4F50"," "],cp=()=>JSON.stringify(sp.map(e=>ln(e,8))),up=e=>`dr-search-v${$d};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var dp=async()=>{let e=(0,ds.createHash)("sha256");e.update(JSON.stringify(Se.DEFAULT_NORMALIZE_OPTIONS));for(let t of lp)await(0,yo.setImmediate)(),e.update("\0"),e.update(fo(ip(t)));return await(0,yo.setImmediate)(),e.update("\0"),e.update(cp()),up(e.digest("hex"))},pp=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},Do=pp(dp);var mp=/^-+/u,yp=/\s+/u,As=e=>{let t=mp.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},hp=(e,t)=>{let r=[...As(e).map(n=>({text:n,tier:Ut.word})),...t.flatMap(n=>As(n).map(o=>({text:o,tier:Ut.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},fp=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),cn=(e,t)=>{if(e.length>xe.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of(0,Ts.parseQuerySets)(sn(e),t).sets){let i=[],l=new Set;for(let c of a.split(yp)){let d=on(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>xe.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=hp(d,hs(c)),R=fp(u);l.has(R)||(l.add(R),i.push({alternatives:u}))}if(i.length>xe.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let s=JSON.stringify([...l].sort());n.has(s)||(n.add(s),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>xe.maxSets?{ok:!1,reason:"too-many-sets"}:o>xe.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},Er=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var qf=Object.freeze({sourceTypes:null,authors:null,customers:null}),Rp=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,Es=(e,t,r)=>{if(Pa(e)&&Rp(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=cn(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var ws=6e4,Sp=1,gp=3200,Is=2e3,bp=Object.freeze({search:gp,reports:Is,"search-marks":Is,"search-facets":null}),Dp=(e,t)=>{let r=bp[e];return r===null?null:{max:t,maxPerOwner:Vr,maxWaitMs:r}},wr=e=>{let{concurrency:t,route:r,logger:n}=e,o=gt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:ws,logger:n,windowFields:()=>`route=${r}`}),a=ct({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:Dp(r,t)}),i=Object.freeze({status:429,message:io,headers:Object.freeze({"Retry-After":String(Sp)})}),l=Ce({windowMs:ws,tallies:["busy"],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`busy_suppressed count=${c} since=${d} route=${r} concurrency=${t}`)}});return{admit:async(s,c)=>{let d=o.spend(s,r);if(d!==null)return{refusal:d};let u=await a.acquire(s,c);return u!==null?{release:u}:(o.refund(s,1),c.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};var $s=require("@aiquants/sse"),Mt=require("@aiquants/sse/server");var er=(e,t)=>{let r=e.message.data;if(!r)return{entry:{id:e.id,message:null},json:void 0};let n;try{n=JSON.parse(r)}catch(i){return t.error(`SSE message ${e.id} is not JSON:`,i),{entry:{id:e.id,message:null},json:void 0}}let o=Ur.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n});return{entry:Object.freeze({id:e.id,message:a}),json:n}},_s=new WeakMap,xs=(e,t,r)=>{let n=_s.get(e);n===void 0&&(n=new Map,_s.set(e,n));let o=n.get(t);if(o!==void 0)return o;let a=r();return n.set(t,a),a},Ao=e=>e,Ap=e=>{switch(e.type){case"connected":case"report-delete":return Ao(e);case"status-update":case"comment-add":case"comment-delete":{let{recipientRawUserId:t,...r}=e;return Ao(r)}}},Tp=(e,t,r)=>{let{recipientRawUserId:n,actorRawUserId:o,...a}=e,i=r?{...a.report,externalComments:[],postedComments:[]}:a.report;return Ao({...a,report:i,viewerIsActor:t})},Cs=(e,t,r)=>{let{parsed:n}=e;if(n.type!=="report-create"&&n.type!=="report-update"&&n.type!=="report-publish")return xs(e,"every-viewer",()=>JSON.stringify(Ap(n)));let o=n.actorRawUserId===t;return xs(e,`${o?"actor":"observer"}${r?"-comments-redacted":""}`,()=>JSON.stringify(Tp(n,o,r)))};var Ls=require("@aiquants/sse"),vs=require("@aiquants/sse/shared-source");var Ct="daily-report:ids:",To=(e,t)=>`${e}st:${t}`,Eo=e=>`${Ct}user:${e}:`,Ms=(e,t)=>To(Eo(e),t),tr=e=>`daily-report:date:${e}:user:`,rr=(e,t)=>`${tr(e)}${t}:`,Ps=(e,t,r)=>To(rr(e,t),r),Ge=e=>`daily-report:detail:${e}:user:`,wo=(e,t)=>`${Ge(e)}${t}:`,ks=(e,t,r)=>To(wo(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},Ep=5e3,wp=qr,nr=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=Ae(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:It}_createSource(){return(0,vs.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Ls.systemSseRuntime,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",i=>{this._logger.error("Redis client error:",i)});let o=!1,a=this._readLoop(n,t,r,()=>o);return async()=>{if(o=!0,n.isOpen)try{await n.quit()}catch{}await a}}async _readLoop(t,r,n,o){let a=n;try{for(;!o()&&t.isOpen;){let i=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:Ep,COUNT:wp});if(i)for(let l of i)for(let s of l.messages){a=s.id;let{entry:c,json:d}=er(s,this._logger);this._invalidateCaches(d),r.next(c)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(Ct),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ge(n))}};var Ip=6e4,Ir="Report visibility is unavailable",Ns=["initial","refresh"],Os=Object.freeze({ok:!1}),_p=e=>e===null?"null":Array.isArray(e)?"array":typeof e,Hs=(e,t)=>{let r=Ce({windowMs:Ip,tallies:Ns,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{t.error(`visibility_unavailable_suppressed count=${o} since=${a} cause=${n} reasons=${Ns.map(l=>`${l}:${i[l]}`).join(",")}`)}});return async(n,o)=>{let a;try{a=await e(n,{reason:o})}catch(l){return r.record("port_failure",o,()=>t.error(`visibility unavailable cause=port_failure reason=${o}`,l)),Os}let i=is(a);return i===null?(r.record("port_contract",o,()=>t.error(`visibility unavailable cause=port_contract reason=${o} answer=${_p(a)}`)),Os):{ok:!0,scope:i}}},Fs=(e,t,r)=>{let n=e(t,r,{error:{message:Ir}},503);for(let[o,a]of Object.entries(Ee(503)))n.headers.set(o,a);return n};var Bs=Object.freeze({...gr,route:"sse",frameworkDataRefusal:Wr}),Us=864e5,xp={baseMs:2e3,jitterMs:8e3},Io=6e4,dn=qr,Vs=JSON.stringify({type:"connected"}),Cp=e=>{let t=e.length,r=e["entries-added"];if(typeof t!="number"||!Number.isSafeInteger(t)||t<0||typeof r!="number"||!Number.isSafeInteger(r)||r<t)throw new Error(`XINFO STREAM must report length and entries-added as safe integers with entries-added >= length >= 0 (Redis 7.0 or later); got length=${String(t)} entries-added=${String(r)}`);return r-t},Mp=(e,t,r)=>{if(t===null&&r===null)return!0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Ie(t,e.report.sourceType);case"comment-add":case"comment-delete":return Ie(r,e.sourceType);case"report-delete":return Ie(t,e.sourceType)}},Pp=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Ie(t,e.report.sourceType),kp=(e,t)=>{e.writeEvent({event:null,id:t,data:Vs})},Lp=(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||!Mp(o,r.visibleSet,r.commentableSet)){kp(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Cs(n,r.internalUserId,Pp(o,r.commentableSet))})},qs=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:s}=e,c=async(d,u)=>{let{request:R,internalUserId:p,cursor:m}=u,h=u.initialScope.visible,y=u.initialScope.commentable,S=0,T=setInterval(()=>{let L=++S;n(R,"refresh").then(B=>{if(L===S){if(!B.ok){d.close();return}h=B.scope.visible,y=B.scope.commentable}})},Io);d.onClose(()=>clearInterval(T));let D=m===null?It:m,f=m!==null&&o!==void 0,g=[],k=null,x=L=>{dt(L.id,D)||(D=L.id,Lp(d,L,{internalUserId:p,visibleSet:h,commentableSet:y}))},C=async(L,B)=>{let[E]=await L.xRange(i,"-","+",{COUNT:1});return E!==void 0&&!dt(E.id,B)},Y=async(L,B)=>{let[E]=await L.xRange(i,"-","+",{COUNT:1});if(E===void 0)return!0;let I;if(B===It){if(Cp(await L.xInfoStream(i))>0)return!1;I=E.id}else{if(!dt(E.id,B))return!1;I=B}for(;;){let V=await L.xRange(i,I,"+",{COUNT:dn}),J=V[0];if(J!==void 0&&J.id!==I&&await C(L,I))return!1;for(let z of V){if(k!==null&&dt(k,z.id))return!0;dt(z.id,D)||x(er(z,s).entry)}let te=V.at(-1);if(V.length<dn||te===void 0||d.isClosed())return!0;I=te.id}},v=a.subscribe(L=>{if(!f){x(L);return}dt(L.id,D)||(k===null&&(k=L.id),g.push(L))},L=>{s.error(`[SSE:${p}] Fan-Out reader error:`,L),d.close()});if(d.onClose(v),m===null){await a.ready();try{let L=await o?.getClient();if(L){let B=await L.xRevRange(i,"+","-",{COUNT:1});B.length>0&&!dt(B[0].id,D)&&(D=B[0].id)}}catch{}}if(d.writeEvent({event:null,id:D===It?null:D,data:Vs}),(0,Mt.startSseHeartbeat)(d,{intervalMs:da,retry:xp,runtime:$s.systemSseRuntime}),m===null||o===void 0)return;await a.ready();let N=await o.getClient();if(N===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await Y(N,m)){d.writeRetry(Us),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}f=!1;for(let L of g.splice(0))x(L)};return async({request:d,params:u})=>{let R,p=()=>{let h=new Headers;R!==void 0&&h.append("Set-Cookie",R);for(let[y,S]of Object.entries(lt))h.set(y,S);return h},m=h=>(0,Mt.terminalStreamResponse)(h,{data:"",retryMs:Us,headers:p()});try{let h=await t(d,{failureRedirect:null});R=h.cookie;let{user:y}=h;if(!y)return m("auth-required");let S=await r.getUserIdByExternalId(y.id);if(!S)return m("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:p()});let T=(0,Mt.readLastEventId)(d,pa);if(T!==null&&!ma(T))return s.warn(`[SSE:${S}] malformed resume cursor; asking the client to resync`),m("resync-required");let D=tn(d),f=await l.admit(S,"sse",D);if(f===null){let k=p();for(let[x,C]of Object.entries(Ee(503)))k.set(x,C);return new Response("Too many streams",{status:503,headers:k})}let g=!1;try{let k=await n(d,"initial");if(!k.ok){let C=p();for(let[Y,v]of Object.entries(Ee(503)))C.set(Y,v);return new Response(Ir,{status:503,headers:C})}let x=k.scope;return(0,Mt.createSseResponse)({requestSignal:D,headers:p(),onError:(C,Y)=>s.error(`[SSE:${S}] ${Y} failed:`,C),produce:C=>(g=!0,C.onClose(f),c(C,{request:d,internalUserId:S,cursor:T,initialScope:x}))})}finally{g||f()}}catch(h){if(h instanceof Response)throw h;let y=h instanceof Error?h:new Error(String(h));return s.error(`500 sse name=${y.name} message=${y.message}`),new Response("Internal Server Error",{status:500,headers:p()})}}};var Ys=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...lt});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},vp=Object.freeze({...gr,route:"api",frameworkDataRefusal:({params:e})=>Jn(e.endpoint)&&$t[e.endpoint].body==="stream"?Wr():null}),Np=Object.freeze({...gr,route:"action"}),Op=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),Js=6e4,Qs=5,Hp=Qs*Math.ceil(Js/500),Fp=2,Up=6,$p=6e4,Bp=Qs*Fp*Up,Vp=2,qp=10,Yp=2,Wp=10,Ws=(e,t)=>Math.max(e,Vr)*t,Xs=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},jp=Object.freeze({etag:(e,t,r)=>za(e,t,r,200),"no-store":(e,t,r)=>to(t,r,200)}),zp=e=>ro(e.body==="json"?jp[e.cache]:null),js=ro(null),zs=(e,t,r,n)=>Xs(e(t,r,{error:{message:n.message}},n.status),n.headers),Gs=(e,t,r)=>Xs(e(t,r,null,503),Ee(503));function pn(e){Zr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:le("service.titleMaxLength",r.titleMaxLength,1)},{loginRedirectPath:s}=e;if(typeof s!="string"||s.trim()==="")throw Q("loginRedirectPath","the non-blank path of the host's sign-in route",s);let c=Ae(e.logger,3,"API"),d=Ae(e.logger,3,"Visibility"),u=Hs(lr("resolveVisibleSourceTypes",e.resolveVisibleSourceTypes),d),R=Ae(e.logger,1,"SSE"),p=Ae(e.logger,1,"Attachment"),m=Ae(e.logger,2,"Isolation"),h=Ae(e.logger,2,"Action"),y=Ae(e.logger,2,"Search"),S=Ae(e.logger,2,"Refresh"),T=Ae(e.logger,2,"Streams"),D=Ae(e.logger,2,"Reads"),f=gt({reason:"refresh_rate_limit",limitPerWindow:Bp,windowMs:$p,logger:S,windowFields:()=>"route=api"}),g=Gi(T),k=Wi(D),x=async(b,U,O,H,$,w)=>{let P=await r.getUserIdByExternalId(U.id);try{return await w(P===null?void 0:k.admissionFor(P,b,O.signal))}catch(M){if(M instanceof Qe)return en($,O,H);throw M}},C=(b,U,O,H,$)=>{let w=f.spend(U.id,`endpoint=${b}`);return w===null?null:zs($,O,H,w)},Y=async({request:b})=>{let{user:U,cookie:O}=await t(b,{failureRedirect:s}),H=new Headers;O&&H.append("Set-Cookie",O);let $=await r.getUserIdByExternalId(U.id),w=$?n($):null;return{data:{user:U,userId:w},headers:H}},v=b=>{let{limiter:U}=b;return async(O,H,$,w,P,M)=>{if(U===null)return M($,H,{error:{message:"Unknown endpoint"}},404);let F=b.parse(O);if(!F.ok)return M($,H,F.invalid,400);let _=await r.getUserIdByExternalId(w.id);if(!_)return M($,H,b.emptyAnswer(F.parsed),200);let{signal:j}=$,ee=await U.admit(_,j);if("refusal"in ee)return j.aborted?Gs(M,$,H):zs(M,$,H,ee.refusal);try{j.throwIfAborted();let K=await b.read(F.parsed,{userId:_,user:w,scope:P},j);return j.throwIfAborted(),M($,H,K,200)}catch(K){if(j.aborted&&K===j.reason)return Gs(M,$,H);throw K}finally{ee.release()}}},N=r.searchLimits===null?null:wr({...r.searchLimits,route:ue.search,logger:y}),L=r.searchLimits===null?null:wr({concurrency:Ws(r.searchLimits.concurrency,Vp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*qp,route:ue.reports,logger:y}),B=r.searchLimits===null?null:wr({concurrency:Ws(r.searchLimits.concurrency,Yp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Wp,route:ue.searchMarks,logger:y}),E=r.searchLimits===null?null:wr({...r.searchLimits,route:ue.searchFacets,logger:y}),I={[ue.businessDate]:async(b,U,O,H,$,w)=>{let P=b.searchParams.get(De.businessDate),M=P===null?null:zt(P);if(M===null)return w(O,U,{error:{message:"Invalid business date"}},400);let F=Sr(b.searchParams.get(De.forceRefresh));if(F===null)return w(O,U,{error:{message:"Invalid forceRefresh"}},400);let _=F?C(ue.businessDate,H,O,U,w):null;return _!==null?_:x(ue.businessDate,H,O,U,w,async j=>{let ee=await r.getDailyReportsByBusinessDateByExternalId($,M,H.id,{forceRefresh:F,admission:j});return w(O,U,{businessDate:M,reports:ee},200)})},[ue.idsStream]:rs({service:r,logger:c,streamSlots:g,missGate:k,refuseForcedRead:(b,U,O,H)=>C(ue.idsStream,b,U,O,H)}),[ue.report]:async(b,U,O,H,$,w)=>{let P=Xe(b.searchParams.get(De.reportHubId));if(P===null)return w(O,U,{error:{message:"Invalid reportHubId"}},400);let M=Sr(b.searchParams.get(De.forceRefresh));if(M===null)return w(O,U,{error:{message:"Invalid forceRefresh"}},400);let F=M?C(ue.report,H,O,U,w):null;return F!==null?F:x(ue.report,H,O,U,w,async _=>{let j=await r.getDailyReportDetailByIdByExternalId($,P,H.id,{snapshot:!0,forceRefresh:M,admission:_});return j?w(O,U,{report:j},200):w(O,U,{error:{message:"Report not found"}},404)})},[ue.search]:v({limiter:N,parse:b=>{let U=b.searchParams.get(De.searchQuery),O=Gn(b.searchParams.get(De.searchCombine));if(U===null||O===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let H=La(b.searchParams,r.searchFilterSourceTypes);if(!H.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:H.reason}}};let $=Es(U,O,H.filters);if(!$.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:$.reason}}};let{criteria:w}=$;return{ok:!0,parsed:{criteria:w,words:w.plan===null?[]:Er(w.plan)}}},emptyAnswer:({words:b})=>jn([],b),read:async({criteria:b,words:U},{userId:O,scope:H})=>jn(await r.searchDailyReports(H,O,b),U)}),[ue.reports]:v({limiter:L,parse:b=>{let U=Kn(b.searchParams.get(De.reportIds));return U===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:U}},emptyAnswer:b=>({outcomes:b.map(Rr)}),read:async(b,{user:U,scope:O},H)=>({outcomes:await r.getDailyReportDetailsByIdsByExternalId(O,b,U.id,{signal:H})})}),[ue.searchMarks]:v({limiter:B,parse:b=>{let U=b.searchParams.get(De.searchQuery),O=Gn(b.searchParams.get(De.searchCombine));if(U===null||O===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let H=cn(U,O);if(!H.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:H.reason}}};let $=Kn(b.searchParams.get(De.reportIds));return $===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:H.plan,ids:$}}},emptyAnswer:({plan:b})=>({wordsDigest:Br(Er(b)),reports:[],deferred:[]}),read:({plan:b,ids:U},{userId:O,scope:H},$)=>r.markDailyReportSearchHits(H,O,b,U,{signal:$})}),[ue.searchFacets]:v({limiter:E,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(b,{userId:U,scope:O})=>r.listDailyReportSearchFacets(O,U)})},V=async({request:b,params:U})=>{let{user:O,cookie:H}=await t(b,{failureRedirect:null}),$=H??null;if(!O)return js(b,$,{error:{message:"Unauthorized"}},401);let w=U.endpoint;if(!Jn(w))return js(b,$,{error:{message:"Unknown endpoint"}},404);let P=$t[w],M=zp(P),F=qa[P.body];if(!F.includes(b.method)){let j=M(b,$,{error:{message:"Method not allowed"}},405);return j.headers.set("Allow",F.join(", ")),j}let _=ce();try{let j=new URL(b.url),ee=await u(b,"initial"),K=ee.ok?await I[w](j,$,b,O,ee.scope,M):Fs(M,b,$);return P.body==="json"&&c.debug(K.headers.has("ETag")?`${K.status} endpoint=${w} etag_match=${K.status===304}`:`${K.status} endpoint=${w}`),K}catch(j){let ee=ce()-_,K=j instanceof Error?j:new Error(String(j));return c.error(`500 endpoint=${w} elapsed=${ee}ms name=${K.name} code=${"code"in K?K.code:"N/A"} message=${K.message}`,K),M(b,$,{error:{message:"Internal Server Error"}},500)}},J=Va(h),te=gt({reason:"rate_limit",limitPerWindow:Hp,windowMs:Js,logger:h,windowFields:()=>"route=action"}),z=async(b,U,O,H,$)=>{let{clientTempId:w}=b;if(b.intent==="create")try{let _=await r.createDailyReport(O,U,b.businessDate,w);return $(b,_.reportHubId,{report:_})}catch(_){if(_ instanceof Error&&_.message==="Forbidden")return H({error:"Creating reports is restricted"},{status:403});throw _}let{reportHubId:P,businessDate:M}=b,F=async(_,j)=>{try{let ee=await j(_.value);return $(_,P,{updatedStatus:{isStarred:ee.isStarred,isRead:ee.isRead},operationTimestamp:_.operationTimestamp})}catch(ee){if(ee instanceof Error&&ee.message==="Not Found")return H({error:"Report not found"},{status:404});throw ee}};switch(b.intent){case"update":try{return await r.updateDailyReport(O,P,U,b.changes,w),$(b,P,{})}catch(_){if(_ instanceof Error){if(_.message==="Unauthorized")return H({error:"Unauthorized"},{status:403});if(_.message==="Not Found")return H({error:"Report not found"},{status:404})}throw _}case"publish":try{let _=await r.publishDailyReport(O,P,U,w);return $(b,P,{report:_})}catch(_){if(_ instanceof Error){if(_.message==="Unauthorized")return H({error:"Unauthorized"},{status:403});if(_.message==="Not Found")return H({error:"Report not found"},{status:404})}throw _}case"delete":try{return await r.deleteDailyReport(O,P,U,w),$(b,P,{})}catch(_){if(_ instanceof Error){if(_.message==="Unauthorized")return H({error:"Unauthorized"},{status:403});if(_.message==="Not Found")return H({error:"Report not found"},{status:404})}throw _}case"toggleStar":return await F(b,_=>r.setStarStatus(O,U,P,M,_,w));case"toggleRead":return await F(b,_=>r.setReadStatus(O,U,P,M,_,w));case"addComment":try{let _=await r.addComment(O,U,P,b.content,M,w);return $(b,P,{newComment:_})}catch(_){if(_ instanceof Error){if(_.message==="Not Found")return H({error:"Report not found"},{status:404});if(_.message.startsWith("Comments are restricted"))return H({error:"Comments are restricted for this report"},{status:403})}throw _}case"deleteComment":try{return await r.deleteComment(O,U,P,b.commentId,M,w),$(b,P,{deletedCommentId:b.commentId})}catch(_){if(_ instanceof Error){if(_.message==="Unauthorized")return H({error:"Unauthorized"},{status:403});if(_.message==="Not Found")return H({error:"Comment not found"},{status:404})}throw _}}},ye=async({request:b,params:U})=>{let{user:O,cookie:H}=await t(b,{failureRedirect:null}),$=(M,F)=>Ys(M,{...F,setCookie:H}),w=(M,F,_)=>Ys(Op(M,F,_),{setCookie:H});if(!O)return $({error:"Unauthorized"},{status:401});let P=ce();try{if(U.endpoint!==ue.action)return $({error:"Unknown endpoint"},{status:404});let M=te.spend(O.id,"action");if(M!==null)return $({error:M.message},{status:M.status,headers:M.headers});let F=await Ba(b,l);if("refusal"in F){let{refusal:K}=F;return K.status===413&&J(K.measuredBy),$({error:K.error},{status:K.status})}let{command:_}=F;if(_.intent==="clearCache"&&!e.enableDevCacheClear)return $({error:"Invalid intent"},{status:400});let j=await u(b,"initial");if(!j.ok)return $({error:Ir},{status:503,headers:{...Ee(503),"Cache-Control":"no-store"}});let ee=await r.getUserIdByExternalId(O.id);return ee?_.intent==="clearCache"?(await r.clearCache(),$({status:"OK",intent:"clearCache"})):await z(_,ee,j.scope,$,w):$({error:"User not found"},{status:404})}catch(M){if(M instanceof Response)throw M;let F=ce()-P,_=M instanceof Error?M:new Error(String(M));return c.error(`500 action elapsed=${F}ms name=${_.name} message=${_.message}`,_),$({error:"Internal Server Error"},{status:500})}},Re=qs({authenticate:t,service:r,resolveViewerScope:u,redis:o,sseReader:a,streamKey:i,streamSlots:g,logger:R}),X=$i({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:u,logger:p}),ve=Xa(m),Z=(b,U)=>async O=>{let H=Qa(O.request)?b.frameworkDataRefusal(O):null;if(H!==null)throw H;let $=(0,Ks.crossOriginRefusal)(O.request,b);return $===void 0?U(O):(ve(b.route,$,O.request),b.crossSiteRejection())};return{index:{loader:Y},api:{loader:Z(vp,V),action:Z(Np,ye)},sse:{loader:Z(Bs,Re)},attachment:{loader:Z(Ui,X)}}}var ar=require("@aiquants/mssql"),Te=require("drizzle-orm");var Gp=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],Kp=["document","comment"],Jp=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],Qp=["hubId","ordinal","authorUserId","commentText"],_o=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Zs=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw _n(e,n,r)},el=(e,t,r)=>{if(typeof t!="object"||t===null)throw Q(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw Q(`${e}.${o}`,"a column",n[o])},tl=(e,t)=>{if(!_o(e))throw Q("search","a plain object",e);Zs("search key",e,Gp);let{tables:r}=e;if(!_o(r))throw Q("search.tables","a plain object with document and comment",r);Zs("search.tables key",r,Kp),el("search.tables.document",r.document,Jp),el("search.tables.comment",r.comment,Qp);let n=new Map;if(e.externalSourceTexts!==void 0){if(!_o(e.externalSourceTexts))throw Q("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw _n("search.externalSourceTexts key",o,t);if(typeof a!="function")throw Q(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:le("search.concurrency",e.concurrency,1),rateLimitPerMinute:le("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var Pt=e=>{let t=typeof e=="object"&&e!==null?e.recordset:void 0;if(!Array.isArray(t))throw new Error("[daily-report] search: the database result has no recordset");return t},Vt=(e,t)=>{let r=typeof e=="string"?Xe(e):typeof e=="number"&&it(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},qt=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};var q=require("drizzle-orm");var At=require("drizzle-orm"),rl=e=>{if(e.length===0)throw new Error("[daily-report] draft rule: draftLabelNames must hold at least one name (a rule without names would show every draft to every viewer)");return At.sql.join(e.map(t=>At.sql`${t}`),At.sql`, `)},mn=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return At.sql`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${rl(t)}))`},nl=(e,t)=>{let{hubLabel:r,label:n}=e;return At.sql`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${rl(t)}))`},yn=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?At.sql`${o.userId} = ${t} OR ${o.userId} IS NULL`:At.sql`${o.userId} = ${t}`;return At.sql`(${a} OR NOT ${mn(e,r)})`};var Xp=/[[%_]/gu,Zp=e=>e.replace(Xp,t=>`[${t}]`),ol=e=>`%${Zp(e)}%`;var tt=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),Yt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),xr=Object.freeze({value:"value"}),Me=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),W=e=>q.sql`${q.sql.identifier(e.name)}`,_r=e=>q.sql.join(e.map(t=>q.sql`${t}`),q.sql`, `),al=(e,t)=>q.sql`SELECT ${W(e.id)} AS ${q.sql.identifier(Me.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${_r(t)}) ORDER BY ${e.id}`,em=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>ol(u.text)),l=q.sql.join(i.map(u=>q.sql`${o.searchText} LIKE ${u}`),q.sql` OR `),s=q.sql.join(i.map(u=>q.sql`${a.commentText} LIKE ${u}`),q.sql` OR `),c=Tr(n.sourceType,r.scope.commentable),d=c===void 0?q.sql``:q.sql` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return q.sql`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},il=(e,t,r)=>q.sql`(${q.sql.join(t.words.map(n=>em(e,n,r)),q.sql` AND `)})`,xo=(e,t,r,n)=>{let{hub:o}=e,a=[q.sql`${o.deletedAt} IS NULL`,yn(e,t.userId,r,"author")],i=Tr(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(q.sql`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},tm=(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(q.sql`LOWER(${r.sourceType}) IN (${_r([...t.sourceTypes])})`)}return t.authors!==null&&o.push(q.sql`${n.authorName} IN (${_r(t.authors)})`),t.customers!==null&&o.push(q.sql`${n.customerName} IN (${_r(t.customers)})`),o},sl=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...xo(e,r,n,o),...tm(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?q.sql` AND `:q.sql` OR `;s.push(q.sql`(${q.sql.join(l.sets.map(d=>il(e,d,r)),c)})`)}return q.sql`SELECT ${W(a.id)} AS ${q.sql.identifier(tt.reportHubId)}, CONVERT(char(10), ${W(a.businessDate)}, 23) AS ${q.sql.identifier(tt.businessDate)}, ${W(a.sourceType)} AS ${q.sql.identifier(tt.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${q.sql.join(s,q.sql` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},ll=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=q.sql.join(t.sets.map((s,c)=>q.sql`(CASE WHEN ${il(e,s,r)} THEN ${2**c} ELSE 0 END)`),q.sql` + `);return q.sql`SELECT ${W(a.id)} AS ${q.sql.identifier(Yt.reportHubId)}, ${l} AS ${q.sql.identifier(Yt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${q.sql.join(xo(e,r,n,o),q.sql` AND `)}`},cl=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...xo(e,r,n),q.sql`${i} IS NOT NULL`];return q.sql`SELECT ${i} AS ${q.sql.identifier(xr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${q.sql.join(l,q.sql` AND `)} GROUP BY ${i} ORDER BY ${i}`},ul=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(s=>({[n.hubId.name]:s.hubId,[n.searchText.name]:s.searchText,[n.sourceDigest.name]:s.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:s.authorName,[n.customerName.name]:s.customerName}))),i=JSON.stringify(t.flatMap(s=>s.comments.map(c=>({[o.hubId.name]:s.hubId,[o.ordinal.name]:c.ordinal,[o.authorUserId.name]:c.authorUserId,[o.commentText.name]:c.commentText})))),l=JSON.stringify(t.map(s=>s.hubId));return q.sql`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${W(n.hubId)} bigint, ${W(n.searchText)} nvarchar(max), ${W(n.sourceDigest)} char(64), ${W(n.normalizerVersion)} varchar(64), ${W(n.authorName)} nvarchar(max), ${W(n.customerName)} nvarchar(max))) AS s ON t.${W(n.hubId)} = s.${W(n.hubId)}
|
|
8
|
+
WHEN MATCHED THEN UPDATE SET t.${W(n.searchText)} = s.${W(n.searchText)}, t.${W(n.sourceDigest)} = CONVERT(binary(32), s.${W(n.sourceDigest)}, 2), t.${W(n.normalizerVersion)} = s.${W(n.normalizerVersion)}, t.${W(n.authorName)} = s.${W(n.authorName)}, t.${W(n.customerName)} = s.${W(n.customerName)}, t.${W(n.indexedAt)} = SYSUTCDATETIME()
|
|
9
|
+
WHEN NOT MATCHED THEN INSERT (${W(n.hubId)}, ${W(n.searchText)}, ${W(n.sourceDigest)}, ${W(n.normalizerVersion)}, ${W(n.authorName)}, ${W(n.customerName)}) VALUES (s.${W(n.hubId)}, s.${W(n.searchText)}, CONVERT(binary(32), s.${W(n.sourceDigest)}, 2), s.${W(n.normalizerVersion)}, s.${W(n.authorName)}, s.${W(n.customerName)});
|
|
10
10
|
DELETE FROM ${o} WHERE ${o.hubId} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${l}));
|
|
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));`},Qs=(e,t)=>B.sql`SELECT ${Y(e.hubId)} AS ${B.sql.identifier(_e.hubId)}, LOWER(CONVERT(char(64), ${Y(e.sourceDigest)}, 2)) AS ${B.sql.identifier(_e.sourceDigest)}, ${Y(e.normalizerVersion)} AS ${B.sql.identifier(_e.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${fr(t)})`,Xs=(e,t,r)=>B.sql`SELECT TOP (${r}) ${Y(e.id)} AS ${B.sql.identifier(_e.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var Zs=e=>({search:async(t,r)=>Pe(r.scope.visible)?[]:gt(await t.execute(zs(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Lt(o[Ke.sourceType],Ke.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${Ke.sourceType} is null`);return{reportHubId:Pt(o[Ke.reportHubId],Ke.reportHubId),businessDate:Lt(o[Ke.businessDate],Ke.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Pe(r.scope.visible))return new Map;let n=gt(await t.execute(Gs(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[kt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${kt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(Pt(i[kt.reportHubId],kt.reportHubId),l)}return a},facetValues:async(t,r)=>Pe(r.scope.visible)?[]:gt(await t.execute(Ks(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Lt(o[Rr.value],Rr.value);if(a===null)throw new Error(`[daily-report] search: column ${Rr.value} is null`);return a})});var nt=require("@aiquants/mssql"),bo=require("drizzle-orm");var tl=require("crypto");var zp=Object.freeze({authorName:"author",customerName:"customer"}),So=e=>e===null?null:On(e),el=(e,t,r)=>{let n=So(r);if(n!==null&&n.length>st.maxValueLength){let o=st.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${zp[t]} display value has ${n.length} UTF-16 units after trimming; the host must keep the author and customer display values at most ${o} UTF-16 units`)}return n},Sr=e=>e===null?"n;":`s${e.length}:${e}`,gr="utf16le",Gp=e=>{let t=(0,tl.createHash)("sha256");t.update(`F${e.fields.length};`,gr);for(let[r,n]of e.fields)t.update(Sr(r)+Sr(n),gr);return t.update(`C${e.comments.length};`,gr),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${Sr(r.text)}`,gr)}),t.update(`P;${Sr(So(e.filterValues.authorName))}${Sr(So(e.filterValues.customerName))}`,gr),t.digest("hex")},go=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=Kr(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=Kr(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:ns(r),comments:n,sourceDigest:Gp(e),forcedCuts:t,authorName:el(e.hubId,"authorName",e.filterValues.authorName),customerName:el(e.hubId,"customerName",e.filterValues.customerName)}};var rl=e=>{let t=async(s,c)=>{let d=[];for(let u of(0,nt.chunk)(c,nt.MAX_IN_LIST))for(let R of gt(await s.execute(js(e.hub,u))))d.push(Pt(R[_e.hubId],_e.hubId));return d},r=async(s,c)=>{for(let d of(0,nt.chunk)(c,nt.MAX_IN_LIST))await s.execute(Js(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of(0,nt.chunk)(c,nt.MAX_IN_LIST))for(let R of gt(await s.execute(Qs(e.tables.document,u))))d.set(Pt(R[_e.hubId],_e.hubId),{sourceDigest:Lt(R[_e.sourceDigest],_e.sourceDigest),normalizerVersion:Lt(R[_e.normalizerVersion],_e.normalizerVersion)});return d},o=async(s,c,d)=>gt(await s.execute(Xs(e.hub,c,d))).map(u=>Pt(u[_e.hubId],_e.hubId)),a=async(s,c)=>{let d=await t(s,[...new Set(c)].sort((R,p)=>R-p));if(d.length===0)return;let u=(await e.loadSources(s,d)).map(go);u.length>0&&await r(s,u)},i=s=>e.inTransaction(async c=>{await c.execute(bo.sql`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),R=(await e.loadSources(c,d)).map(go),p=R.filter(m=>{let h=u.get(m.hubId);return h===void 0||h.sourceDigest!==m.sourceDigest||h.normalizerVersion!==e.normalizerVersion});return p.length>0&&await r(c,p),await c.execute(bo.sql`SET DEADLOCK_PRIORITY NORMAL`),{scanned:R.length,written:p.length,forcedCuts:R.reduce((m,h)=>m+h.forcedCuts,0)}});return{writeHubs:a,reconcile:async(s,c)=>{let{batchSize:d,hubIds:u,signal:R,onProgress:p}=c;se("reconcileSearchIndex: batchSize",d,1,nt.MAX_IN_LIST);let m=le(),h=u===void 0?null:(0,nt.chunk)([...new Set(u)].sort((S,T)=>S-T),d),y={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let S=0;;S++){R?.throwIfAborted();let T=h===null?await o(s,y.lastHubId===null?0:y.lastHubId,d):h[S];if(T===void 0||T.length===0)break;let D=await i(T);y={scanned:y.scanned+D.scanned,written:y.written+D.written,skipped:y.skipped+D.scanned-D.written,forcedCuts:y.forcedCuts+D.forcedCuts,lastHubId:T[T.length-1]},p?.(y)}return{...y,elapsedMs:le()-m}}}};var al=require("@aiquants/fuzzy-search/normalize");var Do=255,rn=Object.values(xt).sort((e,t)=>e-t),Kp=new Intl.Segmenter("und",{granularity:"grapheme"}),fe=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),ot=5e5,nn=Math.floor(ot/fe.linear),Jp=Math.floor(ot/fe.segment),nl=Math.floor(ot/fe.sweep),il=Math.floor(ot/fe.scan),Eo=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),sl=(e,t)=>{let r=0,n=t(),o=ot,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+ot,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=ot,a=!1}}},oS=Object.freeze({fits:()=>!0,charge:()=>{}}),ll=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 Qp=(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},Xp=(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*Zp(e,t,r,n){let o=!1;for(let c=t;c<r&&!o;c+=nn){let d=Math.min(r,c+nn),u=(d-c)*fe.linear;n.fits(u)||(yield),o=(0,al.holdsMultiUnitCluster)(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=Kp.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(Jp,s.value.segment.length);n.fits(c*fe.segment)||(yield);let d=0;for(;!s.done&&d+s.value.segment.length<=c;){let{index:u,segment:R}=s.value;a.fill(t+u,u,u+R.length),i.fill(t+u+R.length,u,u+R.length),d+=R.length,s=l.next()}n.charge(d*fe.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var em=256,tm=e=>{let t=new Int32Array(e.length),r=0;for(let n=1;n<e.length;n++){for(;r>0&&e.charCodeAt(n)!==e.charCodeAt(r);)r=t[r-1];e.charCodeAt(n)===e.charCodeAt(r)&&r++,t[n]=r}return e.length-t[e.length-1]},rm=e=>{let t=new Map;for(let r of e){if(r.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let n=t.get(r.text);(n===void 0||r.tier<n)&&t.set(r.text,r.tier)}return[...t].map(([r,n])=>{let o=tm(r),a=Math.max(il-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(em/o))},windowStarts:a}})},on=(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)},ol=(e,t,r)=>{let n=on(e,t);return e.pieces[n>=0?n:on(e,r==="start"?t-1:t+1)]},cl=(e,t)=>{let r=on(e,t);if(r<0)return ul(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},ul=(e,t)=>{let r=on(e,t);if(r<0)return cl(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},nm=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),om=Object.freeze({kind:"done"}),Ao=Object.freeze({kind:"slice"}),am=Object.freeze({kind:"clusters"}),im=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:s,periodic:c}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(fe.run))return Ao;let p=ol(e,n.closedStart,"start"),m=ol(e,n.closedEnd-1,"end");if(p.mapped===null)return{kind:"map",piece:p};if(m.mapped===null)return{kind:"map",piece:m};if(e.isCut&&e.clusters===void 0)return am;let h=t(e.offset+cl(e,n.closedStart)),y=t(e.offset+ul(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let S=e.clusters;S==null?a(h,y,s):a(S.clusterStarts[h-S.start],S.clusterEnds[y-1-S.start],s),o.charge(fe.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(ot))return Ao;let{period:p,continuation:m}=c,h=n.periodicEnd,y=Math.min(i.length,h+Math.max(il,m.length)),S=h;for(;S+m.length<=y&&i.startsWith(m,S);)S+=m.length;let T=S+m.length>y&&y<i.length;if(!T)for(;S<i.length&&i.charCodeAt(S)===i.charCodeAt(S-p);)S++;if(o.charge((S-h)*fe.scan),T){n.periodicEnd=S;continue}n.periodicEnd=-1,n.last+=Math.floor((S-n.last-l.length)/p)*p,n.from=n.last+l.length-p+1;continue}if(n.from<0){if(n.runStart<0)return om;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(ot))return Ao;n.from>=n.windowEnd&&(n.windowStart=n.from,n.windowEnd=n.from+r.windowStarts,n.window=i.slice(n.from,n.windowEnd+l.length-1));let d=n.from-n.windowStart,u=n.window.indexOf(l,d);if(u<0){o.charge((n.window.length-d)*fe.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*fe.scan);let R=n.windowStart+u;(n.runStart<0||R>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=R),n.last=R,c===null?n.from=R+1:n.periodicEnd=R+l.length}};function*To(e,t,r){let n=Math.floor(ot/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*sm(e,t,r,n,o){if(t.length===0)return;let a=yield*To(os(e),fe.strip,n),i=[],l=[];yield*To(as(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),fe.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(fe.line)||(yield),n.charge(fe.line);let d=i[c],u=a.text.slice(d,l[c]),R=yield*To(is(u,r),fe.plan,n),p=[],m="";for(let y of R.chunks){let S="",T=[];for(let D of y){let f=(D.end-D.start)*fe.normalize;n.fits(f)||(yield);let b=so(D.start===0&&D.end===u.length?u:u.slice(D.start,D.end),r).text;n.charge(f),b.length>0&&T.push({start:D.start,end:D.end,text:b,chunkStart:S.length}),S+=b}if(S.length!==0){m.length>0&&(m+=" ");for(let D of T)p.push({start:D.start,end:D.end,text:D.text,plainStart:m.length+D.chunkStart,mapped:null});m+=S}}if(m.length===0)continue;let h={offset:d,plain:m,pieces:p,isCut:!Xp(R,u),lastPiece:0,clusters:void 0};for(let y of t){let S=nm();for(;;){let T=im(h,s,y,S,n,o);if(T.kind==="done")break;if(T.kind==="slice"){yield;continue}if(T.kind==="clusters"){h.clusters=yield*Zp(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:D}=T,f=(D.end-D.start)*fe.map;n.fits(f)||(yield);let b=u.slice(D.start,D.end);D.mapped=Qp(rs(b,io(b,r)),D.text),n.charge(f)}}}}function*lm(e,t,r,n){let o=new Int32Array(rn.length),a=0,i=Do;for(let l=0;l<=e;l+=nl){let s=Math.min(e+1,l+nl),c=(s-l)*fe.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=Do;for(let R=rn.length-1;R>=0;R--){let p=rn[R];o[p]+=t[p][d],o[p]>0&&(u=p)}if(u!==i){if(i!==Do&&!n(a,d,i))return!1;a=d,i=u}}r.charge(c)}return!0}function*cm(e,t,r,n,o){let a=null;return yield*sm(e,t,r,n,(l,s,c)=>{a===null&&(a=rn.map(()=>new Int32Array(e.length+1))),a[c][l]++,a[c][s]--}),a===null?!0:yield*lm(e.length,a,n,o)}var um=(e,t,r,n)=>{let o=rm(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return ll(function*(){return(yield*cm(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var dl=(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)},pl=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of pa)r(it.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(it.interviewer(o,"name"),n.name),r(it.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(it.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(it.comment(Cn(o),"author"),n.name),r(it.comment(Cn(o),"content"),n.text)});for(let n of e.postedComments)r(it.comment(n.id,"author"),n.userName),r(it.comment(n.id,"content"),n.content);return t};function*dm(e,t){let r=Ln;for(let n=0;n<e.length;n+=nn){let o=Math.min(e.length,n+nn),a=(o-n)*fe.linear;t.fits(a)||(yield),r=kn(r,e,n,o),t.charge(a)}return r}var ml=async(e,t,r,n)=>{let o=0,a=0,i=async c=>{for(;!c.step();)await r(),n.startSlice();return c.result()},l=async(c,d)=>{if(!d&&a>t.maxRanges)return null;let u={};for(let{key:R,value:p}of c.fields){if(!d&&o+p.length>t.maxUnits)return null;let m=await i(ll(dm(p,n))),h=await i(um(p,c.alternatives,{maxLength:no,maxRanges:t.maxFieldRanges},n));if(o+=p.length,h.dense){u[R]={fingerprint:m,dense:!0};continue}if(u[R]={fingerprint:m,ranges:h.ranges},a+=h.ranges.length/3,!d&&a>t.maxRanges)return null}return u},s=[];for(let c=0;c<e.length;c++){let d=e[c],u=await l(d,s.length===0);if(u===null)return{reports:s,deferred:e.slice(c).map(R=>R.reportHubId)};s.push({reportHubId:d.reportHubId,matchedSets:d.matchedSets,fields:u})}return{reports:s,deferred:[]}};var ke=require("drizzle-orm");var Le=require("drizzle-orm");var yt=e=>(0,Le.getColumns)(e),Ee=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},yl=e=>{let{db:t,tables:r,encodeUserId:n,settings:o,draftVisibilityTables:a}=e,{hub:i,label:l}=r,{externalSources:s,draftLabelNames:c,canonicalDraftLabelName:d}=o,u=v=>pr(i.sourceType,v),R=(v,O)=>tn(a,v,c,O),p=Le.sql`CASE WHEN ${en(a,c)} THEN 1 ELSE 0 END`,m=async v=>{let[O]=await t.select({id:i.id}).top(1).from(i).where((0,Le.and)((0,Le.eq)(i.id,v),en(a,c)));return O!==void 0},h=v=>v==null||v===""?null:/^\d+$/.test(v)?n(Number(v)):v,y=()=>{let v={};for(let O of s)v[`ext_${O.sourceType}`]=yt(O.table);return v},S=v=>{let O=v;for(let k of s)O=O.leftJoin(k.table,(0,Le.and)((0,Le.eq)(i.sourceType,k.sourceType),(0,Le.eq)(i.sourceIdNum,k.idColumn)));return O},T=v=>{let{hub:O,internal:k}=v,H=O.summary,E=[],x=null,$=null,K=null,ee=null,J=null,ye=null,Se=[],te=s.find(F=>F.sourceType===O.sourceType),Ue=te?v[`ext_${te.sourceType}`]:void 0;if(te&&Ue){let F=te.mapRow(Ue);F.content!==void 0&&(H=F.content),F.employeeName!==void 0&&(ye=F.employeeName),F.category!==void 0&&(x=F.category),F.creationCategory!==void 0&&($=F.creationCategory),F.visitTimeFrom!==void 0&&(K=F.visitTimeFrom),F.visitTimeTo!==void 0&&(ee=F.visitTimeTo),F.customerName!==void 0&&(J=F.customerName),F.interviewers!==void 0&&(E=F.interviewers),F.externalComments!==void 0&&(Se=F.externalComments)}else O.sourceType===Ge&&k&&(H=k.body);return{content:H,author:v.creatorName??h(O.createdBy)??"",employeeName:ye??v.creatorName??h(O.createdBy),updatedBy:h(O.updatedBy),category:x,creationCategory:$,visitTimeFrom:K,visitTimeTo:ee,customerName:J,interviewers:E,externalComments:Se}},D=v=>{if(v===1)return!0;if(v===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${Et(v)}`)},f=v=>v.creationCategory!==null&&c.includes(v.creationCategory),b=(v,O)=>D(v.hasDraftLabel)?!0:f(O),M=async v=>{let[O]=await v.select({id:l.id}).top(1).from(l).where((0,Le.eq)(l.name,d)).orderBy((0,Le.asc)(l.id));return O===void 0?null:O.id},I=()=>M(t);return{visibleSourceTypeCondition:u,draftVisibleTo:R,draftLabelFlag:p,isDraftReport:m,externalSelections:y,applyExternalJoins:S,resolveHubDisplayFields:T,readCanonicalDraftLabelId:M,getDraftLabelId:I,resolveCreationCategoryDraftLabelId:v=>v.some(f)?I():Promise.resolve(null),mapHubRecord:(v,O,k,H,E)=>{let{hub:x}=O,$=O.labels.map(J=>({id:J.id,name:J.name,color:J.color})),K=O.postedCommentRows,ee=Te(v.commentable,x.sourceType);return H!==null&&f(k)&&!$.some(J=>J.id===H)&&$.push({id:H,name:d,color:null}),{reportHubId:x.id,date:Ee(x.businessDate,"YYYY-MM-DD"),author:k.author,userId:x.userId?n(x.userId):"",sourceType:x.sourceType,createdAt:Ee(x.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:Ee(x.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:k.updatedBy,employeeName:k.employeeName,category:k.category,creationCategory:k.creationCategory,visitTimeFrom:k.visitTimeFrom,visitTimeTo:k.visitTimeTo,customerName:k.customerName,interviewers:k.interviewers,subject:x.title,content:k.content,externalComments:ee?k.externalComments:[],isRead:O.isRead??!1,isStarred:O.isStarred??!1,isDraft:b(O,k),labels:$,postedComments:K.filter(J=>Wi({authorUserId:J.userId},x.sourceType,E,v)).map(J=>({...J,userId:n(J.userId),isMine:E?J.userId===E:!1})),attachments:O.attachments}}}};var hl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r})=>{let{db:n,tables:o,logger:a,settings:i}=e,{hub:l}=o,{attachmentDelivery:s}=i,c=(m,h)=>h!=null?"absent":m!=null?"present":"unknown";return{getAttachmentsByHubIds:async m=>{let h=new Map,y=o.attachment;if(m.length===0||!y||s===null)return h;let S=s.idCodec,T=s.thumbnails!==null,D=await n.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where((0,ke.inArray)(y.hubId,m)).orderBy((0,ke.asc)(y.createdAt),(0,ke.asc)(y.id));for(let f of D){let b=f.fileType?String(f.fileType):null,M=f.fileSize!=null?Number(f.fileSize):null,I=c(f.objectCheckedAt,f.objectMissingAt),_={id:S.encode(Number(f.id)),fileName:String(f.fileName),fileType:b,fileSize:M,createdAt:Ee(f.createdAt,"YYYY-MM-DD HH:mm:ss"),state:I,hasThumbnail:T&&I!=="absent"&&Ur({fileType:b,fileSize:M},s.maxBytes)},V=h.get(Number(f.hubId));V?V.push(_):h.set(Number(f.hubId),[_])}return h},getAttachmentForUser:async(m,h,y)=>{let S=o.attachment;return!S||Pe(m.visible)?null:(await n.select({fileName:S.fileName,filePath:S.filePath,fileType:S.fileType,fileSize:S.fileSize}).top(1).from(S).innerJoin(l,(0,ke.eq)(l.id,S.hubId)).where((0,ke.and)((0,ke.eq)(S.id,h),(0,ke.isNull)(l.deletedAt),t(y,"author"),r(m.visible))))[0]??null},markAttachmentMissing:async m=>{let h=o.attachment;if(!h)return;let y=new Date;try{await n.update(h).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where((0,ke.eq)(h.id,m))}catch(S){a.error("markAttachmentMissing failed",S)}},markAttachmentPresent:async m=>{let h=o.attachment;if(!h)return;let y=new Date;try{await n.update(h).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where((0,ke.eq)(h.id,m))}catch(S){a.error("markAttachmentPresent failed",S)}}}};var an=require("drizzle-orm");var Nt=require("drizzle-orm"),Gt=async(e,t,r,n)=>{if((await e.update(t).set({deletedAt:null}).output().where((0,Nt.and)((0,Nt.eq)(t.id,r),(0,Nt.isNull)(t.deletedAt),n===null?void 0:(0,Nt.eq)(t.userId,n)))).length===0)throw new Error("Not Found")};var bt="daily-report:ids:epoch",Oe="daily-report:date-epoch:",at="daily-report:detail-epoch:",fl=({redis:e,logger:t,epochs:r,streamKey:n,streamMaxLen:o})=>({incrementRedisEpoch:s=>r.incrementEpoch(s),publishToSseStream:async(s,c)=>{let d=await e?.getClient();if(!d){t.warn(`[SSE] Redis client unavailable (${c})`);return}let u=JSON.stringify(s),R=Buffer.byteLength(u);if(R>6356992){t.warn(`[SSE] Event too large (${c}): ${R} bytes > ${6356992}; not published`);return}let p=le();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let m=le()-p;m>1e3&&t.warn(`[SSE] Slow publish (${c}): ${m}ms`)}catch(m){t.error(`[SSE] Redis publish failed (${c}):`,m)}},readSseStreamAnchor:async()=>{try{let s=await e?.getClient();if(s===void 0)return null;let[c]=await s.xRevRange(n,"+","-",{COUNT:1});return c===void 0?null:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});var Rl=(e,{isDraftReport:t,assertHubMutable:r,incrementRedisEpoch:n})=>{let{db:o,tables:a,users:i,encodeUserId:l,cache:s,inTransaction:c,prepareSearchIndex:d,publishToSseStream:u}=e,{hub:R,comment:p}=a,m=async(T,D)=>{if(D!==null)return await t(T)?D:void 0},h=async(T,D,f,b,M,I)=>{let _=await r(T,f,D);if(!Te(T.commentable,_.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(_.sourceType.toLowerCase()!==Ge.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let V=await m(f,_.userId),v=await d(),O=await c(async x=>{await Gt(x,R,f,null);let[$]=await x.insert(p).output().values({hubId:f,userId:D,body:b,createdAt:new Date,createdBy:String(D),updatedAt:new Date,updatedBy:String(D)});return v!==null&&await v.writeHubs(x,[f]),$}),[k]=await o.select({displayName:i.displayName}).top(1).from(i).where((0,an.eq)(i.id,D)),H=k?.displayName??"";if(M){let x=Ne(M);x&&(s.invalidatePrefix(jt(x)),await n(`${Oe}${x}`))}s.invalidatePrefix(Ve(f)),await n(`${at}${f}`);let E={id:O.id,userId:l(O.userId),userName:H,content:O.body,createdAt:Ee(O.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(Dn.parse({type:"comment-add",reportHubId:f,comment:E,clientTempId:I,recipientRawUserId:V,sourceType:_.sourceType}),"addComment"),E},y=async(T,D)=>await T.select().top(1).from(p).where((0,an.eq)(p.id,D));return{addComment:h,deleteComment:async(T,D,f,b,M,I)=>{let _=await y(o,b);if(_.length===0)throw new Error("Not Found");if(_[0].hubId!==f)throw new Error("Not Found");let V=await r(T,_[0].hubId,D);if(_[0].userId!==D)throw new Error("Unauthorized");let v=await m(f,V.userId),O=await d();if(await c(async k=>{await Gt(k,R,f,null),await k.delete(p).where((0,an.eq)(p.id,b)),O!==null&&await O.writeHubs(k,[f])}),M){let k=Ne(M);k&&(s.invalidatePrefix(jt(k)),await n(`${Oe}${k}`))}s.invalidatePrefix(Ve(f)),await n(`${at}${f}`),await u(An.parse({type:"comment-delete",reportHubId:f,commentId:b,clientTempId:I,recipientRawUserId:v,sourceType:V.sourceType}),"deleteComment")}}};var Fe=require("drizzle-orm");var Sl=e=>e===""?null:e,gl=(e,{readCanonicalDraftLabelId:t,isDraftReport:r,getDailyReportDetailById:n,assertHubMutable:o,incrementRedisEpoch:a})=>{let{db:i,tables:l,cache:s,logger:c,inTransaction:d,prepareSearchIndex:u,publishToSseStream:R,settings:p,draftVisibilityTables:m}=e,{hub:h,internal:y,hubLabel:S,userStatus:T}=l,{canonicalDraftLabelName:D,draftLabelNames:f}=p,b=async(H,E,x,$)=>{if(!Tr(x))throw Q("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",x);if(!Te(H.visible,Ge))throw new Error("Forbidden");c.info("createDailyReport called",{userId:E,businessDate:x});let K=await u();try{let ee=await d(async te=>{c.info("Starting transaction");let Ue=await t(te);if(Ue===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(D)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let F=`internal-temp-${Date.now()}-${Math.random()}`,[g]=await te.insert(h).output().values({sourceType:Ge,sourceId:F,businessDate:new Date(`${x}T00:00:00Z`),userId:E,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(E),updatedAt:new Date,updatedBy:String(E)});return await te.update(h).set({sourceId:String(g.id)}).where((0,Fe.eq)(h.id,g.id)),c.info("Hub created",g),await te.insert(y).values({hubId:g.id,body:"",createdAt:new Date,createdBy:String(E),updatedAt:new Date,updatedBy:String(E)}),c.info("Internal created"),await te.insert(S).values({hubId:g.id,labelId:Ue,createdAt:new Date,createdBy:String(E)}),c.info("Label assigned"),await te.insert(T).values({hubId:g.id,userId:E,isRead:!0,isStarred:!1,createdAt:new Date,createdBy:String(E),updatedAt:new Date,updatedBy:String(E)}),K!==null&&await K.writeHubs(te,[g.id]),g.id});s.invalidatePrefix(Wt(x,E)),s.invalidatePrefix(mo(E)),await a(bt),await a(`${Oe}${x}`);let J=await n(Be.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),ee,E,{forceRefresh:!0});if(J===null)throw new Error(`[daily-report] createDailyReport: report ${ee} was committed but its detail read returned nothing`);let ye=await r(J.reportHubId);await R(wn.parse({type:"report-create",reportHubId:J.reportHubId,report:J,clientTempId:$,recipientRawUserId:ye?E:void 0,actorRawUserId:E}),"createDailyReport");let Se=await n(H,ee,E,{forceRefresh:!0});if(Se===null)throw new Error(`[daily-report] createDailyReport: the actor's scope cannot read report ${ee} it just created`);return Se}catch(ee){throw c.error("Error in createDailyReport",ee),ee}},M=async(H,E)=>await H.select().top(1).from(h).where((0,Fe.eq)(h.id,E)),I=async(H,E,x)=>{await o(H,E,x);let[$]=await M(i,E);if($===void 0||$.deletedAt)throw new Error("Not Found");if($.userId!==x)throw new Error("Unauthorized");return $},_=async(H,E,x)=>{await H.update(h).set(x).where((0,Fe.eq)(h.id,E))},V=async(H,E,x)=>{await H.update(y).set(x).where((0,Fe.eq)(y.hubId,E))};return{createDailyReport:b,updateDailyReport:async(H,E,x,$,K)=>{let ee=await I(H,E,x),J=await u();await d(async te=>{await Gt(te,h,E,x),$.title!==void 0&&await _(te,E,{title:Sl($.title),updatedAt:new Date,updatedBy:String(x)}),$.content!==void 0&&await V(te,E,{body:Sl($.content),updatedAt:new Date,updatedBy:String(x)}),J!==null&&await J.writeHubs(te,[E])}),s.invalidatePrefix(Ve(E)),await a(`${at}${E}`);let ye=Ne(Ee(ee.businessDate,"YYYY-MM-DD"));ye&&(s.invalidatePrefix(jt(ye)),await a(`${Oe}${ye}`));let Se=await n(Be.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),E,x,{forceRefresh:!0});if(Se){let te=await r(E);await R(In.parse({type:"report-update",reportHubId:Se.reportHubId,report:Se,clientTempId:K,recipientRawUserId:te?x:void 0,actorRawUserId:x}),"updateDailyReport")}},publishDailyReport:async(H,E,x,$)=>{let K=await I(H,E,x),ee=await u();if(await d(async te=>{await Gt(te,h,E,x),await te.delete(S).where((0,Fe.and)((0,Fe.eq)(S.hubId,E),qs(m,f))),ee!==null&&await ee.writeHubs(te,[E])}),s.invalidatePrefix(Ve(E)),s.invalidatePrefix(Rt),await a(bt),K.businessDate){let te=Ne(Ee(K.businessDate,"YYYY-MM-DD"));te&&await a(`${Oe}${te}`)}let J=Ne(Ee(K.businessDate,"YYYY-MM-DD"));J&&s.invalidatePrefix(Wt(J,x));let ye=await n(Be.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),E,x,{forceRefresh:!0});if(ye===null)return null;let Se=await r(E);return await R(_n.parse({type:"report-publish",reportHubId:ye.reportHubId,report:ye,clientTempId:$,recipientRawUserId:Se?x:void 0,actorRawUserId:x}),"publishDailyReport"),await n(H,E,x,{forceRefresh:!0})},deleteDailyReport:async(H,E,x,$)=>{let K=await I(H,E,x);if(await d(async ee=>{if((await ee.update(h).set({deletedAt:new Date,deletedBy:String(x),updatedAt:new Date,updatedBy:String(x)}).output().where((0,Fe.and)((0,Fe.eq)(h.id,E),(0,Fe.eq)(h.userId,x),(0,Fe.isNull)(h.deletedAt)))).length===0)throw new Error("Not Found")}),s.invalidatePrefix(Ve(E)),s.invalidatePrefix(Rt),await a(bt),K.businessDate){let ee=Ne(Ee(K.businessDate,"YYYY-MM-DD"));ee&&await a(`${Oe}${ee}`)}await R(Ir.parse({type:"report-delete",reportHubId:E,clientTempId:$,sourceType:K.sourceType}),"deleteDailyReport")}}};var z=require("drizzle-orm");var bl=xr([]),Dl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r,draftLabelFlag:n,externalSelections:o,applyExternalJoins:a,resolveHubDisplayFields:i,resolveCreationCategoryDraftLabelId:l,mapHubRecord:s,getAttachmentsByHubIds:c,readSseStreamAnchor:d,incrementRedisEpoch:u})=>{let{db:R,tables:p,users:m,resolveUserId:h,cache:y,epochs:S,logger:T,settings:D}=e,{hub:f,internal:b,comment:M,label:I,hubLabel:_,userStatus:V}=p,v=D.idsTtlMs,O=D.businessDateTtlMs,k=async(F,g)=>(await R.select({reportHubId:f.id,businessDate:f.businessDate,sourceType:f.sourceType}).from(f).where((0,z.and)((0,z.isNull)(f.deletedAt),t(g,"author-or-authorless"),r(F.visible))).orderBy((0,z.desc)(f.businessDate),(0,z.desc)(f.id))).map(w=>({...w,businessDate:Ee(w.businessDate,"YYYY-MM-DD")})),H=async(F,g,C)=>{let w=await x(g);return w?Pe(F.visible)?[]:(await R.select({reportHubId:f.id,businessDate:f.businessDate,sourceType:f.sourceType}).top(C).from(f).where((0,z.and)((0,z.isNull)(f.deletedAt),t(w,"author-or-authorless"),r(F.visible))).orderBy((0,z.desc)(f.businessDate),(0,z.desc)(f.id))).map(N=>({...N,businessDate:Ee(N.businessDate,"YYYY-MM-DD")})):[]},E=new Map,x=async F=>{if(!D.disableUserIdCache&&E.has(F))return E.get(F)??null;let g=await h(F);return g!==null&&!D.disableUserIdCache&&E.set(F,g),g},$=async(F,g,{forceRefresh:C=!1,snapshot:w=!1,ttlMsOverride:L,onFetchStart:N,admission:q}={})=>{let W=await x(g);if(!W)return{items:[],streamAnchor:null,snapshot:bl};if(Pe(F.visible))return{items:[],streamAnchor:await d(),snapshot:bl};let U=hs(W,jr(F)),[G]=await y.getOrFetch({cacheKey:U,fetcher:async()=>{let P=await d(),X=await k(F,W);if(!la(X)){T.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let j=[...X].sort(xn);return[{items:j,streamAnchor:P,snapshot:xr(j)}]}return[{items:X,streamAnchor:P,snapshot:xr(X)}]},onFetchStart:N,forceRefresh:C,snapshot:w,admission:q,ttlMsOverride:L??v,epochKey:bt,refreshAheadRatio:.5});if(G===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return G},K=async(F,g,C)=>{let w=await a(R.select({hub:yt(f),internal:yt(b),isRead:V.isRead,isStarred:V.isStarred,creatorName:m.displayName,hasDraftLabel:n,...o()}).from(f)).leftJoin(b,(0,z.eq)(f.id,b.hubId)).leftJoin(V,(0,z.and)((0,z.eq)(f.id,V.hubId),(0,z.eq)(V.userId,g))).leftJoin(m,(0,z.eq)(f.userId,m.id)).where((0,z.and)(C,(0,z.isNull)(f.deletedAt),t(g,"author"),r(F.visible))).orderBy((0,z.desc)(f.id));if(w.length===0)return[];let L=w.map(j=>j.hub.id),N=await R.select({hubId:_.hubId,id:I.id,name:I.name,color:I.color}).from(_).innerJoin(I,(0,z.eq)(_.labelId,I.id)).where((0,z.inArray)(_.hubId,L)),q=await R.select({hubId:M.hubId,id:M.id,body:M.body,createdAt:M.createdAt,userId:M.userId,userName:m.displayName}).from(M).leftJoin(m,(0,z.eq)(M.userId,m.id)).where((0,z.inArray)(M.hubId,L)).orderBy((0,z.asc)(M.createdAt)),W=await c(L),U=new Map,G=new Map;for(let j of N){let Z=U.get(j.hubId);Z||(Z=[],U.set(j.hubId,Z)),Z.push({id:j.id,name:j.name,color:j.color})}for(let j of q){let Z=G.get(j.hubId);Z||(Z=[],G.set(j.hubId,Z)),Z.push({id:j.id,content:j.body,createdAt:Ee(j.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:j.userId,userName:j.userName||""})}let P=w.map(i),X=await l(P);return w.map((j,Z)=>{let Dt=j.hub.id;return s(F,{...j,attachments:W.get(Dt)??[],labels:U.get(Dt)||[],postedCommentRows:G.get(Dt)||[]},P[Z],X,g)})},ee=async(F,g,C,{forceRefresh:w=!1,snapshot:L=!1,ttlMsOverride:N,admission:q}={})=>{let W=await x(C);if(!W)return[];let U=Ne(g);if(!U)return[];if(Pe(F.visible))return[];let G=fs(U,W,jr(F));return y.getOrFetch({cacheKey:G,fetcher:()=>K(F,W,(0,z.eq)(f.businessDate,z.sql`${U}`)),forceRefresh:w,snapshot:L,admission:q,ttlMsOverride:N??O,epochKey:`${Oe}${U}`})},J=async(F,g,C,{forceRefresh:w=!1,snapshot:L=!1,ttlMsOverride:N,admission:q}={})=>{if(Pe(F.visible))return null;let W=Rs(g,C,jr(F));return(await y.getOrFetch({cacheKey:W,fetcher:async()=>{let G=await a(R.select({hub:yt(f),internal:yt(b),isRead:V.isRead,isStarred:V.isStarred,creatorName:m.displayName,hasDraftLabel:n,...o()}).from(f)).leftJoin(b,(0,z.eq)(f.id,b.hubId)).leftJoin(V,(0,z.and)((0,z.eq)(f.id,V.hubId),(0,z.eq)(V.userId,C))).leftJoin(m,(0,z.eq)(f.userId,m.id)).where((0,z.and)((0,z.eq)(f.id,g),(0,z.isNull)(f.deletedAt),t(C,"author"),r(F.visible)));if(G.length===0)return[];let P=G[0].hub.id,X=await R.select({id:I.id,name:I.name,color:I.color}).from(_).innerJoin(I,(0,z.eq)(_.labelId,I.id)).where((0,z.eq)(_.hubId,P)),j=await R.select({id:M.id,body:M.body,createdAt:M.createdAt,userId:M.userId,userName:m.displayName}).from(M).leftJoin(m,(0,z.eq)(M.userId,m.id)).where((0,z.eq)(M.hubId,P)).orderBy((0,z.asc)(M.createdAt)),Z=await c([P]),Dt=X.map(qe=>({id:qe.id,name:qe.name,color:qe.color})),dn=j.map(qe=>({id:qe.id,content:qe.body,createdAt:Ee(qe.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:qe.userId,userName:qe.userName||""})),Jt=i(G[0]),pn=await l([Jt]);return[s(F,{...G[0],attachments:Z.get(P)??[],labels:Dt,postedCommentRows:dn},Jt,pn,C)]},forceRefresh:w,snapshot:L,admission:q,ttlMsOverride:N??O,epochKey:`${at}${g}`}))[0]??null};return{getUserIdByExternalId:x,getDailyReportIdsByExternalId:$,getDailyReportIdsFirstPageByExternalId:H,getDailyReportsByBusinessDateByExternalId:ee,getDailyReportDetailById:J,getDailyReportDetailByIdByExternalId:async(F,g,C,w={})=>{let L=await x(C);return L?J(F,g,L,w):null},getDailyReportDetailsByIdsByExternalId:async(F,g,C)=>{if(g.length>Ie.maxDetailIds)throw Q("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${Ie.maxDetailIds} ids`,g.length);let w=await x(C);return!w||g.length===0?[]:Pe(F.visible)?[]:K(F,w,(0,z.inArray)(f.id,[...g]))},fetchVisibleHubDetails:K,invalidateHubReadCaches:async(F,g)=>{y.invalidatePrefix(Rt),await u(bt);for(let C of new Set(F))y.invalidatePrefix(Ve(C)),await u(`${at}${C}`);for(let C of new Set(g)){let w=Ne(C);w&&await u(`${Oe}${w}`)}},clearCache:async()=>{y.clearAll(),E.clear(),S&&await u(bt),T.info("Server-side DB/SQL caches cleared successfully.")}}};var sn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,streamKey:"daily-report:sse-stream",streamMaxLen:1e4}),mm=e=>{let{length:t}=e;if(t===void 0)throw Q("tables.hub.title","a character column with a declared length",t);return se("tables.hub.title.length",t,1)},ym=e=>{if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0)||new Set(e).size!==e.length)throw Q("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},hm=e=>{let t=new Map([[Ge.toLowerCase(),`the internal source type ${JSON.stringify(Ge)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw Q(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([Ge,...e.map(r=>r.sourceType)])},Al=e=>{let t=e.externalSources??[],r=ym(e.draftLabelNames);Br(e);let n=Ii(e.attachments),o=mm(e.tables.hub.title);to(e.tables.hub.sourceType);let a=xe("idsTtlMs",e.idsTtlMs,1,sn.idsTtlMs),i=xe("businessDateTtlMs",e.businessDateTtlMs,1,sn.businessDateTtlMs),l=xe("streamMaxLen",e.streamMaxLen,1,sn.streamMaxLen);return Object.freeze({externalSources:t,sourceTypes:hm(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamKey:e.streamKey??sn.streamKey,streamMaxLen:l,disableUserIdCache:!!e.disableUserIdCache})};var pe=require("drizzle-orm");var ln=["hubId","userId","isRead","isStarred","createdAt","createdBy","updatedAt","updatedBy"],fm={isRead:{statusType:"read",callerName:"setReadStatus"},isStarred:{statusType:"star",callerName:"setStarStatus"}},He=e=>pe.sql`${pe.sql.identifier(e.name)}`,Rm=(e,t,{reportHubId:r,userId:n,value:o,at:a})=>{let i=String(n),l=He(e[t]),s=(p,m)=>pe.sql`t.${He(p)} = CASE WHEN t.${l} = ${o} THEN t.${He(p)} ELSE ${m} END`,c={hubId:pe.sql`s.${He(e.hubId)}`,userId:pe.sql`s.${He(e.userId)}`,isRead:pe.sql`${t==="isRead"?o:!1}`,isStarred:pe.sql`${t==="isStarred"?o:!1}`,createdAt:pe.sql`${a}`,createdBy:pe.sql`${i}`,updatedAt:pe.sql`${a}`,updatedBy:pe.sql`${i}`},d=pe.sql.join(ln.map(p=>He(e[p])),pe.sql`, `),u=pe.sql.join(ln.map(p=>c[p]),pe.sql`, `),R=pe.sql.join(ln.map(p=>pe.sql`inserted.${He(e[p])} AS ${pe.sql.identifier(p)}`),pe.sql`, `);return pe.sql`MERGE ${e} WITH (HOLDLOCK) AS t USING (SELECT ${r} AS ${He(e.hubId)}, ${n} AS ${He(e.userId)}) AS s ON t.${He(e.hubId)} = s.${He(e.hubId)} AND t.${He(e.userId)} = s.${He(e.userId)}
|
|
11
|
+
INSERT INTO ${o} (${W(o.hubId)}, ${W(o.ordinal)}, ${W(o.authorUserId)}, ${W(o.commentText)}) SELECT ${W(o.hubId)}, ${W(o.ordinal)}, ${W(o.authorUserId)}, ${W(o.commentText)} FROM OPENJSON(${i}) WITH (${W(o.hubId)} bigint, ${W(o.ordinal)} int, ${W(o.authorUserId)} bigint, ${W(o.commentText)} nvarchar(max));`},dl=(e,t)=>q.sql`SELECT ${W(e.hubId)} AS ${q.sql.identifier(Me.hubId)}, LOWER(CONVERT(char(64), ${W(e.sourceDigest)}, 2)) AS ${q.sql.identifier(Me.sourceDigest)}, ${W(e.normalizerVersion)} AS ${q.sql.identifier(Me.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${_r(t)})`,pl=(e,t,r)=>q.sql`SELECT TOP (${r}) ${W(e.id)} AS ${q.sql.identifier(Me.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var ml=e=>({search:async(t,r)=>Ne(r.scope.visible)?[]:Pt(await t.execute(sl(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=qt(o[tt.sourceType],tt.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${tt.sourceType} is null`);return{reportHubId:Vt(o[tt.reportHubId],tt.reportHubId),businessDate:qt(o[tt.businessDate],tt.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Ne(r.scope.visible))return new Map;let n=Pt(await t.execute(ll(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames,r.ids))),o=2**r.plan.sets.length-1,a=new Map;for(let i of n){let l=i[Yt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${Yt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(Vt(i[Yt.reportHubId],Yt.reportHubId),l)}return a},facetValues:async(t,r)=>Ne(r.scope.visible)?[]:Pt(await t.execute(cl(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=qt(o[xr.value],xr.value);if(a===null)throw new Error(`[daily-report] search: column ${xr.value} is null`);return a})});var pt=require("@aiquants/mssql"),Po=require("drizzle-orm");var hl=require("crypto");var rm=Object.freeze({authorName:"author",customerName:"customer"}),Co=e=>e===null?null:zn(e),yl=(e,t,r)=>{let n=Co(r);if(n!==null&&n.length>Rt.maxValueLength){let o=Rt.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${rm[t]} display value has ${n.length} UTF-16 units after trimming; the host must keep the author and customer display values at most ${o} UTF-16 units`)}return n},Cr=e=>e===null?"n;":`s${e.length}:${e}`,Mr="utf16le",nm=e=>{let t=(0,hl.createHash)("sha256");t.update(`F${e.fields.length};`,Mr);for(let[r,n]of e.fields)t.update(Cr(r)+Cr(n),Mr);return t.update(`C${e.comments.length};`,Mr),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${Cr(r.text)}`,Mr)}),t.update(`P;${Cr(Co(e.filterValues.authorName))}${Cr(Co(e.filterValues.customerName))}`,Mr),t.digest("hex")},Mo=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=ln(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=ln(o.text);t+=a.forcedCuts,a.text.length!==0&&n.push({ordinal:n.length,authorUserId:o.authorUserId,commentText:a.text})}return{hubId:e.hubId,searchText:Ss(r),comments:n,sourceDigest:nm(e),forcedCuts:t,authorName:yl(e.hubId,"authorName",e.filterValues.authorName),customerName:yl(e.hubId,"customerName",e.filterValues.customerName)}};var fl=e=>{let t=async(s,c)=>{let d=[];for(let u of(0,pt.chunk)(c,pt.MAX_IN_LIST))for(let R of Pt(await s.execute(al(e.hub,u))))d.push(Vt(R[Me.hubId],Me.hubId));return d},r=async(s,c)=>{for(let d of(0,pt.chunk)(c,pt.MAX_IN_LIST))await s.execute(ul(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of(0,pt.chunk)(c,pt.MAX_IN_LIST))for(let R of Pt(await s.execute(dl(e.tables.document,u))))d.set(Vt(R[Me.hubId],Me.hubId),{sourceDigest:qt(R[Me.sourceDigest],Me.sourceDigest),normalizerVersion:qt(R[Me.normalizerVersion],Me.normalizerVersion)});return d},o=async(s,c,d)=>Pt(await s.execute(pl(e.hub,c,d))).map(u=>Vt(u[Me.hubId],Me.hubId)),a=async(s,c)=>{let d=await t(s,[...new Set(c)].sort((R,p)=>R-p));if(d.length===0)return;let u=(await e.loadSources(s,d)).map(Mo);u.length>0&&await r(s,u)},i=s=>e.inTransaction(async c=>{await c.execute(Po.sql`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),R=(await e.loadSources(c,d)).map(Mo),p=R.filter(m=>{let h=u.get(m.hubId);return h===void 0||h.sourceDigest!==m.sourceDigest||h.normalizerVersion!==e.normalizerVersion});return p.length>0&&await r(c,p),await c.execute(Po.sql`SET DEADLOCK_PRIORITY NORMAL`),{scanned:R.length,written:p.length,forcedCuts:R.reduce((m,h)=>m+h.forcedCuts,0)}});return{writeHubs:a,reconcile:async(s,c)=>{let{batchSize:d,hubIds:u,signal:R,onProgress:p}=c;le("reconcileSearchIndex: batchSize",d,1,pt.MAX_IN_LIST);let m=ce(),h=u===void 0?null:(0,pt.chunk)([...new Set(u)].sort((S,T)=>S-T),d),y={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let S=0;;S++){R?.throwIfAborted();let T=h===null?await o(s,y.lastHubId===null?0:y.lastHubId,d):h[S];if(T===void 0||T.length===0)break;let D=await i(T);y={scanned:y.scanned+D.scanned,written:y.written+D.written,skipped:y.skipped+D.scanned-D.written,forcedCuts:y.forcedCuts+D.forcedCuts,lastHubId:T[T.length-1]},p?.(y)}return{...y,elapsedMs:ce()-m}}}};var gl=require("@aiquants/fuzzy-search/normalize");var ko=255,hn=Object.values(Ut).sort((e,t)=>e-t),om=new Intl.Segmenter("und",{granularity:"grapheme"}),ge=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),mt=5e5,fn=Math.floor(mt/ge.linear),am=Math.floor(mt/ge.segment),Rl=Math.floor(mt/ge.sweep),bl=Math.floor(mt/ge.scan),Pr=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),Dl=(e,t)=>{let r=0,n=t(),o=mt,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+mt,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=mt,a=!1}}},DS=Object.freeze({fits:()=>!0,charge:()=>{}}),Al=e=>{let t=null;return{step:()=>{if(t!==null)return!0;let r=e.next();return r.done!==!0?!1:(t={result:r.value},!0)},result:()=>{if(t===null)throw new Error("[daily-report] search marks: the walk is not done (step until it returns true)");return t.result}}};var im=(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},sm=(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*lm(e,t,r,n){let o=!1;for(let c=t;c<r&&!o;c+=fn){let d=Math.min(r,c+fn),u=(d-c)*ge.linear;n.fits(u)||(yield),o=(0,gl.holdsMultiUnitCluster)(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=om.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(am,s.value.segment.length);n.fits(c*ge.segment)||(yield);let d=0;for(;!s.done&&d+s.value.segment.length<=c;){let{index:u,segment:R}=s.value;a.fill(t+u,u,u+R.length),i.fill(t+u+R.length,u,u+R.length),d+=R.length,s=l.next()}n.charge(d*ge.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var cm=256,um=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]},dm=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=um(r),a=Math.max(bl-r.length+1,r.length);if(o===r.length)return{text:r,tier:n,periodic:null,windowStarts:a};let i=r.length%o,l=r.slice(i,o)+r.slice(0,i);return{text:r,tier:n,periodic:{period:o,continuation:l.repeat(Math.ceil(cm/o))},windowStarts:a}})},Rn=(e,t)=>{let{pieces:r}=e,n=r[e.lastPiece];if(n.plainStart<=t&&t<n.plainStart+n.text.length)return e.lastPiece;let o=0,a=r.length-1;for(;o<a;){let i=o+a+1>>1;r[i].plainStart<=t?o=i:a=i-1}return t>=r[o].plainStart+r[o].text.length?-1:(e.lastPiece=o,o)},Sl=(e,t,r)=>{let n=Rn(e,t);return e.pieces[n>=0?n:Rn(e,r==="start"?t-1:t+1)]},Tl=(e,t)=>{let r=Rn(e,t);if(r<0)return El(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},El=(e,t)=>{let r=Rn(e,t);if(r<0)return Tl(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},pm=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),mm=Object.freeze({kind:"done"}),Lo=Object.freeze({kind:"slice"}),ym=Object.freeze({kind:"clusters"}),hm=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:s,periodic:c}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(ge.run))return Lo;let p=Sl(e,n.closedStart,"start"),m=Sl(e,n.closedEnd-1,"end");if(p.mapped===null)return{kind:"map",piece:p};if(m.mapped===null)return{kind:"map",piece:m};if(e.isCut&&e.clusters===void 0)return ym;let h=t(e.offset+Tl(e,n.closedStart)),y=t(e.offset+El(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let S=e.clusters;S==null?a(h,y,s):a(S.clusterStarts[h-S.start],S.clusterEnds[y-1-S.start],s),o.charge(ge.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(mt))return Lo;let{period:p,continuation:m}=c,h=n.periodicEnd,y=Math.min(i.length,h+Math.max(bl,m.length)),S=h;for(;S+m.length<=y&&i.startsWith(m,S);)S+=m.length;let T=S+m.length>y&&y<i.length;if(!T)for(;S<i.length&&i.charCodeAt(S)===i.charCodeAt(S-p);)S++;if(o.charge((S-h)*ge.scan),T){n.periodicEnd=S;continue}n.periodicEnd=-1,n.last+=Math.floor((S-n.last-l.length)/p)*p,n.from=n.last+l.length-p+1;continue}if(n.from<0){if(n.runStart<0)return mm;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(mt))return Lo;n.from>=n.windowEnd&&(n.windowStart=n.from,n.windowEnd=n.from+r.windowStarts,n.window=i.slice(n.from,n.windowEnd+l.length-1));let d=n.from-n.windowStart,u=n.window.indexOf(l,d);if(u<0){o.charge((n.window.length-d)*ge.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*ge.scan);let R=n.windowStart+u;(n.runStart<0||R>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=R),n.last=R,c===null?n.from=R+1:n.periodicEnd=R+l.length}};function*vo(e,t,r){let n=Math.floor(mt/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*fm(e,t,r,n,o){if(t.length===0)return;let a=yield*vo(gs(e),ge.strip,n),i=[],l=[];yield*vo(bs(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),ge.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(ge.line)||(yield),n.charge(ge.line);let d=i[c],u=a.text.slice(d,l[c]),R=yield*vo(Ds(u,r),ge.plan,n),p=[],m="";for(let y of R.chunks){let S="",T=[];for(let D of y){let f=(D.end-D.start)*ge.normalize;n.fits(f)||(yield);let g=go(D.start===0&&D.end===u.length?u:u.slice(D.start,D.end),r).text;n.charge(f),g.length>0&&T.push({start:D.start,end:D.end,text:g,chunkStart:S.length}),S+=g}if(S.length!==0){m.length>0&&(m+=" ");for(let D of T)p.push({start:D.start,end:D.end,text:D.text,plainStart:m.length+D.chunkStart,mapped:null});m+=S}}if(m.length===0)continue;let h={offset:d,plain:m,pieces:p,isCut:!sm(R,u),lastPiece:0,clusters:void 0};for(let y of t){let S=pm();for(;;){let T=hm(h,s,y,S,n,o);if(T.kind==="done")break;if(T.kind==="slice"){yield;continue}if(T.kind==="clusters"){h.clusters=yield*lm(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:D}=T,f=(D.end-D.start)*ge.map;n.fits(f)||(yield);let g=u.slice(D.start,D.end);D.mapped=im(Rs(g,So(g,r)),D.text),n.charge(f)}}}}function*Rm(e,t,r,n){let o=new Int32Array(hn.length),a=0,i=ko;for(let l=0;l<=e;l+=Rl){let s=Math.min(e+1,l+Rl),c=(s-l)*ge.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=ko;for(let R=hn.length-1;R>=0;R--){let p=hn[R];o[p]+=t[p][d],o[p]>0&&(u=p)}if(u!==i){if(i!==ko&&!n(a,d,i))return!1;a=d,i=u}}r.charge(c)}return!0}function*Sm(e,t,r,n,o){let a=null;return yield*fm(e,t,r,n,(l,s,c)=>{a===null&&(a=hn.map(()=>new Int32Array(e.length+1))),a[c][l]++,a[c][s]--}),a===null?!0:yield*Rm(e.length,a,n,o)}var gm=(e,t,r,n)=>{let o=dm(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return Al(function*(){return(yield*Sm(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var wl=(e,t)=>{if(e.combine==="intersection"||e.sets.length===1)return e.sets.flatMap(r=>r.words);if(t===null)throw new Error(`[daily-report] search marks: a union of ${e.sets.length} keywords needs the report's mask of matched keywords`);return e.sets.flatMap((r,n)=>(t&1<<n)===0?[]:r.words)},Il=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of Ia)r(ft.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(ft.interviewer(o,"name"),n.name),r(ft.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(ft.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(ft.comment($n(o),"author"),n.name),r(ft.comment($n(o),"content"),n.text)});for(let n of e.postedComments)r(ft.comment(n.id,"author"),n.userName),r(ft.comment(n.id,"content"),n.content);return t};function*bm(e,t){let r=qn;for(let n=0;n<e.length;n+=fn){let o=Math.min(e.length,n+fn),a=(o-n)*ge.linear;t.fits(a)||(yield),r=Yn(r,e,n,o),t.charge(a)}return r}var _l=async(e,t,r,n)=>{let o=0,a=0,i=async c=>{for(;!c.step();)await r(),n.startSlice();return c.result()},l=async(c,d)=>{if(!d&&a>t.maxRanges)return null;let u={};for(let{key:R,value:p}of c.fields){if(!d&&o+p.length>t.maxUnits)return null;let m=await i(Al(bm(p,n))),h=await i(gm(p,c.alternatives,{maxLength:ho,maxRanges:t.maxFieldRanges},n));if(o+=p.length,h.dense){u[R]={fingerprint:m,dense:!0};continue}if(u[R]={fingerprint:m,ranges:h.ranges},a+=h.ranges.length/3,!d&&a>t.maxRanges)return null}return u},s=[];for(let c=0;c<e.length;c++){let d=e[c],u=await l(d,s.length===0);if(u===null)return{reports:s,deferred:e.slice(c).map(R=>R.reportHubId)};s.push({reportHubId:d.reportHubId,matchedSets:d.matchedSets,fields:u})}return{reports:s,deferred:[]}};var He=require("drizzle-orm");var Oe=require("drizzle-orm");var Tt=e=>(0,Oe.getColumns)(e),_e=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},xl=e=>{let{db:t,tables:r,encodeUserId:n,settings:o,draftVisibilityTables:a}=e,{hub:i,label:l}=r,{externalSources:s,draftLabelNames:c,canonicalDraftLabelName:d}=o,u=v=>Tr(i.sourceType,v),R=(v,N)=>yn(a,v,c,N),p=Oe.sql`CASE WHEN ${mn(a,c)} THEN 1 ELSE 0 END`,m=async v=>{let[N]=await t.select({id:i.id}).top(1).from(i).where((0,Oe.and)((0,Oe.eq)(i.id,v),mn(a,c)));return N!==void 0},h=v=>v==null||v===""?null:/^\d+$/.test(v)?n(Number(v)):v,y=()=>{let v={};for(let N of s)v[`ext_${N.sourceType}`]=Tt(N.table);return v},S=v=>{let N=v;for(let L of s)N=N.leftJoin(L.table,(0,Oe.and)((0,Oe.eq)(i.sourceType,L.sourceType),(0,Oe.eq)(i.sourceIdNum,L.idColumn)));return N},T=v=>{let{hub:N,internal:L}=v,B=N.summary,E=[],I=null,V=null,J=null,te=null,z=null,ye=null,Re=[],X=s.find(Z=>Z.sourceType===N.sourceType),ve=X?v[`ext_${X.sourceType}`]:void 0;if(X&&ve){let Z=X.mapRow(ve);Z.content!==void 0&&(B=Z.content),Z.employeeName!==void 0&&(ye=Z.employeeName),Z.category!==void 0&&(I=Z.category),Z.creationCategory!==void 0&&(V=Z.creationCategory),Z.visitTimeFrom!==void 0&&(J=Z.visitTimeFrom),Z.visitTimeTo!==void 0&&(te=Z.visitTimeTo),Z.customerName!==void 0&&(z=Z.customerName),Z.interviewers!==void 0&&(E=Z.interviewers),Z.externalComments!==void 0&&(Re=Z.externalComments)}else N.sourceType===et&&L&&(B=L.body);return{content:B,author:v.creatorName??h(N.createdBy)??"",employeeName:ye??v.creatorName??h(N.createdBy),updatedBy:h(N.updatedBy),category:I,creationCategory:V,visitTimeFrom:J,visitTimeTo:te,customerName:z,interviewers:E,externalComments:Re}},D=v=>{if(v===1)return!0;if(v===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${Nt(v)}`)},f=v=>v.creationCategory!==null&&c.includes(v.creationCategory),g=(v,N)=>D(v.hasDraftLabel)?!0:f(N),k=async v=>{let[N]=await v.select({id:l.id}).top(1).from(l).where((0,Oe.eq)(l.name,d)).orderBy((0,Oe.asc)(l.id));return N===void 0?null:N.id},x=()=>k(t);return{visibleSourceTypeCondition:u,draftVisibleTo:R,draftLabelFlag:p,isDraftReport:m,externalSelections:y,applyExternalJoins:S,resolveHubDisplayFields:T,readCanonicalDraftLabelId:k,getDraftLabelId:x,resolveCreationCategoryDraftLabelId:v=>v.some(f)?x():Promise.resolve(null),mapHubRecord:(v,N,L,B,E)=>{let{hub:I}=N,V=N.labels.map(z=>({id:z.id,name:z.name,color:z.color})),J=N.postedCommentRows,te=Ie(v.commentable,I.sourceType);return B!==null&&f(L)&&!V.some(z=>z.id===B)&&V.push({id:B,name:d,color:null}),{reportHubId:I.id,date:_e(I.businessDate,"YYYY-MM-DD"),author:L.author,userId:I.userId?n(I.userId):"",sourceType:I.sourceType,createdAt:_e(I.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:_e(I.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:L.updatedBy,employeeName:L.employeeName,category:L.category,creationCategory:L.creationCategory,visitTimeFrom:L.visitTimeFrom,visitTimeTo:L.visitTimeTo,customerName:L.customerName,interviewers:L.interviewers,subject:I.title,content:L.content,externalComments:te?L.externalComments:[],isRead:N.isRead??!1,isStarred:N.isStarred??!1,isDraft:g(N,L),labels:V,postedComments:J.filter(z=>ss({authorUserId:z.userId},I.sourceType,E,v)).map(z=>({...z,userId:n(z.userId),isMine:E?z.userId===E:!1})),attachments:N.attachments}}}};var Cl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r})=>{let{db:n,tables:o,logger:a,settings:i}=e,{hub:l}=o,{attachmentDelivery:s}=i,c=(m,h)=>h!=null?"absent":m!=null?"present":"unknown";return{getAttachmentsByHubIds:async m=>{let h=new Map,y=o.attachment;if(m.length===0||!y||s===null)return h;let S=s.idCodec,T=s.thumbnails!==null,D=await n.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where((0,He.inArray)(y.hubId,m)).orderBy((0,He.asc)(y.createdAt),(0,He.asc)(y.id));for(let f of D){let g=f.fileType?String(f.fileType):null,k=f.fileSize!=null?Number(f.fileSize):null,x=c(f.objectCheckedAt,f.objectMissingAt),C={id:S.encode(Number(f.id)),fileName:String(f.fileName),fileType:g,fileSize:k,createdAt:_e(f.createdAt,"YYYY-MM-DD HH:mm:ss"),state:x,hasThumbnail:T&&x!=="absent"&&Qr({fileType:g,fileSize:k},s.maxBytes)},Y=h.get(Number(f.hubId));Y?Y.push(C):h.set(Number(f.hubId),[C])}return h},getAttachmentForUser:async(m,h,y)=>{let S=o.attachment;return!S||Ne(m.visible)?null:(await n.select({fileName:S.fileName,filePath:S.filePath,fileType:S.fileType,fileSize:S.fileSize}).top(1).from(S).innerJoin(l,(0,He.eq)(l.id,S.hubId)).where((0,He.and)((0,He.eq)(S.id,h),(0,He.isNull)(l.deletedAt),t(y,"author"),r(m.visible))))[0]??null},markAttachmentMissing:async m=>{let h=o.attachment;if(!h)return;let y=new Date;try{await n.update(h).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where((0,He.eq)(h.id,m))}catch(S){a.error("markAttachmentMissing failed",S)}},markAttachmentPresent:async m=>{let h=o.attachment;if(!h)return;let y=new Date;try{await n.update(h).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where((0,He.eq)(h.id,m))}catch(S){a.error("markAttachmentPresent failed",S)}}}};var Sn=require("drizzle-orm");var Wt=require("drizzle-orm"),or=async(e,t,r,n)=>{if((await e.update(t).set({deletedAt:null}).output().where((0,Wt.and)((0,Wt.eq)(t.id,r),(0,Wt.isNull)(t.deletedAt),n===null?void 0:(0,Wt.eq)(t.userId,n)))).length===0)throw new Error("Not Found")};var kt="daily-report:ids:epoch",qe="daily-report:date-epoch:",yt="daily-report:detail-epoch:",Ml=({redis:e,logger:t,epochs:r,streamKey:n,streamMaxLen:o})=>({incrementRedisEpoch:s=>r.incrementEpoch(s),publishToSseStream:async(s,c)=>{let d=await e?.getClient();if(!d){t.warn(`[SSE] Redis client unavailable (${c})`);return}let u=JSON.stringify(s),R=Buffer.byteLength(u);if(R>6356992){t.warn(`[SSE] Event too large (${c}): ${R} bytes > ${6356992}; not published`);return}let p=ce();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let m=ce()-p;m>1e3&&t.warn(`[SSE] Slow publish (${c}): ${m}ms`)}catch(m){t.error(`[SSE] Redis publish failed (${c}):`,m)}},readSseStreamAnchor:async()=>{try{let s=await e?.getClient();if(s===void 0)return null;let[c]=await s.xRevRange(n,"+","-",{COUNT:1});return c===void 0?It:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});var Pl=(e,{isDraftReport:t,assertHubMutable:r,incrementRedisEpoch:n})=>{let{db:o,tables:a,users:i,encodeUserId:l,cache:s,inTransaction:c,prepareSearchIndex:d,publishToSseStream:u}=e,{hub:R,comment:p}=a,m=async(T,D)=>{if(D!==null)return await t(T)?D:void 0},h=async(T,D,f,g,k,x)=>{let C=await r(T,f,D);if(!Ie(T.commentable,C.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(C.sourceType.toLowerCase()!==et.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let Y=await m(f,C.userId),v=await d(),N=await c(async I=>{await or(I,R,f,null);let[V]=await I.insert(p).output().values({hubId:f,userId:D,body:g,createdAt:new Date,createdBy:String(D),updatedAt:new Date,updatedBy:String(D)});return v!==null&&await v.writeHubs(I,[f]),V}),[L]=await o.select({displayName:i.displayName}).top(1).from(i).where((0,Sn.eq)(i.id,D)),B=L?.displayName??"";if(k){let I=Be(k);I&&(s.invalidatePrefix(tr(I)),await n(`${qe}${I}`))}s.invalidatePrefix(Ge(f)),await n(`${yt}${f}`);let E={id:N.id,userId:l(N.userId),userName:B,content:N.body,createdAt:_e(N.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(kn.parse({type:"comment-add",reportHubId:f,comment:E,clientTempId:x,recipientRawUserId:Y,sourceType:C.sourceType}),"addComment"),E},y=async(T,D)=>await T.select().top(1).from(p).where((0,Sn.eq)(p.id,D));return{addComment:h,deleteComment:async(T,D,f,g,k,x)=>{let C=await y(o,g);if(C.length===0)throw new Error("Not Found");if(C[0].hubId!==f)throw new Error("Not Found");let Y=await r(T,C[0].hubId,D);if(C[0].userId!==D)throw new Error("Unauthorized");let v=await m(f,Y.userId),N=await d();if(await c(async L=>{await or(L,R,f,null),await L.delete(p).where((0,Sn.eq)(p.id,g)),N!==null&&await N.writeHubs(L,[f])}),k){let L=Be(k);L&&(s.invalidatePrefix(tr(L)),await n(`${qe}${L}`))}s.invalidatePrefix(Ge(f)),await n(`${yt}${f}`),await u(Ln.parse({type:"comment-delete",reportHubId:f,commentId:g,clientTempId:x,recipientRawUserId:v,sourceType:Y.sourceType}),"deleteComment")}}};var Ye=require("drizzle-orm");var kl=e=>e===""?null:e,Ll=(e,{readCanonicalDraftLabelId:t,isDraftReport:r,getDailyReportDetailById:n,assertHubMutable:o,incrementRedisEpoch:a})=>{let{db:i,tables:l,cache:s,logger:c,inTransaction:d,prepareSearchIndex:u,publishToSseStream:R,settings:p,draftVisibilityTables:m}=e,{hub:h,internal:y,hubLabel:S,userStatus:T}=l,{canonicalDraftLabelName:D,draftLabelNames:f}=p,g=async(B,E,I,V)=>{if(!Nr(I))throw Q("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",I);if(!Ie(B.visible,et))throw new Error("Forbidden");c.info("createDailyReport called",{userId:E,businessDate:I});let J=await u();try{let te=await d(async X=>{c.info("Starting transaction");let ve=await t(X);if(ve===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(D)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let Z=`internal-temp-${Date.now()}-${Math.random()}`,[b]=await X.insert(h).output().values({sourceType:et,sourceId:Z,businessDate:new Date(`${I}T00:00:00Z`),userId:E,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(E),updatedAt:new Date,updatedBy:String(E)});return await X.update(h).set({sourceId:String(b.id)}).where((0,Ye.eq)(h.id,b.id)),c.info("Hub created",b),await X.insert(y).values({hubId:b.id,body:"",createdAt:new Date,createdBy:String(E),updatedAt:new Date,updatedBy:String(E)}),c.info("Internal created"),await X.insert(S).values({hubId:b.id,labelId:ve,createdAt:new Date,createdBy:String(E)}),c.info("Label assigned"),await X.insert(T).values({hubId:b.id,userId:E,isRead:!0,isStarred:!1,createdAt:new Date,createdBy:String(E),updatedAt:new Date,updatedBy:String(E)}),J!==null&&await J.writeHubs(X,[b.id]),b.id});s.invalidatePrefix(rr(I,E)),s.invalidatePrefix(Eo(E)),await a(kt),await a(`${qe}${I}`);let z=await n(ze.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),te,E,{forceRefresh:!0});if(z===null)throw new Error(`[daily-report] createDailyReport: report ${te} was committed but its detail read returned nothing`);let ye=await r(z.reportHubId);await R(On.parse({type:"report-create",reportHubId:z.reportHubId,report:z,clientTempId:V,recipientRawUserId:ye?E:void 0,actorRawUserId:E}),"createDailyReport");let Re=await n(B,te,E,{forceRefresh:!0});if(Re===null)throw new Error(`[daily-report] createDailyReport: the actor's scope cannot read report ${te} it just created`);return Re}catch(te){throw c.error("Error in createDailyReport",te),te}},k=async(B,E)=>await B.select().top(1).from(h).where((0,Ye.eq)(h.id,E)),x=async(B,E,I)=>{await o(B,E,I);let[V]=await k(i,E);if(V===void 0||V.deletedAt)throw new Error("Not Found");if(V.userId!==I)throw new Error("Unauthorized");return V},C=async(B,E,I)=>{await B.update(h).set(I).where((0,Ye.eq)(h.id,E))},Y=async(B,E,I)=>{await B.update(y).set(I).where((0,Ye.eq)(y.hubId,E))};return{createDailyReport:g,updateDailyReport:async(B,E,I,V,J)=>{let te=await x(B,E,I),z=await u();await d(async X=>{await or(X,h,E,I),V.title!==void 0&&await C(X,E,{title:kl(V.title),updatedAt:new Date,updatedBy:String(I)}),V.content!==void 0&&await Y(X,E,{body:kl(V.content),updatedAt:new Date,updatedBy:String(I)}),z!==null&&await z.writeHubs(X,[E])}),s.invalidatePrefix(Ge(E)),await a(`${yt}${E}`);let ye=Be(_e(te.businessDate,"YYYY-MM-DD"));ye&&(s.invalidatePrefix(tr(ye)),await a(`${qe}${ye}`));let Re=await n(ze.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),E,I,{forceRefresh:!0});if(Re){let X=await r(E);await R(Hn.parse({type:"report-update",reportHubId:Re.reportHubId,report:Re,clientTempId:J,recipientRawUserId:X?I:void 0,actorRawUserId:I}),"updateDailyReport")}},publishDailyReport:async(B,E,I,V)=>{let J=await x(B,E,I),te=await u();if(await d(async X=>{await or(X,h,E,I),await X.delete(S).where((0,Ye.and)((0,Ye.eq)(S.hubId,E),nl(m,f))),te!==null&&await te.writeHubs(X,[E])}),s.invalidatePrefix(Ge(E)),s.invalidatePrefix(Ct),await a(kt),J.businessDate){let X=Be(_e(J.businessDate,"YYYY-MM-DD"));X&&await a(`${qe}${X}`)}let z=Be(_e(J.businessDate,"YYYY-MM-DD"));z&&s.invalidatePrefix(rr(z,I));let ye=await n(ze.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),E,I,{forceRefresh:!0});if(ye===null)return null;let Re=await r(E);return await R(Fn.parse({type:"report-publish",reportHubId:ye.reportHubId,report:ye,clientTempId:V,recipientRawUserId:Re?I:void 0,actorRawUserId:I}),"publishDailyReport"),await n(B,E,I,{forceRefresh:!0})},deleteDailyReport:async(B,E,I,V)=>{let J=await x(B,E,I);if(await d(async te=>{if((await te.update(h).set({deletedAt:new Date,deletedBy:String(I),updatedAt:new Date,updatedBy:String(I)}).output().where((0,Ye.and)((0,Ye.eq)(h.id,E),(0,Ye.eq)(h.userId,I),(0,Ye.isNull)(h.deletedAt)))).length===0)throw new Error("Not Found")}),s.invalidatePrefix(Ge(E)),s.invalidatePrefix(Ct),await a(kt),J.businessDate){let te=Be(_e(J.businessDate,"YYYY-MM-DD"));te&&await a(`${qe}${te}`)}await R(Fr.parse({type:"report-delete",reportHubId:E,clientTempId:V,sourceType:J.sourceType}),"deleteDailyReport")}}};var G=require("drizzle-orm");var vl=$r([]),Am=6e4,Oo=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw at(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw Q(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw at(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw Q(`${e}: options.signal`,r,n);return n},Ho=e=>{let t=async()=>{await new Promise(r=>setImmediate(r)),e.throwIfAborted()};return{sliceMs:Pr.sliceMs,now:ce,pause:t}},No=e=>{try{return{ok:!0,value:e()}}catch(t){return{ok:!1,cause:t}}},Tm=e=>No(()=>{let t=hr.safeParse(JSON.parse(JSON.stringify(e)));if(!t.success)throw new Error(`[daily-report] the detail does not match the delivered detail schema (${Ca(t.error)})`);return t.data}),Nl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r,draftLabelFlag:n,externalSelections:o,applyExternalJoins:a,resolveHubDisplayFields:i,resolveCreationCategoryDraftLabelId:l,mapHubRecord:s,getAttachmentsByHubIds:c,readSseStreamAnchor:d,incrementRedisEpoch:u})=>{let{db:R,tables:p,users:m,resolveUserId:h,cache:y,epochs:S,logger:T,settings:D}=e,{hub:f,internal:g,comment:k,label:x,hubLabel:C,userStatus:Y}=p,v=D.idsTtlMs,N=D.businessDateTtlMs,L=async(w,P)=>(await R.select({reportHubId:f.id,businessDate:f.businessDate,sourceType:f.sourceType}).from(f).where((0,G.and)((0,G.isNull)(f.deletedAt),t(P,"author-or-authorless"),r(w.visible))).orderBy((0,G.desc)(f.businessDate),(0,G.desc)(f.id))).map(F=>({...F,businessDate:_e(F.businessDate,"YYYY-MM-DD")})),B=async(w,P,M)=>{let F=await I(P);return F?Ne(w.visible)?[]:(await R.select({reportHubId:f.id,businessDate:f.businessDate,sourceType:f.sourceType}).top(M).from(f).where((0,G.and)((0,G.isNull)(f.deletedAt),t(F,"author-or-authorless"),r(w.visible))).orderBy((0,G.desc)(f.businessDate),(0,G.desc)(f.id))).map(j=>({...j,businessDate:_e(j.businessDate,"YYYY-MM-DD")})):[]},E=new Map,I=async w=>{if(!D.disableUserIdCache&&E.has(w))return E.get(w)??null;let P=await h(w);return P!==null&&!D.disableUserIdCache&&E.set(w,P),P},V=async(w,P,{forceRefresh:M=!1,snapshot:F=!1,ttlMsOverride:_,onFetchStart:j,admission:ee}={})=>{let K=await I(P);if(!K)return{items:[],streamAnchor:null,snapshot:vl};if(Ne(w.visible))return{items:[],streamAnchor:await d(),snapshot:vl};let fe=Ms(K,nn(w)),[be]=await y.getOrFetch({cacheKey:fe,fetcher:async()=>{let Fe=await d(),rt=await L(w,K);if(!Aa(rt)){T.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let ae=[...rt].sort(Un);return[{items:ae,streamAnchor:Fe,snapshot:$r(ae)}]}return[{items:rt,streamAnchor:Fe,snapshot:$r(rt)}]},onFetchStart:j,forceRefresh:M,snapshot:F,admission:ee,ttlMsOverride:_??v,epochKey:kt,refreshAheadRatio:.5});if(be===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return be},J=async(w,P,M)=>{let F=await a(R.select({hub:Tt(f),internal:Tt(g),isRead:Y.isRead,isStarred:Y.isStarred,creatorName:m.displayName,hasDraftLabel:n,...o()}).from(f)).leftJoin(g,(0,G.eq)(f.id,g.hubId)).leftJoin(Y,(0,G.and)((0,G.eq)(f.id,Y.hubId),(0,G.eq)(Y.userId,P))).leftJoin(m,(0,G.eq)(f.userId,m.id)).where((0,G.and)(M,(0,G.isNull)(f.deletedAt),t(P,"author"),r(w.visible))).orderBy((0,G.desc)(f.id));if(F.length===0)return[];let _=F.map(ae=>ae.hub.id),j=await R.select({hubId:C.hubId,id:x.id,name:x.name,color:x.color}).from(C).innerJoin(x,(0,G.eq)(C.labelId,x.id)).where((0,G.inArray)(C.hubId,_)),ee=await R.select({hubId:k.hubId,id:k.id,body:k.body,createdAt:k.createdAt,userId:k.userId,userName:m.displayName}).from(k).leftJoin(m,(0,G.eq)(k.userId,m.id)).where((0,G.inArray)(k.hubId,_)).orderBy((0,G.asc)(k.createdAt)),K=await c(_),fe=new Map,be=new Map;for(let ae of j){let Pe=fe.get(ae.hubId);Pe||(Pe=[],fe.set(ae.hubId,Pe)),Pe.push({id:ae.id,name:ae.name,color:ae.color})}for(let ae of ee){let Pe=be.get(ae.hubId);Pe||(Pe=[],be.set(ae.hubId,Pe)),Pe.push({id:ae.id,content:ae.body,createdAt:_e(ae.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ae.userId,userName:ae.userName||""})}let Fe=F.map(ae=>No(()=>i(ae))),rt=await l(Fe.flatMap(ae=>ae.ok?[ae.value]:[]));return F.map((ae,Pe)=>{let ht=ae.hub.id,Lt=Fe[Pe],Et=Lt.ok?No(()=>s(w,{...ae,attachments:K.get(ht)??[],labels:fe.get(ht)||[],postedCommentRows:be.get(ht)||[]},Lt.value,rt,P)):Lt;return Et.ok?{reportHubId:ht,outcome:"ok",report:Et.value}:{reportHubId:ht,outcome:"failed",cause:Et.cause}})},te=async(w,P,M)=>(await J(w,P,M)).map(F=>{if(F.outcome==="failed")throw F.cause;return F.report}),z=w=>Ce({windowMs:Am,tallies:["failed"],writeSuppressed:(P,{count:M,since:F})=>{T.warn(`failed_report_suppressed count=${M} since=${F} read=${w} report=${P}`)}}),ye={markDailyReportSearchHits:z("markDailyReportSearchHits"),getDailyReportDetailsByIdsByExternalId:z("getDailyReportDetailsByIdsByExternalId")},Re=(w,P,M)=>{ye[w].record(P,"failed",()=>T.error(`${w}: report ${P} passed the visibility predicate but its own assembly failed`,M))},X=(w,P)=>{let M=P.outcome==="ok"?Tm(P.report):{ok:!1,cause:P.cause};return M.ok?{reportHubId:P.reportHubId,outcome:"ok",report:M.value}:(Re(w,P.reportHubId,M.cause),{reportHubId:P.reportHubId,outcome:"failed"})},ve=async(w,P,M,{read:F,signal:_,slicing:j})=>{let ee=await J(w,P,(0,G.inArray)(f.id,[...M]));_.throwIfAborted();let K=[],fe=j.now();for(let be of ee)K.length>0&&j.now()-fe>=j.sliceMs&&(await j.pause(),fe=j.now()),K.push(X(F,be));return K},Z=async(w,P,M,{forceRefresh:F=!1,snapshot:_=!1,ttlMsOverride:j,admission:ee}={})=>{let K=await I(M);if(!K)return[];let fe=Be(P);if(!fe)return[];if(Ne(w.visible))return[];let be=Ps(fe,K,nn(w));return y.getOrFetch({cacheKey:be,fetcher:()=>te(w,K,(0,G.eq)(f.businessDate,G.sql`${fe}`)),forceRefresh:F,snapshot:_,admission:ee,ttlMsOverride:j??N,epochKey:`${qe}${fe}`})},b=async(w,P,M,{forceRefresh:F=!1,snapshot:_=!1,ttlMsOverride:j,admission:ee}={})=>{if(Ne(w.visible))return null;let K=ks(P,M,nn(w));return(await y.getOrFetch({cacheKey:K,fetcher:async()=>{let be=await a(R.select({hub:Tt(f),internal:Tt(g),isRead:Y.isRead,isStarred:Y.isStarred,creatorName:m.displayName,hasDraftLabel:n,...o()}).from(f)).leftJoin(g,(0,G.eq)(f.id,g.hubId)).leftJoin(Y,(0,G.and)((0,G.eq)(f.id,Y.hubId),(0,G.eq)(Y.userId,M))).leftJoin(m,(0,G.eq)(f.userId,m.id)).where((0,G.and)((0,G.eq)(f.id,P),(0,G.isNull)(f.deletedAt),t(M,"author"),r(w.visible)));if(be.length===0)return[];let Fe=be[0].hub.id,rt=await R.select({id:x.id,name:x.name,color:x.color}).from(C).innerJoin(x,(0,G.eq)(C.labelId,x.id)).where((0,G.eq)(C.hubId,Fe)),ae=await R.select({id:k.id,body:k.body,createdAt:k.createdAt,userId:k.userId,userName:m.displayName}).from(k).leftJoin(m,(0,G.eq)(k.userId,m.id)).where((0,G.eq)(k.hubId,Fe)).orderBy((0,G.asc)(k.createdAt)),Pe=await c([Fe]),ht=rt.map(Ke=>({id:Ke.id,name:Ke.name,color:Ke.color})),Lt=ae.map(Ke=>({id:Ke.id,content:Ke.body,createdAt:_e(Ke.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Ke.userId,userName:Ke.userName||""})),Et=i(be[0]),Tn=await l([Et]);return[s(w,{...be[0],attachments:Pe.get(Fe)??[],labels:ht,postedCommentRows:Lt},Et,Tn,M)]},forceRefresh:F,snapshot:_,admission:ee,ttlMsOverride:j??N,epochKey:`${yt}${P}`}))[0]??null};return{getUserIdByExternalId:I,getDailyReportIdsByExternalId:V,getDailyReportIdsFirstPageByExternalId:B,getDailyReportsByBusinessDateByExternalId:Z,getDailyReportDetailById:b,getDailyReportDetailByIdByExternalId:async(w,P,M,F={})=>{let _=await I(M);return _?b(w,P,_,F):null},getDailyReportDetailsByIdsByExternalId:async(w,P,M,F)=>{let _=Oo("getDailyReportDetailsByIdsByExternalId",F);if(P.length>xe.maxDetailIds)throw Q("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${xe.maxDetailIds} ids`,P.length);let j=await I(M);if(!j||P.length===0||Ne(w.visible))return P.map(Rr);_.throwIfAborted();let ee=await ve(w,j,P,{read:"getDailyReportDetailsByIdsByExternalId",signal:_,slicing:Ho(_)}),K=new Map(ee.map(fe=>[fe.reportHubId,fe]));return P.map(fe=>{let be=K.get(fe);return be===void 0?Rr(fe):be})},fetchDeliveredHubOutcomes:ve,invalidateHubReadCaches:async(w,P)=>{y.invalidatePrefix(Ct),await u(kt);for(let M of new Set(w))y.invalidatePrefix(Ge(M)),await u(`${yt}${M}`);for(let M of new Set(P)){let F=Be(M);F&&await u(`${qe}${F}`)}},clearCache:async()=>{y.clearAll(),E.clear(),S&&await u(kt),T.info("Server-side DB/SQL caches cleared successfully.")}}};var gn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,streamKey:"daily-report:sse-stream",streamMaxLen:1e4}),Em=e=>{let{length:t}=e;if(t===void 0)throw Q("tables.hub.title","a character column with a declared length",t);return le("tables.hub.title.length",t,1)},wm=e=>{if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0)||new Set(e).size!==e.length)throw Q("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},Im=e=>{let t=new Map([[et.toLowerCase(),`the internal source type ${JSON.stringify(et)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw Q(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([et,...e.map(r=>r.sourceType)])},Ol=e=>{let t=e.externalSources??[],r=wm(e.draftLabelNames);Zr(e);let n=Bi(e.attachments),o=Em(e.tables.hub.title);mo(e.tables.hub.sourceType);let a=ke("idsTtlMs",e.idsTtlMs,1,gn.idsTtlMs),i=ke("businessDateTtlMs",e.businessDateTtlMs,1,gn.businessDateTtlMs),l=ke("streamMaxLen",e.streamMaxLen,1,gn.streamMaxLen);return Object.freeze({externalSources:t,sourceTypes:Im(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamKey:e.streamKey??gn.streamKey,streamMaxLen:l,disableUserIdCache:!!e.disableUserIdCache})};var me=require("drizzle-orm");var bn=["hubId","userId","isRead","isStarred","createdAt","createdBy","updatedAt","updatedBy"],_m={isRead:{statusType:"read",callerName:"setReadStatus"},isStarred:{statusType:"star",callerName:"setStarStatus"}},We=e=>me.sql`${me.sql.identifier(e.name)}`,xm=(e,t,{reportHubId:r,userId:n,value:o,at:a})=>{let i=String(n),l=We(e[t]),s=(p,m)=>me.sql`t.${We(p)} = CASE WHEN t.${l} = ${o} THEN t.${We(p)} ELSE ${m} END`,c={hubId:me.sql`s.${We(e.hubId)}`,userId:me.sql`s.${We(e.userId)}`,isRead:me.sql`${t==="isRead"?o:!1}`,isStarred:me.sql`${t==="isStarred"?o:!1}`,createdAt:me.sql`${a}`,createdBy:me.sql`${i}`,updatedAt:me.sql`${a}`,updatedBy:me.sql`${i}`},d=me.sql.join(bn.map(p=>We(e[p])),me.sql`, `),u=me.sql.join(bn.map(p=>c[p]),me.sql`, `),R=me.sql.join(bn.map(p=>me.sql`inserted.${We(e[p])} AS ${me.sql.identifier(p)}`),me.sql`, `);return me.sql`MERGE ${e} WITH (HOLDLOCK) AS t USING (SELECT ${r} AS ${We(e.hubId)}, ${n} AS ${We(e.userId)}) AS s ON t.${We(e.hubId)} = s.${We(e.hubId)} AND t.${We(e.userId)} = s.${We(e.userId)}
|
|
12
12
|
WHEN MATCHED THEN UPDATE SET t.${l} = ${o}, ${s(e.updatedAt,a)}, ${s(e.updatedBy,i)}
|
|
13
13
|
WHEN NOT MATCHED THEN INSERT (${d}) VALUES (${u})
|
|
14
|
-
OUTPUT ${R};`},Tl=(e,t)=>(typeof e=="number"||typeof e=="string")&&String(e)===String(t),El=e=>e instanceof Date||typeof e=="string",Sm=e=>{if(!Array.isArray(e))return`recordset ${Et(e)}`;if(e.length!==1)return`${e.length} rows`;let[t]=e;return typeof t!="object"||t===null?`a row of ${Et(t)}`:ln.map(r=>`${r}=${Et(t[r])}`).join(", ")},gm=(e,{reportHubId:t,userId:r})=>{let n=typeof e=="object"&&e!==null?e.recordset:void 0,o=Array.isArray(n)&&n.length===1?n[0]:void 0,a=typeof o=="object"&&o!==null?o:void 0;if(a===void 0||!Tl(a.hubId,t)||!Tl(a.userId,r)||typeof a.isRead!="boolean"||typeof a.isStarred!="boolean"||!El(a.createdAt)||!El(a.updatedAt)||typeof a.createdBy!="string"||typeof a.updatedBy!="string")throw new Error(`[daily-report] user status: the upsert must output the one status row of report ${t} and user ${r}; got ${Sm(n)}`);return{hubId:t,userId:r,isRead:a.isRead,isStarred:a.isStarred,createdAt:a.createdAt,createdBy:a.createdBy,updatedAt:a.updatedAt,updatedBy:a.updatedBy}},wl=(e,{draftVisibleTo:t,incrementRedisEpoch:r})=>{let{db:n,tables:o,cache:a,publishToSseStream:i}=e,{hub:l,userStatus:s}=o,c=async(m,h)=>{let[y]=await n.select({sourceType:l.sourceType,userId:l.userId,deletedAt:l.deletedAt}).top(1).from(l).where((0,pe.and)((0,pe.eq)(l.id,m),t(h,"author")));return y??null},d=async(m,h,y)=>{let S=await c(h,y);if(!S||S.deletedAt||!Te(m.visible,S.sourceType))throw new Error("Not Found");return{sourceType:S.sourceType,userId:S.userId}},u=async(m,h,y,S,T,D,f)=>{await d(h,S,y);let b={reportHubId:S,userId:y,value:D,at:new Date},M=gm(await n.execute(Rm(s,m,b)),b);if(T){let V=Ne(T);V&&(a.invalidatePrefix(Wt(V,y)),await r(`${Oe}${V}`))}a.invalidatePrefix(yo(S,y)),await r(`${at}${S}`);let{statusType:I,callerName:_}=fm[m];return await i(bn.parse({type:"status-update",reportHubId:S,recipientRawUserId:y,statusType:I,value:D,clientTempId:f}),_),M};return{assertHubMutable:d,setStarStatus:(m,h,y,S,T,D)=>u("isStarred",m,h,y,S,T,D),setReadStatus:(m,h,y,S,T,D)=>u("isRead",m,h,y,S,T,D)}};var bm="v4",Io=e=>`${e}:${bm}`,Dm=Object.freeze([]),wo=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},cn=(e,t)=>e.get(t)??Dm,Il=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(zr),Am=(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 Q(`${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 Q(`${e}: options.signal`,r,n);return n};function un(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:s}=e,{hub:c,internal:d,comment:u,label:R,hubLabel:p}=r,m=Al(e),{externalSources:h,draftLabelNames:y,attachmentDelivery:S,titleMaxLength:T}=m,D=be(e.logger,1,"Service"),f=oe=>(0,Kt.runWithTransactionRetry)(de=>t.transaction(re=>de(()=>oe(re))),e.transactionRetry),b=e.search===void 0?null:Bs(e.search,h.map(oe=>oe.sourceType)),M={hub:c,hubLabel:p,label:R},I=b===null?null:Zs({tables:{...M,search:b.tables},draftLabelNames:y});b!==null&&co();let _=null,V=async()=>{if(b===null)return null;if(_===null){let oe=await co(),de=b.externalSourceTexts;_=rl({hub:c,tables:b.tables,loadSources:(re,ae)=>tc(re,ae,de),inTransaction:f,normalizerVersion:oe})}return _},v=Io(m.streamKey),{incrementRedisEpoch:O,publishToSseStream:k,readSseStreamAnchor:H}=fl({redis:i,logger:D,epochs:s,streamKey:v,streamMaxLen:m.streamMaxLen}),E={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:D,settings:m,draftVisibilityTables:M,inTransaction:f,publishToSseStream:k,prepareSearchIndex:V},{visibleSourceTypeCondition:x,draftVisibleTo:$,draftLabelFlag:K,isDraftReport:ee,externalSelections:J,applyExternalJoins:ye,resolveHubDisplayFields:Se,readCanonicalDraftLabelId:te,getDraftLabelId:Ue,resolveCreationCategoryDraftLabelId:F,mapHubRecord:g}=yl(E),{getAttachmentsByHubIds:C,getAttachmentForUser:w,markAttachmentMissing:L,markAttachmentPresent:N}=hl(E,{draftVisibleTo:$,visibleSourceTypeCondition:x}),{getUserIdByExternalId:q,getDailyReportIdsByExternalId:W,getDailyReportIdsFirstPageByExternalId:U,getDailyReportsByBusinessDateByExternalId:G,getDailyReportDetailById:P,getDailyReportDetailByIdByExternalId:X,getDailyReportDetailsByIdsByExternalId:j,fetchVisibleHubDetails:Z,invalidateHubReadCaches:Dt,clearCache:dn}=Dl(E,{draftVisibleTo:$,visibleSourceTypeCondition:x,draftLabelFlag:K,externalSelections:J,applyExternalJoins:ye,resolveHubDisplayFields:Se,resolveCreationCategoryDraftLabelId:F,mapHubRecord:g,getAttachmentsByHubIds:C,readSseStreamAnchor:H,incrementRedisEpoch:O}),{assertHubMutable:Jt,setStarStatus:pn,setReadStatus:qe}=wl(E,{draftVisibleTo:$,incrementRedisEpoch:O}),{addComment:Wl,deleteComment:zl}=Rl(E,{isDraftReport:ee,assertHubMutable:Jt,incrementRedisEpoch:O}),{createDailyReport:Gl,updateDailyReport:Kl,publishDailyReport:Jl,deleteDailyReport:Ql}=gl(E,{readCanonicalDraftLabelId:te,isDraftReport:ee,getDailyReportDetailById:P,assertHubMutable:Jt,incrementRedisEpoch:O}),Xl=async(oe,de)=>{let re=new Map,ae=r.attachment;if(!ae||S===null)return re;let Ae=await oe.select({hubId:ae.hubId,fileName:ae.fileName}).from(ae).where((0,Re.inArray)(ae.hubId,[...de])).orderBy((0,Re.asc)(ae.hubId),(0,Re.asc)(ae.createdAt),(0,Re.asc)(ae.id));for(let ie of Ae)wo(re,Number(ie.hubId),String(ie.fileName));return re},Zl=async(oe,de,re)=>{let ae=new Map;for(let[Ae,ie]of re){let Je=new Map;for(let{hub:Ce}of de)Ce.sourceType===Ae&&Ce.sourceIdNum!==null&&Je.set(Ce.sourceIdNum,Ce.id);if(Je.size===0)continue;let At=await ie(oe,[...Je.keys()]);for(let[Ce,ht]of At){let Qt=Je.get(Ce);if(Qt===void 0)throw Q(`search.externalSourceTexts.${Ae} answer key`,"a source id that was asked for",Ce);if(!(Array.isArray(ht)&&ht.every(vt=>typeof vt=="string")))throw Q(`search.externalSourceTexts.${Ae} answer for ${Ce}`,"an array of strings",ht);ae.set(Qt,ht)}}return ae},ec=(oe,de)=>{let re=Se(oe),ae=[["subject",oe.hub.title],["content",re.content],["author",re.author],["employeeName",re.employeeName],["updatedBy",re.updatedBy],["category",re.category],["creationCategory",re.creationCategory],["customerName",re.customerName]];for(let ie of re.interviewers)ae.push(["interviewerName",ie.name??null],["interviewerAffiliation",ie.affiliation??null]);for(let ie of de.labelNames)ae.push(["label",ie]);for(let ie of de.attachmentNames)ae.push(["attachment",ie]);for(let ie of de.extraTexts)ae.push(["extra",ie]);let Ae=[];for(let ie of re.externalComments)Ae.push({authorUserId:null,text:Il(ie.name,ie.text)});for(let ie of de.postedComments)Ae.push({authorUserId:ie.userId,text:Il(ie.userName,ie.body)});return{hubId:oe.hub.id,fields:ae,comments:Ae,filterValues:{authorName:re.employeeName,customerName:re.customerName}}},tc=async(oe,de,re)=>{let ae=[];for(let Ae of(0,Kt.chunk)(de,Kt.MAX_IN_LIST)){let ie=await ye(oe.select({hub:yt(c),internal:yt(d),creatorName:n.displayName,...J()}).from(c)).leftJoin(d,(0,Re.eq)(c.id,d.hubId)).leftJoin(n,(0,Re.eq)(c.userId,n.id)).where((0,Re.inArray)(c.id,[...Ae])).orderBy((0,Re.asc)(c.id)),Je=new Map,At=await oe.select({hubId:p.hubId,name:R.name}).from(p).innerJoin(R,(0,Re.eq)(p.labelId,R.id)).where((0,Re.inArray)(p.hubId,[...Ae])).orderBy((0,Re.asc)(p.hubId),(0,Re.asc)(R.id));for(let we of At)wo(Je,we.hubId,we.name);let Ce=new Map,ht=await oe.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,(0,Re.eq)(u.userId,n.id)).where((0,Re.inArray)(u.hubId,[...Ae])).orderBy((0,Re.asc)(u.hubId),(0,Re.asc)(u.createdAt),(0,Re.asc)(u.id));for(let we of ht)wo(Ce,we.hubId,we);let Qt=await Xl(oe,Ae),vt=await Zl(oe,ie,re);for(let we of ie){let Tt=we.hub.id;ae.push(ec(we,{labelNames:cn(Je,Tt),postedComments:cn(Ce,Tt),attachmentNames:cn(Qt,Tt),extraTexts:cn(vt,Tt)}))}}return ae},rc=(oe,de,re)=>I===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):I.search(t,{criteria:re,viewerUserId:de,scope:oe}),Mo=m.sourceTypes,nc=async(oe,de)=>{if(I===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let re=Mo.filter(ie=>Te(oe.visible,ie)),ae=await I.facetValues(t,{column:"authorName",viewerUserId:de,scope:oe}),Ae=await I.facetValues(t,{column:"customerName",viewerUserId:de,scope:oe});return{sourceTypes:re,authors:ae,customers:Ae}},oc=async(oe,de,re,ae,Ae)=>{let ie=Am("markDailyReportSearchHits",Ae);if(I===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(ae.length>Ie.maxDetailIds)throw Q("markDailyReportSearchHits: reportHubIds",`at most ${Ie.maxDetailIds} ids`,ae.length);let Je=Cr(mr(re));if(ae.length===0||Pe(oe.visible))return{wordsDigest:Je,reports:[],deferred:[]};ie.throwIfAborted();let At=await Z(oe,de,(0,Re.inArray)(c.id,[...ae]));ie.throwIfAborted();let Ce=re.combine==="union"&&re.sets.length>=2&&At.length>0?await I.matchedSets(t,{plan:re,viewerUserId:de,scope:oe,ids:At.map(we=>we.reportHubId)}):null,ht=At.map(we=>{let Tt=Ce===null?null:Ce.get(we.reportHubId),Po=Tt===void 0?0:Tt;return{reportHubId:we.reportHubId,matchedSets:Po,alternatives:dl(re,Po).flatMap(ic=>ic.alternatives),fields:pl(we)}}),vt=await ml(ht,Eo,async()=>{await new Promise(we=>setImmediate(we)),ie.throwIfAborted()},sl(Eo,le));return{wordsDigest:Je,reports:vt.reports,deferred:vt.deferred}},ac=async oe=>{let de=await V();if(de===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return de.reconcile(t,oe)};return{streamKey:v,attachmentDelivery:S,titleMaxLength:T,searchLimits:b===null?null:{concurrency:b.concurrency,rateLimitPerMinute:b.rateLimitPerMinute},searchFilterSourceTypes:Mo,clearCache:dn,invalidateHubReadCaches:Dt,getUserIdByExternalId:q,getDailyReportIdsByExternalId:W,getDailyReportIdsFirstPageByExternalId:U,readSseStreamAnchor:H,getDailyReportsByBusinessDateByExternalId:G,getDailyReportDetailById:P,getDailyReportDetailByIdByExternalId:X,getDailyReportDetailsByIdsByExternalId:j,getDraftLabelId:Ue,searchDailyReports:rc,markDailyReportSearchHits:oc,listDailyReportSearchFacets:nc,reconcileSearchIndex:ac,getAttachmentsByHubIds:C,getAttachmentForUser:w,markAttachmentMissing:L,markAttachmentPresent:N,setStarStatus:pn,setReadStatus:qe,addComment:Wl,deleteComment:zl,createDailyReport:Gl,updateDailyReport:Kl,publishDailyReport:Jl,deleteDailyReport:Ql}}var _l=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(be(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return be(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};var br=require("drizzle-orm"),A=require("drizzle-orm/mssql-core");function xl(e,t){let r=(0,A.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,A.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,A.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,A.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(br.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,A.date)("business_date"),userId:(0,A.bigint)("user_id",{mode:"number"}),title:(0,A.nvarchar)("title",{length:200}),summary:(0,A.nvarchar)("summary",{length:"max"}),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,A.datetime2)("deleted_at"),deletedBy:(0,A.nvarchar)("deleted_by",{length:50})},u=>[(0,A.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,A.index)(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),(0,A.index)(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),(0,A.index)(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),(0,A.index)(`${e}_DailyReportHub_user_id_index`).on(u.userId),(0,A.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,br.desc)(u.businessDate),(0,br.desc)(u.id)),(0,A.index)(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,A.nvarchar)("body",{length:"max"}),metadata:(0,A.nvarchar)("metadata",{length:"max"}),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),(0,A.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}).notNull(),body:(0,A.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,A.index)(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}),name:(0,A.nvarchar)("name",{length:50}).notNull(),color:(0,A.nvarchar)("color",{length:20}),sortOrder:(0,A.int)("sort_order"),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,A.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,A.bit)("is_read").default(!1).notNull(),isStarred:(0,A.bit)("is_starred").default(!1).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),(0,A.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,A.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,A.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,A.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,A.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,A.nvarchar)("file_type",{length:100}),fileSize:(0,A.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,A.datetime2)("object_checked_at"),objectMissingAt:(0,A.datetime2)("object_missing_at"),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),(0,A.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),(0,A.index)(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:d,label:l,hubLabel:s,userStatus:c}}var me=require("drizzle-orm/mssql-core");function Cl(e){let t=(0,me.mssqlSchema)(e),r=t.table("DailyReportSearchDocument",{hubId:(0,me.bigint)("hub_id",{mode:"number"}).notNull(),searchText:(0,me.nvarchar)("search_text",{length:"max"}).notNull(),sourceDigest:(0,me.binary)("source_digest",{length:32}).notNull(),normalizerVersion:(0,me.varchar)("normalizer_version",{length:64}).notNull(),indexedAt:(0,me.datetime2)("indexed_at").notNull(),rowVersion:(0,me.binary)("row_version",{length:8}).notNull(),authorName:(0,me.nvarchar)("author_name",{length:st.maxValueLength}),customerName:(0,me.nvarchar)("customer_name",{length:st.maxValueLength})},o=>[(0,me.primaryKey)({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:(0,me.bigint)("hub_id",{mode:"number"}).notNull(),ordinal:(0,me.int)("ordinal").notNull(),authorUserId:(0,me.bigint)("author_user_id",{mode:"number"}),commentText:(0,me.nvarchar)("comment_text",{length:"max"}).notNull()},o=>[(0,me.primaryKey)({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var Tm=5e7,_o=2e8,Em=1,xo=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})})}),Ml=125,Pl=4,Ll=16,kl=50,Nl=2,Dr=Object.freeze({renderMs:ve.renderMs,nanosecondsPerBlockVisit:Ml,margin:Pl,maxBlockVisits:Math.floor(ve.renderMs*1e6/(Ml*Pl)),walkBudgetMs:Ll,nanosecondsPerWalkStep:kl,walkMargin:Nl,maxWalkSteps:Math.floor(Ll*1e6/(kl*Nl))}),wm=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),vl=75,Ol=4,Fl="#ffffff",Im=1,_m={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},xm=[/out of memory/i,/insufficient memory/i,/memory allocation|allocation failed/i,/(?:cannot|could not|unable to|failed to) allocate/i,/picture memory error/i,/unable to create thread|error creating thread|resource temporarily unavailable/i,/too many open files|no space left on device/i,/\b(?:ENOMEM|EAGAIN|EMFILE|ENFILE|ENOSPC)\b/],Hl=Object.freeze({ok:!1,reason:"failed"}),Ul=Object.freeze({ok:!1,reason:"unsupported"}),$l=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:si(e)}),Bl=(e,t)=>{switch(t){case"jpeg":{let r=Qn(e);return r===null?null:$l(r)}case"png":{let r=ui(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=di(e,Dr.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},Vl=(e,t)=>{let r=wm.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=xo,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},ql=(e,t,r)=>{let n=Bl(e,t);return n===null?null:Vl(n,r)},Cm=e=>e!==null&&e<=_o,Mm=(e,t)=>{if(t!=="jpeg")return Bl(e,t);let r=li(e,Dr);return r===null||r.blockVisits>Dr.maxBlockVisits?null:$l(r.header)},Pm=e=>{let t=e instanceof Error?e.message:"";return xm.some(r=>r.test(t))?"failed":"unsupported"},Yl=e=>{e.cache(!1),e.concurrency(Em),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(_m)});let t=async(n,o,a,i,l)=>{let s=Mm(n,o);if(s===null)return Ul;try{let c=e(n,{limitInputPixels:Tm,animated:!1});if(!Cm(Vl(s,await c.metadata())))return Ul;if(l.aborted)return Hl;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Fl}).webp({quality:vl,effort:Ol}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:Pm(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?Hl:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${vl}-e${Ol}/flatten-${Fl}/v${Im}`,render:r}};var Co=6e4,jl=e=>{let t=se("ttlMs",e.ttlMs,1,Co),r=Zt("readViewerKey",e.readViewerKey),n=Zt("resolve",e.resolve),o=new Map;return async(a,i)=>{let l=await r(a,i);if(l===null)throw new Error(`[daily-report] createDailyReportVisibilityCache: the request names no viewer for the ${JSON.stringify(i.reason)} resolution (readViewerKey answered null), so no source type may be shown`);let s=le(),c=o.get(l);if(i.reason==="initial"&&c!==void 0&&s<c.expiresAt)return c.answer;let d=Promise.resolve().then(()=>n(a,i));for(let[R,p]of o)p.expiresAt<=s&&o.delete(R);o.set(l,{expiresAt:s+t,answer:d});let u=()=>{o.get(l)?.answer===d&&o.delete(l)};return d.catch(u),d}};function Lm(e){e.redis||be(e.logger,2,"Server").warn("redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=Ar(e.redis),r=new Ot({defaultTtlMs:e.cacheDefaultTtlMs,maxBuckets:e.cacheMaxBuckets,maxBytes:e.cacheMaxBytes},t),n=un({...e,cache:r,epochs:t}),o=new zt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Zr({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:n.searchFilterSourceTypes,...a}}0&&(module.exports={DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,DAILY_REPORT_SSE_CATCH_UP_BATCH,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,buildDailyReportSseStreamKey,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createDailyReportVisibilityCache,createEpochStore,createSharpThumbnailRenderer,dailyReportSseStreamMessageSchema,defineDailyReportSchema,defineDailyReportSearchSchema,encodeIdsStreamRows,isStreamIdLte,parseClientTempId,predictSharpThumbnailWorkingSetBytes,readDailyReportSseStreamEntry,transformJsonArray});
|
|
14
|
+
OUTPUT ${R};`},Hl=(e,t)=>(typeof e=="number"||typeof e=="string")&&String(e)===String(t),Fl=e=>e instanceof Date||typeof e=="string",Cm=e=>{if(!Array.isArray(e))return`recordset ${Nt(e)}`;if(e.length!==1)return`${e.length} rows`;let[t]=e;return typeof t!="object"||t===null?`a row of ${Nt(t)}`:bn.map(r=>`${r}=${Nt(t[r])}`).join(", ")},Mm=(e,{reportHubId:t,userId:r})=>{let n=typeof e=="object"&&e!==null?e.recordset:void 0,o=Array.isArray(n)&&n.length===1?n[0]:void 0,a=typeof o=="object"&&o!==null?o:void 0;if(a===void 0||!Hl(a.hubId,t)||!Hl(a.userId,r)||typeof a.isRead!="boolean"||typeof a.isStarred!="boolean"||!Fl(a.createdAt)||!Fl(a.updatedAt)||typeof a.createdBy!="string"||typeof a.updatedBy!="string")throw new Error(`[daily-report] user status: the upsert must output the one status row of report ${t} and user ${r}; got ${Cm(n)}`);return{hubId:t,userId:r,isRead:a.isRead,isStarred:a.isStarred,createdAt:a.createdAt,createdBy:a.createdBy,updatedAt:a.updatedAt,updatedBy:a.updatedBy}},Ul=(e,{draftVisibleTo:t,incrementRedisEpoch:r})=>{let{db:n,tables:o,cache:a,publishToSseStream:i}=e,{hub:l,userStatus:s}=o,c=async(m,h)=>{let[y]=await n.select({sourceType:l.sourceType,userId:l.userId,deletedAt:l.deletedAt}).top(1).from(l).where((0,me.and)((0,me.eq)(l.id,m),t(h,"author")));return y??null},d=async(m,h,y)=>{let S=await c(h,y);if(!S||S.deletedAt||!Ie(m.visible,S.sourceType))throw new Error("Not Found");return{sourceType:S.sourceType,userId:S.userId}},u=async(m,h,y,S,T,D,f)=>{await d(h,S,y);let g={reportHubId:S,userId:y,value:D,at:new Date},k=Mm(await n.execute(xm(s,m,g)),g);if(T){let Y=Be(T);Y&&(a.invalidatePrefix(rr(Y,y)),await r(`${qe}${Y}`))}a.invalidatePrefix(wo(S,y)),await r(`${yt}${S}`);let{statusType:x,callerName:C}=_m[m];return await i(Pn.parse({type:"status-update",reportHubId:S,recipientRawUserId:y,statusType:x,value:D,clientTempId:f}),C),k};return{assertHubMutable:d,setStarStatus:(m,h,y,S,T,D)=>u("isStarred",m,h,y,S,T,D),setReadStatus:(m,h,y,S,T,D)=>u("isRead",m,h,y,S,T,D)}};var Pm="v4",Uo=e=>`${e}:${Pm}`,km=Object.freeze([]),Fo=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},Dn=(e,t)=>e.get(t)??km,$l=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(an);function An(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:s}=e,{hub:c,internal:d,comment:u,label:R,hubLabel:p}=r,m=Ol(e),{externalSources:h,draftLabelNames:y,attachmentDelivery:S,titleMaxLength:T}=m,D=Ae(e.logger,1,"Service"),f=oe=>(0,ar.runWithTransactionRetry)(pe=>t.transaction(re=>pe(()=>oe(re))),e.transactionRetry),g=e.search===void 0?null:tl(e.search,h.map(oe=>oe.sourceType)),k={hub:c,hubLabel:p,label:R},x=g===null?null:ml({tables:{...k,search:g.tables},draftLabelNames:y});g!==null&&Do();let C=null,Y=async()=>{if(g===null)return null;if(C===null){let oe=await Do(),pe=g.externalSourceTexts;C=fl({hub:c,tables:g.tables,loadSources:(re,ie)=>cc(re,ie,pe),inTransaction:f,normalizerVersion:oe})}return C},v=Uo(m.streamKey),{incrementRedisEpoch:N,publishToSseStream:L,readSseStreamAnchor:B}=Ml({redis:i,logger:D,epochs:s,streamKey:v,streamMaxLen:m.streamMaxLen}),E={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:D,settings:m,draftVisibilityTables:k,inTransaction:f,publishToSseStream:L,prepareSearchIndex:Y},{visibleSourceTypeCondition:I,draftVisibleTo:V,draftLabelFlag:J,isDraftReport:te,externalSelections:z,applyExternalJoins:ye,resolveHubDisplayFields:Re,readCanonicalDraftLabelId:X,getDraftLabelId:ve,resolveCreationCategoryDraftLabelId:Z,mapHubRecord:b}=xl(E),{getAttachmentsByHubIds:U,getAttachmentForUser:O,markAttachmentMissing:H,markAttachmentPresent:$}=Cl(E,{draftVisibleTo:V,visibleSourceTypeCondition:I}),{getUserIdByExternalId:w,getDailyReportIdsByExternalId:P,getDailyReportIdsFirstPageByExternalId:M,getDailyReportsByBusinessDateByExternalId:F,getDailyReportDetailById:_,getDailyReportDetailByIdByExternalId:j,getDailyReportDetailsByIdsByExternalId:ee,fetchDeliveredHubOutcomes:K,invalidateHubReadCaches:fe,clearCache:be}=Nl(E,{draftVisibleTo:V,visibleSourceTypeCondition:I,draftLabelFlag:J,externalSelections:z,applyExternalJoins:ye,resolveHubDisplayFields:Re,resolveCreationCategoryDraftLabelId:Z,mapHubRecord:b,getAttachmentsByHubIds:U,readSseStreamAnchor:B,incrementRedisEpoch:N}),{assertHubMutable:Fe,setStarStatus:rt,setReadStatus:ae}=Ul(E,{draftVisibleTo:V,incrementRedisEpoch:N}),{addComment:Pe,deleteComment:ht}=Pl(E,{isDraftReport:te,assertHubMutable:Fe,incrementRedisEpoch:N}),{createDailyReport:Lt,updateDailyReport:Et,publishDailyReport:Tn,deleteDailyReport:Ke}=Ll(E,{readCanonicalDraftLabelId:X,isDraftReport:te,getDailyReportDetailById:_,assertHubMutable:Fe,incrementRedisEpoch:N}),ic=async(oe,pe)=>{let re=new Map,ie=r.attachment;if(!ie||S===null)return re;let we=await oe.select({hubId:ie.hubId,fileName:ie.fileName}).from(ie).where((0,Te.inArray)(ie.hubId,[...pe])).orderBy((0,Te.asc)(ie.hubId),(0,Te.asc)(ie.createdAt),(0,Te.asc)(ie.id));for(let se of we)Fo(re,Number(se.hubId),String(se.fileName));return re},sc=async(oe,pe,re)=>{let ie=new Map;for(let[we,se]of re){let nt=new Map;for(let{hub:Ue}of pe)Ue.sourceType===we&&Ue.sourceIdNum!==null&&nt.set(Ue.sourceIdNum,Ue.id);if(nt.size===0)continue;let wt=await se(oe,[...nt.keys()]);for(let[Ue,ot]of wt){let vt=nt.get(Ue);if(vt===void 0)throw Q(`search.externalSourceTexts.${we} answer key`,"a source id that was asked for",Ue);if(!(Array.isArray(ot)&&ot.every(ir=>typeof ir=="string")))throw Q(`search.externalSourceTexts.${we} answer for ${Ue}`,"an array of strings",ot);ie.set(vt,ot)}}return ie},lc=(oe,pe)=>{let re=Re(oe),ie=[["subject",oe.hub.title],["content",re.content],["author",re.author],["employeeName",re.employeeName],["updatedBy",re.updatedBy],["category",re.category],["creationCategory",re.creationCategory],["customerName",re.customerName]];for(let se of re.interviewers)ie.push(["interviewerName",se.name??null],["interviewerAffiliation",se.affiliation??null]);for(let se of pe.labelNames)ie.push(["label",se]);for(let se of pe.attachmentNames)ie.push(["attachment",se]);for(let se of pe.extraTexts)ie.push(["extra",se]);let we=[];for(let se of re.externalComments)we.push({authorUserId:null,text:$l(se.name,se.text)});for(let se of pe.postedComments)we.push({authorUserId:se.userId,text:$l(se.userName,se.body)});return{hubId:oe.hub.id,fields:ie,comments:we,filterValues:{authorName:re.employeeName,customerName:re.customerName}}},cc=async(oe,pe,re)=>{let ie=[];for(let we of(0,ar.chunk)(pe,ar.MAX_IN_LIST)){let se=await ye(oe.select({hub:Tt(c),internal:Tt(d),creatorName:n.displayName,...z()}).from(c)).leftJoin(d,(0,Te.eq)(c.id,d.hubId)).leftJoin(n,(0,Te.eq)(c.userId,n.id)).where((0,Te.inArray)(c.id,[...we])).orderBy((0,Te.asc)(c.id)),nt=new Map,wt=await oe.select({hubId:p.hubId,name:R.name}).from(p).innerJoin(R,(0,Te.eq)(p.labelId,R.id)).where((0,Te.inArray)(p.hubId,[...we])).orderBy((0,Te.asc)(p.hubId),(0,Te.asc)(R.id));for(let Je of wt)Fo(nt,Je.hubId,Je.name);let Ue=new Map,ot=await oe.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,(0,Te.eq)(u.userId,n.id)).where((0,Te.inArray)(u.hubId,[...we])).orderBy((0,Te.asc)(u.hubId),(0,Te.asc)(u.createdAt),(0,Te.asc)(u.id));for(let Je of ot)Fo(Ue,Je.hubId,Je);let vt=await ic(oe,we),ir=await sc(oe,se,re);for(let Je of se){let $e=Je.hub.id;ie.push(lc(Je,{labelNames:Dn(nt,$e),postedComments:Dn(Ue,$e),attachmentNames:Dn(vt,$e),extraTexts:Dn(ir,$e)}))}}return ie},uc=(oe,pe,re)=>x===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):x.search(t,{criteria:re,viewerUserId:pe,scope:oe}),qo=m.sourceTypes,dc=async(oe,pe)=>{if(x===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let re=qo.filter(se=>Ie(oe.visible,se)),ie=await x.facetValues(t,{column:"authorName",viewerUserId:pe,scope:oe}),we=await x.facetValues(t,{column:"customerName",viewerUserId:pe,scope:oe});return{sourceTypes:re,authors:ie,customers:we}},pc=async(oe,pe,re,ie,we)=>{let se=Oo("markDailyReportSearchHits",we);if(x===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(ie.length>xe.maxDetailIds)throw Q("markDailyReportSearchHits: reportHubIds",`at most ${xe.maxDetailIds} ids`,ie.length);let nt=Br(Er(re));if(ie.length===0||Ne(oe.visible))return{wordsDigest:nt,reports:[],deferred:[]};se.throwIfAborted();let wt=Ho(se),Ue=await K(oe,pe,ie,{read:"markDailyReportSearchHits",signal:se,slicing:wt});await wt.pause();let ot=Ue.flatMap($e=>$e.outcome==="ok"?[{reportHubId:$e.reportHubId,fields:Il($e.report)}]:[]),vt=re.combine==="union"&&re.sets.length>=2&&ot.length>0?await x.matchedSets(t,{plan:re,viewerUserId:pe,scope:oe,ids:ot.map($e=>$e.reportHubId)}):null,ir=ot.map(({reportHubId:$e,fields:yc})=>{let Yo=vt===null?null:vt.get($e),Wo=Yo===void 0?0:Yo;return{reportHubId:$e,matchedSets:Wo,alternatives:wl(re,Wo).flatMap(hc=>hc.alternatives),fields:yc}}),Je=await _l(ir,Pr,wt.pause,Dl(Pr,wt.now));return{wordsDigest:nt,reports:Je.reports,deferred:Je.deferred}},mc=async oe=>{let pe=await Y();if(pe===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return pe.reconcile(t,oe)};return{streamKey:v,attachmentDelivery:S,titleMaxLength:T,searchLimits:g===null?null:{concurrency:g.concurrency,rateLimitPerMinute:g.rateLimitPerMinute},searchFilterSourceTypes:qo,clearCache:be,invalidateHubReadCaches:fe,getUserIdByExternalId:w,getDailyReportIdsByExternalId:P,getDailyReportIdsFirstPageByExternalId:M,readSseStreamAnchor:B,getDailyReportsByBusinessDateByExternalId:F,getDailyReportDetailById:_,getDailyReportDetailByIdByExternalId:j,getDailyReportDetailsByIdsByExternalId:ee,getDraftLabelId:ve,searchDailyReports:uc,markDailyReportSearchHits:pc,listDailyReportSearchFacets:dc,reconcileSearchIndex:mc,getAttachmentsByHubIds:U,getAttachmentForUser:O,markAttachmentMissing:H,markAttachmentPresent:$,setStarStatus:rt,setReadStatus:ae,addComment:Pe,deleteComment:ht,createDailyReport:Lt,updateDailyReport:Et,publishDailyReport:Tn,deleteDailyReport:Ke}}var Bl=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(Ae(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return Ae(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};var kr=require("drizzle-orm"),A=require("drizzle-orm/mssql-core");function Vl(e,t){let r=(0,A.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,A.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,A.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,A.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(kr.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,A.date)("business_date"),userId:(0,A.bigint)("user_id",{mode:"number"}),title:(0,A.nvarchar)("title",{length:200}),summary:(0,A.nvarchar)("summary",{length:"max"}),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,A.datetime2)("deleted_at"),deletedBy:(0,A.nvarchar)("deleted_by",{length:50})},u=>[(0,A.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,A.index)(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),(0,A.index)(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),(0,A.index)(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),(0,A.index)(`${e}_DailyReportHub_user_id_index`).on(u.userId),(0,A.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,kr.desc)(u.businessDate),(0,kr.desc)(u.id)),(0,A.index)(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,A.nvarchar)("body",{length:"max"}),metadata:(0,A.nvarchar)("metadata",{length:"max"}),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),(0,A.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}).notNull(),body:(0,A.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,A.index)(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}),name:(0,A.nvarchar)("name",{length:50}).notNull(),color:(0,A.nvarchar)("color",{length:20}),sortOrder:(0,A.int)("sort_order"),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,A.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,A.bit)("is_read").default(!1).notNull(),isStarred:(0,A.bit)("is_starred").default(!1).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),(0,A.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,A.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,A.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,A.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,A.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,A.nvarchar)("file_type",{length:100}),fileSize:(0,A.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,A.datetime2)("object_checked_at"),objectMissingAt:(0,A.datetime2)("object_missing_at"),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),(0,A.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),(0,A.index)(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:d,label:l,hubLabel:s,userStatus:c}}var he=require("drizzle-orm/mssql-core");function ql(e){let t=(0,he.mssqlSchema)(e),r=t.table("DailyReportSearchDocument",{hubId:(0,he.bigint)("hub_id",{mode:"number"}).notNull(),searchText:(0,he.nvarchar)("search_text",{length:"max"}).notNull(),sourceDigest:(0,he.binary)("source_digest",{length:32}).notNull(),normalizerVersion:(0,he.varchar)("normalizer_version",{length:64}).notNull(),indexedAt:(0,he.datetime2)("indexed_at").notNull(),rowVersion:(0,he.binary)("row_version",{length:8}).notNull(),authorName:(0,he.nvarchar)("author_name",{length:Rt.maxValueLength}),customerName:(0,he.nvarchar)("customer_name",{length:Rt.maxValueLength})},o=>[(0,he.primaryKey)({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:(0,he.bigint)("hub_id",{mode:"number"}).notNull(),ordinal:(0,he.int)("ordinal").notNull(),authorUserId:(0,he.bigint)("author_user_id",{mode:"number"}),commentText:(0,he.nvarchar)("comment_text",{length:"max"}).notNull()},o=>[(0,he.primaryKey)({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var Lm=5e7,$o=2e8,vm=1,Bo=Object.freeze({fixedBytes:4*1024*1024,pipelineRows:2048,wholeImageBuffer:Object.freeze({"jpeg-single-scan":Object.freeze({kind:"none"}),"jpeg-multi-scan":Object.freeze({kind:"jpeg-coefficients"}),png:Object.freeze({kind:"none"}),"png-interlaced":Object.freeze({kind:"decoded-raster"}),gif:Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-lossy":Object.freeze({kind:"none"}),"webp-lossy-alpha":Object.freeze({kind:"canvas",bytesPerPixel:5}),"webp-lossless":Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-animated":Object.freeze({kind:"canvas",bytesPerPixel:9})})}),Yl=125,Wl=4,jl=16,zl=50,Gl=2,Lr=Object.freeze({renderMs:Ve.renderMs,nanosecondsPerBlockVisit:Yl,margin:Wl,maxBlockVisits:Math.floor(Ve.renderMs*1e6/(Yl*Wl)),walkBudgetMs:jl,nanosecondsPerWalkStep:zl,walkMargin:Gl,maxWalkSteps:Math.floor(jl*1e6/(zl*Gl))}),Nm=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Kl=75,Jl=4,Ql="#ffffff",Om=1,Hm={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Fm=[/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/],Xl=Object.freeze({ok:!1,reason:"failed"}),Zl=Object.freeze({ok:!1,reason:"unsupported"}),ec=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Ai(e)}),tc=(e,t)=>{switch(t){case"jpeg":{let r=lo(e);return r===null?null:ec(r)}case"png":{let r=wi(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Ii(e,Lr.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},rc=(e,t)=>{let r=Nm.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Bo,a=o.wholeImageBuffer[e.layout];return(a.kind==="none"?0:a.kind==="decoded-raster"?t.width*t.height*n:a.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*a.bytesPerPixel)+o.pipelineRows*t.width*n+o.fixedBytes},nc=(e,t,r)=>{let n=tc(e,t);return n===null?null:rc(n,r)},Um=e=>e!==null&&e<=$o,$m=(e,t)=>{if(t!=="jpeg")return tc(e,t);let r=Ti(e,Lr);return r===null||r.blockVisits>Lr.maxBlockVisits?null:ec(r.header)},Bm=e=>{let t=e instanceof Error?e.message:"";return Fm.some(r=>r.test(t))?"failed":"unsupported"},oc=e=>{e.cache(!1),e.concurrency(vm),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Hm)});let t=async(n,o,a,i,l)=>{let s=$m(n,o);if(s===null)return Zl;try{let c=e(n,{limitInputPixels:Lm,animated:!1});if(!Um(rc(s,await c.metadata())))return Zl;if(l.aborted)return Xl;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Ql}).webp({quality:Kl,effort:Jl}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:Bm(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?Xl:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Kl}-e${Jl}/flatten-${Ql}/v${Om}`,render:r}};var Vo=6e4,ac=e=>{let t=le("ttlMs",e.ttlMs,1,Vo),r=lr("readViewerKey",e.readViewerKey),n=lr("resolve",e.resolve),o=new Map;return async(a,i)=>{let l=await r(a,i);if(l===null)throw new Error(`[daily-report] createDailyReportVisibilityCache: the request names no viewer for the ${JSON.stringify(i.reason)} resolution (readViewerKey answered null), so no source type may be shown`);let s=ce(),c=o.get(l);if(i.reason==="initial"&&c!==void 0&&s<c.expiresAt)return c.answer;let d=Promise.resolve().then(()=>n(a,i));for(let[R,p]of o)p.expiresAt<=s&&o.delete(R);o.set(l,{expiresAt:s+t,answer:d});let u=()=>{o.get(l)?.answer===d&&o.delete(l)};return d.catch(u),d}};function Vm(e){e.redis||Ae(e.logger,2,"Server").warn("redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=vr(e.redis),r=new jt({defaultTtlMs:e.cacheDefaultTtlMs,maxBuckets:e.cacheMaxBuckets,maxBytes:e.cacheMaxBytes},t),n=An({...e,cache:r,epochs:t}),o=new nr({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=pn({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:n.searchFilterSourceTypes,...a}}0&&(module.exports={DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,DAILY_REPORT_SSE_CATCH_UP_BATCH,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,buildDailyReportSseStreamKey,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createDailyReportVisibilityCache,createEpochStore,createSharpThumbnailRenderer,dailyReportSseStreamMessageSchema,defineDailyReportSchema,defineDailyReportSearchSchema,encodeIdsStreamRows,isStreamIdLte,parseClientTempId,predictSharpThumbnailWorkingSetBytes,readDailyReportSseStreamEntry,transformJsonArray});
|
|
15
15
|
/* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */
|