@aiquants/daily-report 0.48.0 → 0.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +45 -24
- package/dist/client.d.mts +11 -3
- package/dist/client.d.ts +11 -3
- package/dist/client.js +5 -5
- package/dist/client.mjs +5 -5
- package/dist/server.js +1 -1
- package/dist/server.mjs +1 -1
- package/dist/styles/daily-report.standalone.css +1 -1
- package/package.json +1 -1
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var xn=Object.defineProperty;var Tc=Object.getOwnPropertyDescriptor;var Ac=Object.getOwnPropertyNames;var Ec=Object.prototype.hasOwnProperty;var Xo=e=>{throw TypeError(e)};var wc=(e,t)=>{for(var r in t)xn(e,r,{get:t[r],enumerable:!0})},Ic=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ac(t))!Ec.call(e,o)&&o!==r&&xn(e,o,{get:()=>t[o],enumerable:!(n=Tc(t,o))||n.enumerable});return e};var _c=e=>Ic(xn({},"__esModule",{value:!0}),e);var Zo=(e,t,r)=>t.has(e)||Xo("Cannot "+r);var cr=(e,t,r)=>(Zo(e,t,"read from private field"),r?r.call(e):t.get(e)),Cn=(e,t,r)=>t.has(e)?Xo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Mn=(e,t,r,n)=>(Zo(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var ny={};wc(ny,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>Xr,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>Qr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>Yo,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Nr,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>zo,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>mn,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>ko,DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS:()=>Go,DailyReportSseReader:()=>ar,DailyReportViewerScope:()=>Xe,SqlResultCache:()=>Gt,buildDailyReportRedisKeys:()=>Tn,createDailyReportHandlers:()=>yn,createDailyReportServer:()=>ry,createDailyReportService:()=>In,createDailyReportVisibilityCache:()=>hc,createEpochStore:()=>Or,createSharpThumbnailRenderer:()=>yc,dailyReportSseStreamMessageSchema:()=>Br,defineDailyReportSchema:()=>Xl,defineDailyReportSearchSchema:()=>Zl,encodeIdsStreamRows:()=>Ut,isStreamIdLte:()=>mt,parseClientTempId:()=>Yr,predictSharpThumbnailWorkingSetBytes:()=>mc,readDailyReportSseStreamEntry:()=>rr,transformJsonArray:()=>Ql});module.exports=_c(ny);var Ht=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,Q=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Ht(r)}`),Je=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),kn=(e,t,r)=>Q(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ce=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw Q(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},Oe=(e,t,r,n)=>t===void 0?n:ce(e,t,r),ur=(e,t)=>{if(t===void 0)throw Je(e,"a function");if(typeof t!="function")throw Q(e,"a function",t);return t};var ue=()=>Math.floor(performance.now());var Pn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),rt=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},Or=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),dr=(e,t)=>t?e.map(r=>structuredClone(r)):e,xc=8,Cc=32,Mc=24,kc=16,Pc=-(2**30),vc=2**30-1,Lc=e=>Number.isInteger(e)&&e>=Pc&&e<=vc&&!Object.is(e,-0),Nc=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=Cc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=xc*a.length;for(let i of a)typeof i=="string"?r+=Mc+2*i.length:typeof i=="number"&&!Lc(i)?r+=kc:typeof i=="object"&&i!==null&&n.push(i)}return r},Gt=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-ue())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:c,expireAt:ue()+a,epoch:s}),c})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&s===null)throw new rt(o.signal.aborted?"aborted":"busy");try{for(let d of r)d();let c=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:c,expireAt:ue()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),c}finally{s?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new rt("aborted");return this.dropBucket(r),dr(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ue())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),dr(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),dr(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return dr(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new rt("aborted");return dr(await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};this.readOwnOrRetry=async(t,r)=>{try{return await t}catch(n){let{admission:o}=r;if(!(n instanceof rt&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.totalBytes=0,this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.dropBucket(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=Oe("cacheDefaultTtlMs",t.defaultTtlMs,1,Pn.defaultTtlMs),this.maxBuckets=Oe("cacheMaxBuckets",t.maxBuckets,1,Pn.maxBuckets),this.maxBytes=Oe("cacheMaxBytes",t.maxBytes,1,Pn.maxBytes),this.lastSweepAt=ue()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=Nc(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=ue();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};var rl=require("@aiquants/request-isolation");var Oc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var ea=e=>e<10?`0${e}`:`${e}`,Hc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=ea(e.getMonth()+1),n=ea(e.getDate());return`${t}-${r}-${n}`},Kt=e=>{let t=Oc.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let s=new Date(0);return s.setUTCFullYear(a,i-1,l),s.getUTCFullYear()!==a||s.getUTCMonth()!==i-1||s.getUTCDate()!==l?null:`${r}-${n}-${o}`},Hr=e=>Kt(e)===e;var We=e=>e==null?null:e instanceof Date?Hc(e):Kt(e);var ta=require("zod/v3"),ct=e=>Number.isSafeInteger(e)&&e>0,He=ta.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var re=require("zod/v3");var Fr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;var vn=/^[0-9a-f]{64}$/u;var Ft=e=>typeof e=="string"&&vn.test(e);var $t=Symbol("daily-report wire mismatch"),Qe=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),$t),aa=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,xt=(e,t)=>({code:"invalid_type",expected:e,received:aa(t)}),Fc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$c=e=>{let t=0;for(let r in e)t+=1;return t},ra=(e,t,r)=>{let n={};for(let o=0;o<r;o+=1){let a=t[o];a in e&&(n[a]=e[a])}return n},Jt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!Fc(n))return Qe(o,null,xt("object",n));let a=null,i=!1,l=0;for(let s=0;s<t.length;s+=1){let c=t[s],d=n[c];d!==void 0&&(l+=1);let u=r[s](d,o,c);if(u===$t){i=!0;continue}a===null&&u!==d&&(a=ra(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?$t:a!==null?a:$c(n)===l?n:ra(n,t,t.length)}},pr=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},mr=e=>(t,r,n)=>{if(!Array.isArray(t))return Qe(r,n,xt("array",t));r.path.push(n);let o=t,a=!1;for(let i=0;i<t.length;i+=1){let l=t[i],s=e(l,r,i);s===$t?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?$t:o},ye=(e,t,r)=>e==null||typeof e=="string"?e:Qe(t,r,xt("string",e)),na=(e,t,r)=>e===null||typeof e=="string"?e:Qe(t,r,xt("string",e)),oa=(e,t,r)=>typeof e=="string"?e:Qe(t,r,xt("string",e)),Uc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:Qe(t,r,xt("number",e)),yr=(e,t,r)=>typeof e=="boolean"?e:Qe(t,r,xt("boolean",e)),ia=(e,t,r)=>typeof e!="string"?Qe(t,r,xt("string",e)):Ft(e)?e:Qe(t,r,{code:"invalid_string",validation:"regex",message:"a content digest is 64 lowercase hex digits"}),Bc=(e,t,r)=>e===null?null:ia(e,t,r),Ln=(e,t,r)=>{if(typeof e=="number"&&ct(e))return e;for(let{message:n,path:o,...a}of He.safeParse(e).error.issues)Qe(t,r,a);return $t},sa={present:!0,absent:!0,unknown:!0},la=Object.keys(sa),Vc=la.map(e=>`'${e}'`).join(" | "),qc=(e,t,r)=>typeof e!="string"?Qe(t,r,{code:"invalid_type",expected:Vc,received:aa(e)}):Object.hasOwn(sa,e)?e:Qe(t,r,{code:"invalid_enum_value",received:e,options:[...la]}),ca=Jt({name:ye,affiliation:ye}),ua=Jt({name:ye,text:ye,color:ye}),da=Jt({id:Ln,name:ye,color:ye}),pa=Jt({id:Ln,userId:ye,userName:ye,content:ye,createdAt:ye,isMine:yr}),jc=Jt({id:oa,fileName:oa,fileType:na,fileSize:Uc,createdAt:na,state:qc,hasThumbnail:yr}),Wc=Jt({reportHubId:Ln,date:ye,createdAt:ye,author:ye,userId:ye,sourceType:ye,employeeName:ye,updatedBy:ye,updatedAt:ye,category:ye,creationCategory:ye,visitTimeFrom:ye,visitTimeTo:ye,customerName:ye,interviewers:mr(pr(ca)),subject:ye,content:ye,externalComments:mr(pr(ua)),isRead:yr,isStarred:yr,contentDigest:ia,readContentDigest:Bc,isDraft:yr,labels:mr(pr(da)),postedComments:mr(pr(pa)),attachments:mr(pr(jc))}),hr=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===$t?{ok:!1,issues:r.issues}:{ok:!0,value:n}},ma=e=>hr(Wc,e),ya=e=>hr(ca,e),ha=e=>hr(ua,e),fa=e=>hr(da,e),Ra=e=>hr(pa,e);var Sa=15e3,ga="lastEventId",Yc=/^\d{1,15}-\d{1,15}$/,ba=e=>Yc.test(e),Ct="0-0",fr=e=>re.z.unknown().transform((t,r)=>{let n=e(t);if(n.ok)return n.value;for(let o of n.issues)r.addIssue({...o,fatal:!0});return re.z.NEVER}),Dy=fr(ya),Ty=fr(ha),Ay=fr(fa),zc=fr(Ra),Rr=fr(ma),Sr=re.z.string().regex(Fr),Da=re.z.object({type:re.z.literal("connected")}),Ta=re.z.object({type:re.z.literal("status-update"),reportHubId:He,statusType:re.z.enum(["star","read"]),value:re.z.boolean(),readContentDigest:re.z.string().regex(vn).nullable(),clientTempId:Sr}),Nn=re.z.string(),Aa=re.z.object({type:re.z.literal("comment-add"),reportHubId:He,comment:zc,clientTempId:Sr,sourceType:Nn}),Ea=re.z.object({type:re.z.literal("comment-delete"),reportHubId:He,commentId:He,clientTempId:Sr,sourceType:Nn}),$r={recipientRawUserId:He.optional()},On=Ta.extend($r),Hn=Aa.extend($r),Fn=Ea.extend($r),Qt={reportHubId:He,report:Rr,clientTempId:Sr},$n={...$r,actorRawUserId:He},Un={viewerIsActor:re.z.boolean()},Gc=re.z.object({type:re.z.literal("report-create"),...Qt,...Un}),Kc=re.z.object({type:re.z.literal("report-update"),...Qt,...Un}),Jc=re.z.object({type:re.z.literal("report-publish"),...Qt,...Un}),Bn=re.z.object({type:re.z.literal("report-create"),...Qt,...$n}),Vn=re.z.object({type:re.z.literal("report-update"),...Qt,...$n}),qn=re.z.object({type:re.z.literal("report-publish"),...Qt,...$n}),Ur=re.z.object({type:re.z.literal("report-delete"),reportHubId:He,clientTempId:Sr,sourceType:Nn}),Ey=re.z.discriminatedUnion("type",[Da,Ta,Aa,Ea,Gc,Kc,Jc,Ur]),Br=re.z.discriminatedUnion("type",[Da,On,Hn,Fn,Bn,Vn,qn,Ur]);var wa="ids-columns";var Qc=/^[0-9a-f]{1,16}$/,Ia=e=>ct(e.reportHubId)&&(e.businessDate===null||Hr(e.businessDate)),_a=e=>typeof e=="string"&&Qc.test(e),xy=Object.freeze({kind:"absent"}),Cy=Object.freeze({kind:"value",value:null});var Ut=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:h}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let m=h===void 0?null:h,y=s.get(m);y===void 0&&(y=i.length,i.push(m),s.set(m,y)),l.push(y)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},Vr=e=>{let t=2166136261,r=-624069552;for(let n of e){let o=n.reportHubId;t^=o&255,t=Math.imul(t,16777619),t^=o>>>8&255,t=Math.imul(t,16777619),t^=o>>>16&255,t=Math.imul(t,16777619),t^=o>>>24&255,t=Math.imul(t,16777619),r^=o>>>24&255,r=Math.imul(r,16777619),r^=o>>>16&255,r=Math.imul(r,16777619),r^=o>>>8&255,r=Math.imul(r,16777619),r^=o&255,r=Math.imul(r,16777619);let a=n.businessDate;if(a===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let i=0;i<a.length;i++){let l=a.charCodeAt(i);t^=l&255,t=Math.imul(t,16777619),r^=l&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},xa=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Xc=(e,t,r,n)=>xa(e,t,r,n)<0,jn=(e,t)=>xa(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Ca=e=>{for(let t=1;t<e.length;t++)if(!Xc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},Ma=(e,t)=>{let r=e.findIndex(n=>jn({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var de=Object.freeze({businessDate:"business-date",idsStream:wa,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),Ae=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var ka=(e,t,r=console)=>{let n=o=>typeof o=="string"?[`${t} ${o}`]:[t,o];return{debug:(o,...a)=>{e<=0&&r.debug(...n(o),...a)},info:(o,...a)=>{e<=1&&r.info(...n(o),...a)},warn:(o,...a)=>{e<=2&&r.warn(...n(o),...a)},error:(o,...a)=>{e<=3&&r.error(...n(o),...a)}}},vy=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),Pa=e=>`[DailyReport${e}]`,Ee=(e,t,r)=>e===void 0?ka(t,Pa(r)):ka(0,Pa(r),e);var Mt=require("zod/v3");var gr=e=>({reportHubId:e,outcome:"not_found"}),Hy=Mt.z.discriminatedUnion("outcome",[Mt.z.object({reportHubId:He,outcome:Mt.z.literal("ok"),report:Rr}).strict(),Mt.z.object({reportHubId:He,outcome:Mt.z.literal("not_found")}).strict(),Mt.z.object({reportHubId:He,outcome:Mt.z.literal("failed")}).strict()]);var Zc="legacy-",Wn=e=>`${Zc}${e}`;var eu=/^[1-9][0-9]*$/,tu=/^(?:0|[1-9][0-9]*)$/,nt=e=>{if(e===null||!eu.test(e))return null;let t=Number(e);return ct(t)?t:null},Yn=e=>{if(e===null||!tu.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},zn=e=>e==="true"?!0:e==="false"?!1:null,br=e=>e===null?!1:zn(e);var va=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),St=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var ru=16777619,Gn=2166136261,Kn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,ru);return o>>>0},La=e=>Kn(Gn,e,0,e.length),nu=String.fromCodePoint(3),ou=String.fromCodePoint(2),au=String.fromCodePoint(1),qr=e=>La(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(nu)).join(ou)).join(au));var Na=e=>e==="intersection"||e==="union",Pe=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Jn=2,jr=2,Bt=Object.freeze({word:0,reading:1});var Qn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var qy=2*(1+Jn);var iu=require("zod/v3");var Oa=e=>e.issues.map(t=>`${t.path.length===0?"(root)":t.path.join(".")}: ${t.code}`).join("; ");var Ce=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",contentDigest:"contentDigest",commentId:"commentId"});var Wr=Math.max(1,Math.floor(10.556701030927835));var ot=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var ve=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(c=>[c,0]))};o.set(i,l),ot(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var gt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var Qy=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),su=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Xn=e=>{let t=e.trim();return t.length===0?null:t.replace(su,"\uFFFD")},lu=e=>{let t=Xn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>gt.maxValueLength?"filter-value-too-long":null},cu=e=>{if(e.length>gt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=lu(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},uu=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Ha=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=cu(t);if(r!==null)return r}return uu(e)>gt.maxTotalValueLength?"filters-too-long":null};var Fa=e=>e.trim().length===0;var Yr=e=>e!==null&&Fr.test(e)?e:null,Zn=e=>Na(e)?e:null,eo=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Pe.maxDetailIds)return null;let r=[];for(let n of t){let o=nt(n);if(o===null||r.includes(o))return null;r.push(o)}return r},$a=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},Ua=(e,t)=>{let r={authors:e.getAll(Ae.searchAuthor),sourceTypes:e.getAll(Ae.searchSourceType),customers:e.getAll(Ae.searchCustomer)},n=Ha(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:$a(r.authors),customers:$a(r.customers)}}},Ba=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var qa=Object.freeze({status:400,error:"Invalid form"}),ja=e=>({status:413,error:"Form too large",measuredBy:e}),du=(e,t,r)=>{let n=0;return e.pipeThrough(new TransformStream({transform(o,a){if(n+=o.byteLength,n>t){r(),a.error(new Error(`action form body exceeds ${t} bytes`));return}a.enqueue(o)}}))},pu=async e=>{let t=Yn(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:ja("declared")};let r=!1,n=e.body===null?null:du(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let i;try{i=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?ja("counted"):qa}}let l=Ba(i);return l===null?{refusal:qa}:{fields:l}},Ya=(e,t)=>{let r=e.get(t);if(r===null)return{error:`${t} required`};let n=zn(r);return n===null?{error:`Invalid ${t}`}:{value:n}},mu=(e,t)=>{let r=Ya(e,Ce.isStarred);return"error"in r?r:{command:{...t,intent:"toggleStar",value:r.value}}},yu=(e,t)=>{let r=Ya(e,Ce.isRead);if("error"in r)return r;let n=e.get(Ce.contentDigest);return r.value?n===null?{error:`${Ce.contentDigest} required`}:Ft(n)?{command:{...t,intent:"toggleRead",value:!0,contentDigest:n}}:{error:`Invalid ${Ce.contentDigest}`}:n===null?{command:{...t,intent:"toggleRead",value:!1}}:{error:`${Ce.contentDigest} is not allowed when ${Ce.isRead} is false`}},za=Object.freeze({update:(e,t,r)=>{let n=e.get(Ce.title),o=e.get(Ce.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:mu,toggleRead:yu,addComment:(e,t)=>{let r=e.get(Ce.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=nt(e.get(Ce.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),hu=e=>Object.hasOwn(za,e),fu=(e,t)=>{let r=e.get(Ce.intent),n=e.get(Ce.businessDate),o=n===null?null:Kt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Ce.operationTimestamp),i=Yn(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Ce.clientTempId);if(!l)return{error:"clientTempId required"};let s=Yr(l);if(s===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:i}};let c=nt(e.get(Ce.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!hu(r)?{error:"Invalid intent"}:za[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Ga=async(e,t)=>{let r=await pu(e);if("refusal"in r)return r;let n=fu(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Ru=6e4,Su="form_too_large",Wa=["declared","counted"],Ka=e=>{let t=ve({windowMs:Ru,tallies:Wa,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Wa.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(Su,r,n)}};var Vt=Object.freeze({[de.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[de.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[de.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[de.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[de.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[de.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[de.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),Ja=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),to=e=>e!==void 0&&Object.hasOwn(Vt,e);var ro=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Qa=e=>Object.hasOwn(ro,e);var gu="download",bu="thumbnail",Du="1";var no=e=>{let t=e.getAll(bu),r=e.getAll(gu);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Qa(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Du?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var ri=require("@aiquants/request-isolation");var Xa=require("crypto"),oo=e=>`"${(0,Xa.createHash)("sha256").update(e).digest("hex")}"`,Za=e=>oo(JSON.stringify(e));var ut=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),ao=(e,t)=>{if(e===null)return!1;for(let r of e.split(",")){let n=r.trim();if((n.startsWith("W/")?n.slice(2):n)===t)return!0}return!1},ei=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=oo(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...ut});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&ao(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},io=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...ut});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},so=e=>(t,r,n,o)=>{if(o!==200)return io(r,n,o);if(e===null||n===null)throw new Error(`[daily-report] API route: a 200 JSON answer needs an answer of a JSON 200 and a body; got ${e===null?"a responder without one":"an answer"} and ${n===null?"no body":"a body"}`);return e(t,r,n)},Tu=5e3/1e3,Au=new Map([[503,Tu]]),_e=e=>{let t=Au.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var co="Cross-site request rejected",Eu="Not Found",ti=["api","action","sse","attachment"],ni=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...ut}}),wu=()=>ni(403,co),zr=()=>ni(404,Eu),Dr=Object.freeze({...ri.NO_CROSS_ORIGIN_NAVIGATION,frameworkDataRefusal:()=>null,crossSiteRejection:wu}),oi=e=>new URL(e.url).pathname.endsWith(".data"),Iu=6e4,_u="refusals",xu=32,Cu=/^[a-z-]+$/,lo=e=>{if(e===null)return"-";let t=e.slice(0,xu);return Cu.test(t)&&t===e?e:JSON.stringify(t)},ai=e=>{let t=ve({windowMs:Iu,tallies:ti,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${ti.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n,o)=>{let a=()=>{let{headers:i}=o;e.warn(`cross_site_rejected route=${r} reason=${n} site=${lo(i.get("Sec-Fetch-Site"))} mode=${lo(i.get("Sec-Fetch-Mode"))} dest=${lo(i.get("Sec-Fetch-Dest"))} method=${o.method}`)};t.record(_u,r,a)}};var ii=(e,t)=>(r,n)=>{let o=n?"markAttachmentPresent":"markAttachmentMissing";e[o](r).catch(a=>{t.error(`${o} failed attachment=${r} message=${a instanceof Error?a.message:"unknown"}`)})};var Mu="same-origin",ku="SAMEORIGIN",Xt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Mu,"X-Frame-Options":ku}),Gr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Xt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},si=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Pu=/^[\x20-\x7E]+$/,vu=/^[\w.+-]+\/[\w.+-]+/,uo=e=>e&&Pu.test(e)&&vu.test(e)?e:null,Lu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,li=e=>encodeURIComponent(e.replace(Lu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),ci=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),Tr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},ui={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Kr=e=>typeof e=="string"&&Object.hasOwn(ui,e),Jr=e=>ui[e],bt="Attachment request failed";var dt=e=>{let t=ce("limit",e.limit,1),r=ce("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ce("queue.max",e.queue.max,0),maxPerOwner:ce("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ce("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(p,f)=>p.get(f)??0,c=(p,f,D)=>{let w=s(p,f)+D;w<=0?p.delete(f):p.set(f,w)},d=p=>s(l,p)<r,u=p=>o<t&&d(p),h=p=>(o+=1,c(l,p,1),R(p)),m=()=>{let p=-1,f=r;for(let[D,w]of a.entries()){let S=s(l,w.owner);if(S<f&&(p=D,f=S,S===0))break}return p},y=()=>{for(;o<t;){let p=m();if(p<0)return;let[f]=a.splice(p,1);c(i,f.owner,-1),f.grant(h(f.owner))}},R=p=>{let f=!1;return()=>{f||(f=!0,o-=1,c(l,p,-1),y())}};return{canAcquire:u,acquire:(p,f)=>{if(f.aborted)return Promise.resolve(null);if(u(p))return Promise.resolve(h(p));if(n===null||a.length>=n.max||s(i,p)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:D}=n,w=S=>{let g=()=>{let H=a.indexOf(C);H<0||(a.splice(H,1),c(i,p,-1),T(),S(null))},M=ot(g,D),T=()=>{clearTimeout(M),f.removeEventListener("abort",g)},C={owner:p,grant:H=>{T(),S(H)}};a.push(C),c(i,p,1),f.addEventListener("abort",g,{once:!0})};return new Promise(w)}}};var Nu=1024,po="Too many requests",Ou=(e,t)=>{ce("limitPerWindow",e,1),ce("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let s=l??{tokens:e,lastRefillMs:i};n(s,i),r.set(a,s);for(let c of r.keys()){if(r.size<=Nu)break;r.delete(c)}return s};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let s=r.get(a);s&&(n(s,i),s.tokens=Math.min(e,s.tokens+l))}}},Dt=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ce("windowMs",r,1e3)%1e3!==0)throw Q("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Ou(e.limitPerWindow,r),i=Object.freeze({status:429,message:po,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=ve({windowMs:r,tallies:[t],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`${t}_suppressed count=${c} since=${d} ${o(s)}`)}});return{spend:(s,c)=>a.consume(s,ue())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,ue(),c)}}};var Fu=256*1024,di=6e4,$u=e=>Math.ceil(e/2),Uu=new Uint8Array(new ArrayBuffer(0)),Bu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Uu,t()},i=l=>{clearTimeout(o),o=ot(()=>{l.error(new Error(`attachment body idle for ${di} ms`)),a()},di)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Fu,r.byteLength);if(s>n&&l.enqueue(r.slice(n,s)),n=s,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},pi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=Dt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=dt({limit:e.concurrency,maxHeldPerOwner:$u(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:h,readAttachment:m,cookie:y,fail:R}=s,p=e.maxBytes,f=i.spend(h,`attachment=${u} viewer=${h}`);if(f)return R(f.status,f.message,f.headers);let D=await n(c,"initial");if(!D.ok)return R(503,Tr[503],_e(503));let w=await t.getAttachmentForUser(D.scope,u,h);if(!w)return o.warn(`404 attachment=${u} viewer=${h} reason=not_visible`),R(404,"Attachment not found");if(w.fileSize!=null&&w.fileSize>p)return o.warn(`413 attachment=${u} viewer=${h} reason=db_size`),R(413,"Attachment too large");let S=uo(w.fileType),g=`filename="${ci(w.fileName)}"; filename*=UTF-8''${li(w.fileName)}`,M=await l.acquire(h,c.signal);if(!M)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${h} reason=aborted`),R(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${h} reason=concurrency`),R(503,"Too many concurrent downloads",_e(503)));let T=!1;try{let C=await m(w.filePath,{maxBytes:p,head:c.method==="HEAD",principal:r(h),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${h} reason=aborted`),R(503,"Attachment request aborted");if(!C.ok){if(!Kr(C.reason))return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=failure_reason`),R(500,bt);let $=Jr(C.reason);return C.reason==="not_found"&&a(u,!1),o.warn(`${$} attachment=${u} viewer=${h} reason=${C.reason} code=${C.code??"-"}`),R($,Tr[$],_e($))}if(C.bytes.byteLength>p)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),R(500,bt);let H=c.method==="HEAD";if(H&&C.size!==void 0&&C.size>p)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),R(500,bt);if(!H&&C.size!==void 0&&C.size!==C.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=size_mismatch`),R(500,bt);let I=S??uo(C.contentType),L=I!==null&&si.has(I),x=L?I:"application/octet-stream",j=L&&d.kind!=="download"?"inline":"attachment",X=H?C.size:C.bytes.byteLength,J=new Headers({"Content-Type":x,"Content-Disposition":`${j}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Xt});return X!==void 0&&J.set("Content-Length",String(X)),y&&J.append("Set-Cookie",y),a(u,!0),o.info(`200 attachment=${u} viewer=${h} type=${x} disposition=${j} bytes=${X??"-"}`),H?new Response(null,{status:200,headers:J}):(T=!0,new Response(Bu(C.bytes,M),{status:200,headers:J}))}finally{T||M()}}};var Ye=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),$h=Ye.queueWaitMs+Ye.readMs+Ye.renderMs+Ye.transferMarginMs;var hi=require("buffer"),fi=new Set([194,198,202,206]),Vu=new Set([192,193,194,195]),Ri=216,qu=217,Si=218,ju=4,Wu=64,Yu=2,mi=8,yi=28,kt=12,mo=8,zu=20,gi=kt+mo+10,Gu=2,Tt=(e,t)=>e[t]<<8|e[t+1],Zt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},pt=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},bi=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Di=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),Ti=e=>(e.stepsLeft-=1,e.stepsLeft>=0),Ai=e=>e[0]===255&&e[1]===Ri,Ei=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!Ti(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let o=e[n];if(n+=1,o===qu)return"eoi";if(o===0||o===Ri)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=Tt(e,n),i=n+a;return a<2||i>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=i,"segment")}},Ku=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!Ti(r))return null;if(a+1>=n)return n;let i=e[a+1];if(i===255)a+=1;else if(i===0||i>=208&&i<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},wi=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=Tt(e,r+1),a=Tt(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let s=0;s<i;s+=1){let c=e[r+7+3*s],d=c>>4,u=c&15;if(d<1||d>4||u<1||u>4)return null;l.push({id:e[r+6+3*s],horizontal:d,vertical:u})}return{marker:t,width:a,height:o,components:l}},Ii=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>ju||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},_i=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:fi.has(e.marker)||t<e.components.length}),yo=e=>{if(!Ai(e))return null;let t=Di(e.byteLength),r=null;for(let n=2;;){if(Ei(e,n,t)!=="segment")return null;if(bi(t.marker)){if(r!==null||(r=wi(e,t),r===null))return null}else if(t.marker===Si){if(r===null)return null;let o=Ii(e,t);return o===null?null:_i(r,o.length)}n=t.end}},xi=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:o})=>{let a=Math.ceil(e.width*n/(t*mi)),i=Math.ceil(e.height*o/(r*mi));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},Ci=e=>e.multiScan?xi(e).reduce((r,n)=>r+n,0)*Wu*Yu:0,Ju=896,Mi=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!Ai(e))return null;let n=hi.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=Di(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let h=Ei(e,u,o);if(h===null)return null;if(h==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,bi(o.marker)){if(a!==null||!Vu.has(o.marker)||(a=wi(e,o),a===null))return null;let m=xi(a);l=new Map;for(let[y,R]of a.components.entries()){let p=l.get(R.id);l.set(R.id,p===void 0?m[y]:Math.max(p,m[y]))}s=a.components.length*(fi.has(a.marker)?Ju:1)}else if(o.marker===Si){if(a===null||d===s)return null;let m=Ii(e,o);if(m===null)return null;for(let R of m){let p=l.get(R);if(p===void 0)return null;c+=p}if(d+=1,i===null&&(i=_i(a,m.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let y=Ku(n,o.end,o);if(y===null)return null;u=y}}},ki=e=>{if(e.byteLength<24||Tt(e,8)!==0||Tt(e,10)!==13||!pt(e,12,"IHDR"))return null;let t=Tt(e,16)*65536+Tt(e,18),r=Tt(e,20)*65536+Tt(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Qu=e=>{if(pt(e,kt,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Zt(e,26,2)&16383,r=Zt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(pt(e,kt,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Zt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return pt(e,kt,"VP8X")?e.byteLength<gi?null:{width:Zt(e,24,3)+1,height:Zt(e,27,3)+1}:null},Pi=e=>{if(ki(e)===null||e.byteLength<=yi)return null;switch(e[yi]){case 0:return!1;case 1:return!0;default:return null}},vi=(e,t)=>{if(pt(e,kt,"VP8 "))return"lossy";if(pt(e,kt,"VP8L"))return"lossless";if(!pt(e,kt,"VP8X")||e.byteLength<gi)return null;if((e[zu]&Gu)!==0)return"animated";let r=!1,n=t;for(let o=kt;o+mo<=e.byteLength;){if(n-=1,n<0)return null;if(pt(e,o,"VP8L"))return"lossless";if(pt(e,o,"VP8 "))return r?"lossy-alpha":"lossy";pt(e,o,"ALPH")&&(r=!0);let a=Zt(e,o+4,4);o+=mo+a+a%2}return null},Li={png:ki,jpeg:yo,webp:Qu};var Qr=Object.freeze(["image/webp","image/jpeg","image/png"]),Xr=1024*1024;var Xu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Zu={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},ed=new Set(Qr),td=e=>typeof e=="string"&&ed.has(e),rd=256,Zr=(e,t)=>e.fileType===null||!Xu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,nd=[137,80,78,71,13,10,26,10],od=[255,216,255],ad=[[71,73,70,56,55,97],[71,73,70,56,57,97]],id=[82,73,70,70],sd=[87,69,66,80],Ar=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,o]of t.entries())if(e[r+n]!==o)return!1;return!0},ho=e=>{if(Ar(e,nd,0))return"png";if(Ar(e,od,0))return"jpeg";for(let t of ad)if(Ar(e,t,0))return"gif";return Ar(e,id,0)&&Ar(e,sd,8)?"webp":null},Ni=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:Za([t])}},Oi=(e,t)=>{if(!td(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Xr)return"too_large";let r=Zu[e.contentType];if(ho(e.bytes)!==r)return"signature";let n=Li[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Hi=e=>{ce("maxBytes",e.maxBytes,0),ce("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+rd;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let s of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(s)}}}};var fo=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ue(),l=new AbortController,s=!1,c,d,u=()=>{a(ue()-i)},h=S=>{c=ot(()=>{s=!0,S({timedOut:!0}),d=ot(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},m=new Promise(h),y=AbortSignal.any([r,l.signal]),R=S=>{S(n(y))},p=new Promise(R),f=S=>(clearTimeout(c),clearTimeout(d),s&&o(ue()-i,S.kind==="error"?{error:S.error}:null),S),D=p.then(S=>f({kind:"value",value:S}),S=>f({kind:"error",error:S}));return{outcome:Promise.race([p.then(S=>({timedOut:!1,value:S})),m]),settled:D}};var At={404:"Attachment not found",500:bt,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Fi=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=Oi(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},ld=e=>{let t=new AbortController,r=()=>{t.abort()},n=ot(r,Ye.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},$i=()=>{},cd=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),Ui=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(m,y)=>{let R=y.then($i,$i);l.set(m,R);let p=()=>{l.get(m)===R&&l.delete(m)};R.then(p)},c=async(m,y)=>{let R=l.get(m.key);if(R===void 0)return t.acquire(m.owner,y);let p=ld(y);try{if(await cd(R,p.signal),p.signal.aborted)return null;let f=r.get(m.key);return f!==void 0?{...f,identity:"verified"}:await t.acquire(m.owner,p.signal)}finally{p.end()}},d=(m,y)=>{if(m.fileSize===null)return y.kind==="exact"?"verified":"unrecorded";if(y.kind==="exact"?y.bytes===m.fileSize:m.fileSize>y.maxBytes)return"verified";let p=y.kind==="exact"?String(y.bytes):`>${y.maxBytes}`;return i.warn(`size_mismatch expected=${m.fileSize} got=${p} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`),"unverified"},u=(m,y)=>(R,p)=>{let f=p===null?"":` message=${p.error instanceof Error?p.error.message:"unknown"}`;i.warn(`${m}_overrun ms=${R} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail${f}`)},h=(m,y)=>R=>{i.warn(`${m}_stuck ms=${R} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail`)};return async(m,y)=>{let R=await c(m,y);if(R===null)return{kind:"failure",status:503,reason:y.aborted?"aborted":"queue"};if(typeof R!="function")return R;let p=R,f=null;try{if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let D=r.get(m.key);if(D!==void 0)return{...D,identity:"verified"};let w=fo({budgetMs:Ye.readMs,flightSignal:y,call:$=>m.readAttachment(m.filePath,{maxBytes:n,head:!1,principal:o(m.owner),signal:$}),onOverrun:u("read",m),onStuck:h("read",m)}),S=await w.outcome;if(S.timedOut)return f=w.settled,y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=S.value;if(!g.ok&&g.reason!=="too_large")return Kr(g.reason)?(g.reason==="not_found"&&a(m.attachmentId,!1),{kind:"failure",status:Jr(g.reason),reason:g.reason,code:g.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(g.ok&&g.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let M=d(m,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),T=$=>{M==="verified"&&r.set(m.key,$)},C=$=>(T($),{...$,identity:M});if(!g.ok)return C({kind:"unrenderable",reason:"too_large"});let H=ho(g.bytes);if(H===null)return C({kind:"unrenderable",reason:"signature"});let I=fo({budgetMs:Ye.renderMs,flightSignal:y,call:$=>m.renderer.render(g.bytes,{format:H,maxWidth:m.box.maxWidth,maxHeight:m.box.maxHeight,signal:$}),onOverrun:u("render",m),onStuck:h("render",m)}),L=$=>{if($.kind==="error")return;let _=Fi($.value,m.box);"entry"in _&&T(_.entry)},x=null,j=()=>(x===null&&(x=I.settled.then(L),s(m.key,x)),x);y.addEventListener("abort",j,{once:!0});let X=await I.outcome.finally(()=>y.removeEventListener("abort",j));if(X.timedOut||y.aborted)return f=j(),y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let J=Fi(X.value,m.box);return"entry"in J?C(J.entry):J.failure}finally{f===null?p():f.then(p,p)}}};var Bi=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let s=new AbortController,c=()=>{e.get(t)?.controller===s&&e.delete(t)},u={promise:n(s.signal).finally(c),controller:s,waiters:0};return e.set(t,u),u},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var ji=10,ud=1/ji,Vi=1-ud,dd=1024,pd=64,md=8,qi="private, no-cache",yd="no-store",hd=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),fd=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Wi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(S,g)=>Dt({reason:S,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:M=>`viewer=${M} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*ji),h=dt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:pd,maxPerOwner:md,maxWaitMs:Ye.queueWaitMs}}),m=Hi({maxBytes:l.cacheBytes,maxEntries:dd}),y=Bi(),R=Ui({gate:h,cache:m,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),p=(S,g,M,T)=>{let C=`attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail cache=${T}`;if(g.kind==="failure")return o[fd(g)](`${g.status} ${C} reason=${g.reason} code=${g.code??"-"}`),S.fail(g.status,At[g.status],_e(g.status));let H=hd[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${C} reason=${g.reason}${H}`),S.fail(404,At[404]);let I=g.identity==="verified"?{"Cache-Control":qi,ETag:M}:{"Cache-Control":yd},L=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...I,"Content-Security-Policy":"default-src 'none'; sandbox",...Xt});return S.cookie&&L.append("Set-Cookie",S.cookie),o.info(`200 ${C} type=${g.contentType} bytes=${g.bytes.byteLength}${H}`),new Response(g.bytes,{status:200,headers:L})},f=(S,g)=>{let M=S.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return M===null?null:g.fail(M.status,M.message,M.headers)},D=S=>f(d,S),w=(S,g)=>g?f(u,S):D(S);return async(S,g)=>{let{request:M,attachmentId:T,internalUserId:C,readAttachment:H,cookie:I,fail:L}=S,x=ro[g],j=M.headers.get("If-None-Match"),X=j!==null,J=w(S,X);if(J)return J;let $=await n(M,"initial");if(!$.ok)return L(503,At[503],_e(503));let _=await t.getAttachmentForUser($.scope,T,C),Y=_!==null&&Zr(_,i)?Ni({rendererId:s.id,box:x,attachmentId:T,filePath:_.filePath,fileType:_.fileType,fileSize:_.fileSize}):null;if(Y&&ao(j,Y.etag)){let b=new Headers({"Cache-Control":qi,ETag:Y.etag,...Xt});return I&&b.append("Set-Cookie",I),o.info(`304 attachment=${T} viewer=${C} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:b})}if(X){let b=D(S);if(b)return b}if(!_)return o.warn(`404 attachment=${T} viewer=${C} variant=thumbnail reason=not_visible`),L(404,At[404]);if(!Y)return d.refund(C,Vi),o.info(`404 attachment=${T} viewer=${C} variant=thumbnail reason=not_eligible`),L(404,At[404]);let{key:pe,etag:ie}=Y,me=m.get(pe);if(me)return d.refund(C,Vi),p(S,{...me,identity:"verified"},ie,"hit");let De=b=>R({key:pe,attachmentId:T,filePath:_.filePath,fileSize:_.fileSize,box:x,owner:C,readAttachment:H,renderer:s},b),Z;try{Z=await y.join(pe,M.signal,De)}catch(b){return o.error(`500 attachment=${T} viewer=${C} variant=thumbnail cache=miss reason=port_exception message=${b instanceof Error?b.message:"unknown"}`),L(500,At[500])}return p(S,Z,ie,"miss")}};var Rd='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Sd=()=>Gr(403,co,{cookie:null}),Yi=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=no(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Gr(404,Tr[404],{cookie:null}),crossSiteRejection:Sd}),zi=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,i=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:ii(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:pi({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Wi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,h=(m,y,R={})=>Gr(m,y,{cookie:u,extraHeaders:R});try{let{user:m,cookie:y}=await t(c,{failureRedirect:null});if(u=y??null,!m)return h(401,"Unauthorized");let R=no(new URL(c.url).searchParams);if(R.kind==="invalid")return h(400,"Invalid attachment request");if(R.kind==="thumbnail"&&c.method!=="GET")return h(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return h(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return h(404,"Attachment not found");if(d.token===void 0)throw new Error(Rd);let p=s.idCodec.decode(d.token);if(p===null||!ct(p))return h(400,"Invalid attachment token");let f=await r.getUserIdByExternalId(m.id);if(!f)return h(403,"Forbidden");let D={request:c,delivery:R,attachmentId:p,internalUserId:f,readAttachment:s.read,cookie:u,fail:h};return R.kind!=="thumbnail"?await s.serveOriginal(D):s.serveThumbnail===null?h(404,At[404]):await s.serveThumbnail(D,R.variant)}catch(m){if(m instanceof Response)throw m;return a.error(`500 attachment=? viewer=? reason=unexpected message=${m instanceof Error?m.message:"unknown"}`),h(500,bt)}}};var gd=32*1024*1024,bd=60,Dd=4,Td=120,Ad=2,Ed=8*1024*1024,en=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wd=e=>{if(e===void 0)throw Je("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!en(e))throw Q("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Je("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw Q("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Q("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Id=e=>{if(e===void 0)return null;if(!en(e))throw Q("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:wd(e.renderer),rateLimitPerMinute:Oe("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Td),concurrency:Oe("attachments.thumbnails.concurrency",e.concurrency,1,Ad),cacheBytes:Oe("attachments.thumbnails.cacheBytes",e.cacheBytes,0,Ed)})},Gi=e=>{let t=e;if(t===void 0)return null;if(!en(t))throw Q("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Je("attachments.idCodec","injected when attachments is given");if(!en(r)||typeof r.encode!="function"||typeof r.decode!="function")throw Q("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Je("attachments.read","injected when attachments is given");if(typeof n!="function")throw Q("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Oe("attachments.maxBytes",t.maxBytes,1,gd),rateLimitPerMinute:Oe("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,bd),concurrency:Oe("attachments.concurrency",t.concurrency,1,Dd),thumbnails:Id(t.thumbnails)})},_d=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),tn=e=>{for(let[t,r]of _d)if(Object.hasOwn(e,t))throw Je(r,`given in place of the flat key ${t}`)};var Ji=8,xd=8*Ji,Cd=128,Md=2,Qi=Md*Cd,kd=4*Qi,Pd=6e4,vd=6e4,Ld="Too many reads",Ki=Object.freeze(Object.keys(Vt).filter(e=>Vt[e].admission.includes("miss-gate"))),Xi=e=>{let t=dt({limit:xd,maxHeldPerOwner:Ji,queue:{max:kd,maxPerOwner:Qi,maxWaitMs:Pd}}),r=ve({windowMs:vd,tallies:Ki,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Ki.map(l=>`${l}:${i[l]}`).join(",")}`)}});return{admissionFor:(n,o,a)=>({signal:a,acquire:async i=>{let l=await t.acquire(n,i);return l===null&&!i.aborted&&r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=cache_miss_admission`)),l}})}},rn=(e,t,r)=>{let n=e(t,r,{error:{message:Ld}},503);for(let[o,a]of Object.entries(_e(503)))n.headers.set(o,a);return n};var Zi=e=>{let t=e.get(Ae.cursorReportHubId),r=e.get(Ae.cursorBusinessDate),n=e.get(Ae.cursorSnapshot),o=_a(n)?n:null,a=null;if(t!==null){let l=nt(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!Ia(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=br(e.get(Ae.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var nn=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Nd=2,Od=16,Hd=Nd*Od,Fd=6e4,es=()=>{},$d=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},ts=e=>{let t=dt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Hd,queue:null}),r=ve({windowMs:Fd,tallies:["sse","ids-stream"],writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`streams_per_viewer_suppressed count=${o} since=${a} viewer=${n} routes=sse:${i.sse},ids-stream:${i["ids-stream"]}`)}});return{admit:async(n,o,a)=>{if(n===null)return es;if(a.aborted){if(t.canAcquire(n))return es}else{let i=await t.acquire(n,a);if(i!==null)return $d(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var on=30,is=4e3,Ud="stream interrupted by server error",Bd="Too many streams",Vd=15e3,ss=Symbol("ids-stream-heartbeat"),rs=()=>{},ns=e=>e.return(void 0).then(rs,rs),qd=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(ss),Vd)}),stop:()=>clearTimeout(e)}};async function*os(e,t,r,n){let o=t?Ma(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:is),e.length),l=Ut(e,o,i),s=i>o?e[i-1]:void 0;o=i;let c=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:c||s===void 0?null:{businessDate:s.businessDate,reportHubId:s.reportHubId},isLast:c,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,c)return}}var ls=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...ut});return e&&t.append("Set-Cookie",e),t},as=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await ns(t);try{d.close()}catch{}},i=new TextEncoder,l=!1,s=null,c=new ReadableStream({async pull(d){if(l||r.aborted){await a(d,!0);return}let u=qd();try{s===null&&(s=t.next());let h=await Promise.race([s,u.fired]);if(u.stop(),h===ss){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
1
|
+
"use strict";var xn=Object.defineProperty;var Tc=Object.getOwnPropertyDescriptor;var Ac=Object.getOwnPropertyNames;var Ec=Object.prototype.hasOwnProperty;var Xo=e=>{throw TypeError(e)};var wc=(e,t)=>{for(var r in t)xn(e,r,{get:t[r],enumerable:!0})},Ic=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ac(t))!Ec.call(e,o)&&o!==r&&xn(e,o,{get:()=>t[o],enumerable:!(n=Tc(t,o))||n.enumerable});return e};var _c=e=>Ic(xn({},"__esModule",{value:!0}),e);var Zo=(e,t,r)=>t.has(e)||Xo("Cannot "+r);var cr=(e,t,r)=>(Zo(e,t,"read from private field"),r?r.call(e):t.get(e)),Cn=(e,t,r)=>t.has(e)?Xo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Mn=(e,t,r,n)=>(Zo(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var ny={};wc(ny,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>Xr,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>Qr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>Yo,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Nr,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>zo,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>mn,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>ko,DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS:()=>Go,DailyReportSseReader:()=>ar,DailyReportViewerScope:()=>Xe,SqlResultCache:()=>Gt,buildDailyReportRedisKeys:()=>Tn,createDailyReportHandlers:()=>yn,createDailyReportServer:()=>ry,createDailyReportService:()=>In,createDailyReportVisibilityCache:()=>hc,createEpochStore:()=>Or,createSharpThumbnailRenderer:()=>yc,dailyReportSseStreamMessageSchema:()=>Br,defineDailyReportSchema:()=>Xl,defineDailyReportSearchSchema:()=>Zl,encodeIdsStreamRows:()=>Ut,isStreamIdLte:()=>mt,parseClientTempId:()=>Yr,predictSharpThumbnailWorkingSetBytes:()=>mc,readDailyReportSseStreamEntry:()=>rr,transformJsonArray:()=>Ql});module.exports=_c(ny);var Ht=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,Q=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Ht(r)}`),Je=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),kn=(e,t,r)=>Q(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ce=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw Q(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},Oe=(e,t,r,n)=>t===void 0?n:ce(e,t,r),ur=(e,t)=>{if(t===void 0)throw Je(e,"a function");if(typeof t!="function")throw Q(e,"a function",t);return t};var ue=()=>Math.floor(performance.now());var Pn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),rt=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},Or=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),dr=(e,t)=>t?e.map(r=>structuredClone(r)):e,xc=8,Cc=32,Mc=24,kc=16,Pc=-(2**30),vc=2**30-1,Lc=e=>Number.isInteger(e)&&e>=Pc&&e<=vc&&!Object.is(e,-0),Nc=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=Cc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=xc*a.length;for(let i of a)typeof i=="string"?r+=Mc+2*i.length:typeof i=="number"&&!Lc(i)?r+=kc:typeof i=="object"&&i!==null&&n.push(i)}return r},Gt=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-ue())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:c,expireAt:ue()+a,epoch:s}),c})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&s===null)throw new rt(o.signal.aborted?"aborted":"busy");try{for(let d of r)d();let c=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:c,expireAt:ue()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),c}finally{s?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new rt("aborted");return this.dropBucket(r),dr(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ue())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),dr(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),dr(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return dr(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new rt("aborted");return dr(await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};this.readOwnOrRetry=async(t,r)=>{try{return await t}catch(n){let{admission:o}=r;if(!(n instanceof rt&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.totalBytes=0,this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.dropBucket(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=Oe("cacheDefaultTtlMs",t.defaultTtlMs,1,Pn.defaultTtlMs),this.maxBuckets=Oe("cacheMaxBuckets",t.maxBuckets,1,Pn.maxBuckets),this.maxBytes=Oe("cacheMaxBytes",t.maxBytes,1,Pn.maxBytes),this.lastSweepAt=ue()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=Nc(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=ue();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};var rl=require("@aiquants/request-isolation");var Oc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var ea=e=>e<10?`0${e}`:`${e}`,Hc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=ea(e.getMonth()+1),n=ea(e.getDate());return`${t}-${r}-${n}`},Kt=e=>{let t=Oc.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let s=new Date(0);return s.setUTCFullYear(a,i-1,l),s.getUTCFullYear()!==a||s.getUTCMonth()!==i-1||s.getUTCDate()!==l?null:`${r}-${n}-${o}`},Hr=e=>Kt(e)===e;var We=e=>e==null?null:e instanceof Date?Hc(e):Kt(e);var ta=require("zod/v3"),ct=e=>Number.isSafeInteger(e)&&e>0,He=ta.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var re=require("zod/v3");var Fr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;var vn=/^[0-9a-f]{64}$/u;var Ft=e=>typeof e=="string"&&vn.test(e);var $t=Symbol("daily-report wire mismatch"),Qe=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),$t),aa=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,xt=(e,t)=>({code:"invalid_type",expected:e,received:aa(t)}),Fc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$c=e=>{let t=0;for(let r in e)t+=1;return t},ra=(e,t,r)=>{let n={};for(let o=0;o<r;o+=1){let a=t[o];a in e&&(n[a]=e[a])}return n},Jt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!Fc(n))return Qe(o,null,xt("object",n));let a=null,i=!1,l=0;for(let s=0;s<t.length;s+=1){let c=t[s],d=n[c];d!==void 0&&(l+=1);let u=r[s](d,o,c);if(u===$t){i=!0;continue}a===null&&u!==d&&(a=ra(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?$t:a!==null?a:$c(n)===l?n:ra(n,t,t.length)}},pr=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},mr=e=>(t,r,n)=>{if(!Array.isArray(t))return Qe(r,n,xt("array",t));r.path.push(n);let o=t,a=!1;for(let i=0;i<t.length;i+=1){let l=t[i],s=e(l,r,i);s===$t?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?$t:o},ye=(e,t,r)=>e==null||typeof e=="string"?e:Qe(t,r,xt("string",e)),na=(e,t,r)=>e===null||typeof e=="string"?e:Qe(t,r,xt("string",e)),oa=(e,t,r)=>typeof e=="string"?e:Qe(t,r,xt("string",e)),Uc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:Qe(t,r,xt("number",e)),yr=(e,t,r)=>typeof e=="boolean"?e:Qe(t,r,xt("boolean",e)),ia=(e,t,r)=>typeof e!="string"?Qe(t,r,xt("string",e)):Ft(e)?e:Qe(t,r,{code:"invalid_string",validation:"regex",message:"a content digest is 64 lowercase hex digits"}),Bc=(e,t,r)=>e===null?null:ia(e,t,r),Ln=(e,t,r)=>{if(typeof e=="number"&&ct(e))return e;for(let{message:n,path:o,...a}of He.safeParse(e).error.issues)Qe(t,r,a);return $t},sa={present:!0,absent:!0,unknown:!0},la=Object.keys(sa),Vc=la.map(e=>`'${e}'`).join(" | "),qc=(e,t,r)=>typeof e!="string"?Qe(t,r,{code:"invalid_type",expected:Vc,received:aa(e)}):Object.hasOwn(sa,e)?e:Qe(t,r,{code:"invalid_enum_value",received:e,options:[...la]}),ca=Jt({name:ye,affiliation:ye}),ua=Jt({name:ye,text:ye,color:ye}),da=Jt({id:Ln,name:ye,color:ye}),pa=Jt({id:Ln,userId:ye,userName:ye,content:ye,createdAt:ye,isMine:yr}),jc=Jt({id:oa,fileName:oa,fileType:na,fileSize:Uc,createdAt:na,state:qc,hasThumbnail:yr}),Wc=Jt({reportHubId:Ln,date:ye,createdAt:ye,author:ye,userId:ye,sourceType:ye,employeeName:ye,updatedBy:ye,updatedAt:ye,category:ye,creationCategory:ye,visitTimeFrom:ye,visitTimeTo:ye,customerName:ye,interviewers:mr(pr(ca)),subject:ye,content:ye,externalComments:mr(pr(ua)),isRead:yr,isStarred:yr,contentDigest:ia,readContentDigest:Bc,isDraft:yr,labels:mr(pr(da)),postedComments:mr(pr(pa)),attachments:mr(pr(jc))}),hr=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===$t?{ok:!1,issues:r.issues}:{ok:!0,value:n}},ma=e=>hr(Wc,e),ya=e=>hr(ca,e),ha=e=>hr(ua,e),fa=e=>hr(da,e),Ra=e=>hr(pa,e);var Sa=15e3,ga="lastEventId",Yc=/^\d{1,15}-\d{1,15}$/,ba=e=>Yc.test(e),Ct="0-0",fr=e=>re.z.unknown().transform((t,r)=>{let n=e(t);if(n.ok)return n.value;for(let o of n.issues)r.addIssue({...o,fatal:!0});return re.z.NEVER}),Dy=fr(ya),Ty=fr(ha),Ay=fr(fa),zc=fr(Ra),Rr=fr(ma),Sr=re.z.string().regex(Fr),Da=re.z.object({type:re.z.literal("connected")}),Ta=re.z.object({type:re.z.literal("status-update"),reportHubId:He,statusType:re.z.enum(["star","read"]),value:re.z.boolean(),readContentDigest:re.z.string().regex(vn).nullable(),clientTempId:Sr}),Nn=re.z.string(),Aa=re.z.object({type:re.z.literal("comment-add"),reportHubId:He,comment:zc,clientTempId:Sr,sourceType:Nn}),Ea=re.z.object({type:re.z.literal("comment-delete"),reportHubId:He,commentId:He,clientTempId:Sr,sourceType:Nn}),$r={recipientRawUserId:He.optional()},On=Ta.extend($r),Hn=Aa.extend($r),Fn=Ea.extend($r),Qt={reportHubId:He,report:Rr,clientTempId:Sr},$n={...$r,actorRawUserId:He},Un={viewerIsActor:re.z.boolean()},Gc=re.z.object({type:re.z.literal("report-create"),...Qt,...Un}),Kc=re.z.object({type:re.z.literal("report-update"),...Qt,...Un}),Jc=re.z.object({type:re.z.literal("report-publish"),...Qt,...Un}),Bn=re.z.object({type:re.z.literal("report-create"),...Qt,...$n}),Vn=re.z.object({type:re.z.literal("report-update"),...Qt,...$n}),qn=re.z.object({type:re.z.literal("report-publish"),...Qt,...$n}),Ur=re.z.object({type:re.z.literal("report-delete"),reportHubId:He,clientTempId:Sr,sourceType:Nn}),Ey=re.z.discriminatedUnion("type",[Da,Ta,Aa,Ea,Gc,Kc,Jc,Ur]),Br=re.z.discriminatedUnion("type",[Da,On,Hn,Fn,Bn,Vn,qn,Ur]);var wa="ids-columns";var Qc=/^[0-9a-f]{1,16}$/,Ia=e=>ct(e.reportHubId)&&(e.businessDate===null||Hr(e.businessDate)),_a=e=>typeof e=="string"&&Qc.test(e),xy=Object.freeze({kind:"absent"}),Cy=Object.freeze({kind:"value",value:null});var Ut=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:h}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let m=h===void 0?null:h,y=s.get(m);y===void 0&&(y=i.length,i.push(m),s.set(m,y)),l.push(y)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},Vr=e=>{let t=2166136261,r=-624069552;for(let n of e){let o=n.reportHubId;t^=o&255,t=Math.imul(t,16777619),t^=o>>>8&255,t=Math.imul(t,16777619),t^=o>>>16&255,t=Math.imul(t,16777619),t^=o>>>24&255,t=Math.imul(t,16777619),r^=o>>>24&255,r=Math.imul(r,16777619),r^=o>>>16&255,r=Math.imul(r,16777619),r^=o>>>8&255,r=Math.imul(r,16777619),r^=o&255,r=Math.imul(r,16777619);let a=n.businessDate;if(a===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let i=0;i<a.length;i++){let l=a.charCodeAt(i);t^=l&255,t=Math.imul(t,16777619),r^=l&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},xa=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Xc=(e,t,r,n)=>xa(e,t,r,n)<0,jn=(e,t)=>xa(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Ca=e=>{for(let t=1;t<e.length;t++)if(!Xc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},Ma=(e,t)=>{let r=e.findIndex(n=>jn({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var de=Object.freeze({businessDate:"business-date",idsStream:wa,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),Ae=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var ka=(e,t,r=console)=>{let n=o=>typeof o=="string"?[`${t} ${o}`]:[t,o];return{debug:(o,...a)=>{e<=0&&r.debug(...n(o),...a)},info:(o,...a)=>{e<=1&&r.info(...n(o),...a)},warn:(o,...a)=>{e<=2&&r.warn(...n(o),...a)},error:(o,...a)=>{e<=3&&r.error(...n(o),...a)}}},vy=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection","SessionGate"]),Pa=e=>`[DailyReport${e}]`,Ee=(e,t,r)=>e===void 0?ka(t,Pa(r)):ka(0,Pa(r),e);var Mt=require("zod/v3");var gr=e=>({reportHubId:e,outcome:"not_found"}),Hy=Mt.z.discriminatedUnion("outcome",[Mt.z.object({reportHubId:He,outcome:Mt.z.literal("ok"),report:Rr}).strict(),Mt.z.object({reportHubId:He,outcome:Mt.z.literal("not_found")}).strict(),Mt.z.object({reportHubId:He,outcome:Mt.z.literal("failed")}).strict()]);var Zc="legacy-",Wn=e=>`${Zc}${e}`;var eu=/^[1-9][0-9]*$/,tu=/^(?:0|[1-9][0-9]*)$/,nt=e=>{if(e===null||!eu.test(e))return null;let t=Number(e);return ct(t)?t:null},Yn=e=>{if(e===null||!tu.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},zn=e=>e==="true"?!0:e==="false"?!1:null,br=e=>e===null?!1:zn(e);var va=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),St=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var ru=16777619,Gn=2166136261,Kn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,ru);return o>>>0},La=e=>Kn(Gn,e,0,e.length),nu=String.fromCodePoint(3),ou=String.fromCodePoint(2),au=String.fromCodePoint(1),qr=e=>La(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(nu)).join(ou)).join(au));var Na=e=>e==="intersection"||e==="union",Pe=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Jn=2,jr=2,Bt=Object.freeze({word:0,reading:1});var Qn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var qy=2*(1+Jn);var iu=require("zod/v3");var Oa=e=>e.issues.map(t=>`${t.path.length===0?"(root)":t.path.join(".")}: ${t.code}`).join("; ");var Ce=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",contentDigest:"contentDigest",commentId:"commentId"});var Wr=Math.max(1,Math.floor(10.556701030927835));var ot=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var ve=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(c=>[c,0]))};o.set(i,l),ot(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var gt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var Qy=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),su=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Xn=e=>{let t=e.trim();return t.length===0?null:t.replace(su,"\uFFFD")},lu=e=>{let t=Xn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>gt.maxValueLength?"filter-value-too-long":null},cu=e=>{if(e.length>gt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=lu(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},uu=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Ha=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=cu(t);if(r!==null)return r}return uu(e)>gt.maxTotalValueLength?"filters-too-long":null};var Fa=e=>e.trim().length===0;var Yr=e=>e!==null&&Fr.test(e)?e:null,Zn=e=>Na(e)?e:null,eo=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Pe.maxDetailIds)return null;let r=[];for(let n of t){let o=nt(n);if(o===null||r.includes(o))return null;r.push(o)}return r},$a=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},Ua=(e,t)=>{let r={authors:e.getAll(Ae.searchAuthor),sourceTypes:e.getAll(Ae.searchSourceType),customers:e.getAll(Ae.searchCustomer)},n=Ha(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:$a(r.authors),customers:$a(r.customers)}}},Ba=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var qa=Object.freeze({status:400,error:"Invalid form"}),ja=e=>({status:413,error:"Form too large",measuredBy:e}),du=(e,t,r)=>{let n=0;return e.pipeThrough(new TransformStream({transform(o,a){if(n+=o.byteLength,n>t){r(),a.error(new Error(`action form body exceeds ${t} bytes`));return}a.enqueue(o)}}))},pu=async e=>{let t=Yn(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:ja("declared")};let r=!1,n=e.body===null?null:du(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let i;try{i=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?ja("counted"):qa}}let l=Ba(i);return l===null?{refusal:qa}:{fields:l}},Ya=(e,t)=>{let r=e.get(t);if(r===null)return{error:`${t} required`};let n=zn(r);return n===null?{error:`Invalid ${t}`}:{value:n}},mu=(e,t)=>{let r=Ya(e,Ce.isStarred);return"error"in r?r:{command:{...t,intent:"toggleStar",value:r.value}}},yu=(e,t)=>{let r=Ya(e,Ce.isRead);if("error"in r)return r;let n=e.get(Ce.contentDigest);return r.value?n===null?{error:`${Ce.contentDigest} required`}:Ft(n)?{command:{...t,intent:"toggleRead",value:!0,contentDigest:n}}:{error:`Invalid ${Ce.contentDigest}`}:n===null?{command:{...t,intent:"toggleRead",value:!1}}:{error:`${Ce.contentDigest} is not allowed when ${Ce.isRead} is false`}},za=Object.freeze({update:(e,t,r)=>{let n=e.get(Ce.title),o=e.get(Ce.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:mu,toggleRead:yu,addComment:(e,t)=>{let r=e.get(Ce.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=nt(e.get(Ce.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),hu=e=>Object.hasOwn(za,e),fu=(e,t)=>{let r=e.get(Ce.intent),n=e.get(Ce.businessDate),o=n===null?null:Kt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Ce.operationTimestamp),i=Yn(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Ce.clientTempId);if(!l)return{error:"clientTempId required"};let s=Yr(l);if(s===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:i}};let c=nt(e.get(Ce.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!hu(r)?{error:"Invalid intent"}:za[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Ga=async(e,t)=>{let r=await pu(e);if("refusal"in r)return r;let n=fu(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Ru=6e4,Su="form_too_large",Wa=["declared","counted"],Ka=e=>{let t=ve({windowMs:Ru,tallies:Wa,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Wa.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(Su,r,n)}};var Vt=Object.freeze({[de.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[de.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[de.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[de.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[de.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[de.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[de.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),Ja=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),to=e=>e!==void 0&&Object.hasOwn(Vt,e);var ro=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Qa=e=>Object.hasOwn(ro,e);var gu="download",bu="thumbnail",Du="1";var no=e=>{let t=e.getAll(bu),r=e.getAll(gu);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Qa(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Du?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var ri=require("@aiquants/request-isolation");var Xa=require("crypto"),oo=e=>`"${(0,Xa.createHash)("sha256").update(e).digest("hex")}"`,Za=e=>oo(JSON.stringify(e));var ut=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),ao=(e,t)=>{if(e===null)return!1;for(let r of e.split(",")){let n=r.trim();if((n.startsWith("W/")?n.slice(2):n)===t)return!0}return!1},ei=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=oo(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...ut});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&ao(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},io=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...ut});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},so=e=>(t,r,n,o)=>{if(o!==200)return io(r,n,o);if(e===null||n===null)throw new Error(`[daily-report] API route: a 200 JSON answer needs an answer of a JSON 200 and a body; got ${e===null?"a responder without one":"an answer"} and ${n===null?"no body":"a body"}`);return e(t,r,n)},Tu=5e3/1e3,Au=new Map([[503,Tu]]),_e=e=>{let t=Au.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var co="Cross-site request rejected",Eu="Not Found",ti=["api","action","sse","attachment"],ni=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...ut}}),wu=()=>ni(403,co),zr=()=>ni(404,Eu),Dr=Object.freeze({...ri.NO_CROSS_ORIGIN_NAVIGATION,frameworkDataRefusal:()=>null,crossSiteRejection:wu}),oi=e=>new URL(e.url).pathname.endsWith(".data"),Iu=6e4,_u="refusals",xu=32,Cu=/^[a-z-]+$/,lo=e=>{if(e===null)return"-";let t=e.slice(0,xu);return Cu.test(t)&&t===e?e:JSON.stringify(t)},ai=e=>{let t=ve({windowMs:Iu,tallies:ti,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${ti.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n,o)=>{let a=()=>{let{headers:i}=o;e.warn(`cross_site_rejected route=${r} reason=${n} site=${lo(i.get("Sec-Fetch-Site"))} mode=${lo(i.get("Sec-Fetch-Mode"))} dest=${lo(i.get("Sec-Fetch-Dest"))} method=${o.method}`)};t.record(_u,r,a)}};var ii=(e,t)=>(r,n)=>{let o=n?"markAttachmentPresent":"markAttachmentMissing";e[o](r).catch(a=>{t.error(`${o} failed attachment=${r} message=${a instanceof Error?a.message:"unknown"}`)})};var Mu="same-origin",ku="SAMEORIGIN",Xt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Mu,"X-Frame-Options":ku}),Gr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Xt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},si=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Pu=/^[\x20-\x7E]+$/,vu=/^[\w.+-]+\/[\w.+-]+/,uo=e=>e&&Pu.test(e)&&vu.test(e)?e:null,Lu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,li=e=>encodeURIComponent(e.replace(Lu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),ci=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),Tr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},ui={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Kr=e=>typeof e=="string"&&Object.hasOwn(ui,e),Jr=e=>ui[e],bt="Attachment request failed";var dt=e=>{let t=ce("limit",e.limit,1),r=ce("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ce("queue.max",e.queue.max,0),maxPerOwner:ce("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ce("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(p,f)=>p.get(f)??0,c=(p,f,D)=>{let w=s(p,f)+D;w<=0?p.delete(f):p.set(f,w)},d=p=>s(l,p)<r,u=p=>o<t&&d(p),h=p=>(o+=1,c(l,p,1),R(p)),m=()=>{let p=-1,f=r;for(let[D,w]of a.entries()){let S=s(l,w.owner);if(S<f&&(p=D,f=S,S===0))break}return p},y=()=>{for(;o<t;){let p=m();if(p<0)return;let[f]=a.splice(p,1);c(i,f.owner,-1),f.grant(h(f.owner))}},R=p=>{let f=!1;return()=>{f||(f=!0,o-=1,c(l,p,-1),y())}};return{canAcquire:u,acquire:(p,f)=>{if(f.aborted)return Promise.resolve(null);if(u(p))return Promise.resolve(h(p));if(n===null||a.length>=n.max||s(i,p)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:D}=n,w=S=>{let g=()=>{let H=a.indexOf(C);H<0||(a.splice(H,1),c(i,p,-1),T(),S(null))},M=ot(g,D),T=()=>{clearTimeout(M),f.removeEventListener("abort",g)},C={owner:p,grant:H=>{T(),S(H)}};a.push(C),c(i,p,1),f.addEventListener("abort",g,{once:!0})};return new Promise(w)}}};var Nu=1024,po="Too many requests",Ou=(e,t)=>{ce("limitPerWindow",e,1),ce("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let s=l??{tokens:e,lastRefillMs:i};n(s,i),r.set(a,s);for(let c of r.keys()){if(r.size<=Nu)break;r.delete(c)}return s};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let s=r.get(a);s&&(n(s,i),s.tokens=Math.min(e,s.tokens+l))}}},Dt=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ce("windowMs",r,1e3)%1e3!==0)throw Q("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Ou(e.limitPerWindow,r),i=Object.freeze({status:429,message:po,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=ve({windowMs:r,tallies:[t],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`${t}_suppressed count=${c} since=${d} ${o(s)}`)}});return{spend:(s,c)=>a.consume(s,ue())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,ue(),c)}}};var Fu=256*1024,di=6e4,$u=e=>Math.ceil(e/2),Uu=new Uint8Array(new ArrayBuffer(0)),Bu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Uu,t()},i=l=>{clearTimeout(o),o=ot(()=>{l.error(new Error(`attachment body idle for ${di} ms`)),a()},di)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Fu,r.byteLength);if(s>n&&l.enqueue(r.slice(n,s)),n=s,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},pi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=Dt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=dt({limit:e.concurrency,maxHeldPerOwner:$u(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:h,readAttachment:m,cookie:y,fail:R}=s,p=e.maxBytes,f=i.spend(h,`attachment=${u} viewer=${h}`);if(f)return R(f.status,f.message,f.headers);let D=await n(c,"initial");if(!D.ok)return R(503,Tr[503],_e(503));let w=await t.getAttachmentForUser(D.scope,u,h);if(!w)return o.warn(`404 attachment=${u} viewer=${h} reason=not_visible`),R(404,"Attachment not found");if(w.fileSize!=null&&w.fileSize>p)return o.warn(`413 attachment=${u} viewer=${h} reason=db_size`),R(413,"Attachment too large");let S=uo(w.fileType),g=`filename="${ci(w.fileName)}"; filename*=UTF-8''${li(w.fileName)}`,M=await l.acquire(h,c.signal);if(!M)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${h} reason=aborted`),R(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${h} reason=concurrency`),R(503,"Too many concurrent downloads",_e(503)));let T=!1;try{let C=await m(w.filePath,{maxBytes:p,head:c.method==="HEAD",principal:r(h),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${h} reason=aborted`),R(503,"Attachment request aborted");if(!C.ok){if(!Kr(C.reason))return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=failure_reason`),R(500,bt);let $=Jr(C.reason);return C.reason==="not_found"&&a(u,!1),o.warn(`${$} attachment=${u} viewer=${h} reason=${C.reason} code=${C.code??"-"}`),R($,Tr[$],_e($))}if(C.bytes.byteLength>p)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),R(500,bt);let H=c.method==="HEAD";if(H&&C.size!==void 0&&C.size>p)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),R(500,bt);if(!H&&C.size!==void 0&&C.size!==C.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=size_mismatch`),R(500,bt);let I=S??uo(C.contentType),L=I!==null&&si.has(I),x=L?I:"application/octet-stream",j=L&&d.kind!=="download"?"inline":"attachment",X=H?C.size:C.bytes.byteLength,J=new Headers({"Content-Type":x,"Content-Disposition":`${j}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Xt});return X!==void 0&&J.set("Content-Length",String(X)),y&&J.append("Set-Cookie",y),a(u,!0),o.info(`200 attachment=${u} viewer=${h} type=${x} disposition=${j} bytes=${X??"-"}`),H?new Response(null,{status:200,headers:J}):(T=!0,new Response(Bu(C.bytes,M),{status:200,headers:J}))}finally{T||M()}}};var Ye=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),$h=Ye.queueWaitMs+Ye.readMs+Ye.renderMs+Ye.transferMarginMs;var hi=require("buffer"),fi=new Set([194,198,202,206]),Vu=new Set([192,193,194,195]),Ri=216,qu=217,Si=218,ju=4,Wu=64,Yu=2,mi=8,yi=28,kt=12,mo=8,zu=20,gi=kt+mo+10,Gu=2,Tt=(e,t)=>e[t]<<8|e[t+1],Zt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},pt=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},bi=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Di=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),Ti=e=>(e.stepsLeft-=1,e.stepsLeft>=0),Ai=e=>e[0]===255&&e[1]===Ri,Ei=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!Ti(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let o=e[n];if(n+=1,o===qu)return"eoi";if(o===0||o===Ri)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=Tt(e,n),i=n+a;return a<2||i>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=i,"segment")}},Ku=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!Ti(r))return null;if(a+1>=n)return n;let i=e[a+1];if(i===255)a+=1;else if(i===0||i>=208&&i<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},wi=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=Tt(e,r+1),a=Tt(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let s=0;s<i;s+=1){let c=e[r+7+3*s],d=c>>4,u=c&15;if(d<1||d>4||u<1||u>4)return null;l.push({id:e[r+6+3*s],horizontal:d,vertical:u})}return{marker:t,width:a,height:o,components:l}},Ii=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>ju||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},_i=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:fi.has(e.marker)||t<e.components.length}),yo=e=>{if(!Ai(e))return null;let t=Di(e.byteLength),r=null;for(let n=2;;){if(Ei(e,n,t)!=="segment")return null;if(bi(t.marker)){if(r!==null||(r=wi(e,t),r===null))return null}else if(t.marker===Si){if(r===null)return null;let o=Ii(e,t);return o===null?null:_i(r,o.length)}n=t.end}},xi=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:o})=>{let a=Math.ceil(e.width*n/(t*mi)),i=Math.ceil(e.height*o/(r*mi));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},Ci=e=>e.multiScan?xi(e).reduce((r,n)=>r+n,0)*Wu*Yu:0,Ju=896,Mi=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!Ai(e))return null;let n=hi.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=Di(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let h=Ei(e,u,o);if(h===null)return null;if(h==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,bi(o.marker)){if(a!==null||!Vu.has(o.marker)||(a=wi(e,o),a===null))return null;let m=xi(a);l=new Map;for(let[y,R]of a.components.entries()){let p=l.get(R.id);l.set(R.id,p===void 0?m[y]:Math.max(p,m[y]))}s=a.components.length*(fi.has(a.marker)?Ju:1)}else if(o.marker===Si){if(a===null||d===s)return null;let m=Ii(e,o);if(m===null)return null;for(let R of m){let p=l.get(R);if(p===void 0)return null;c+=p}if(d+=1,i===null&&(i=_i(a,m.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let y=Ku(n,o.end,o);if(y===null)return null;u=y}}},ki=e=>{if(e.byteLength<24||Tt(e,8)!==0||Tt(e,10)!==13||!pt(e,12,"IHDR"))return null;let t=Tt(e,16)*65536+Tt(e,18),r=Tt(e,20)*65536+Tt(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Qu=e=>{if(pt(e,kt,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Zt(e,26,2)&16383,r=Zt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(pt(e,kt,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Zt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return pt(e,kt,"VP8X")?e.byteLength<gi?null:{width:Zt(e,24,3)+1,height:Zt(e,27,3)+1}:null},Pi=e=>{if(ki(e)===null||e.byteLength<=yi)return null;switch(e[yi]){case 0:return!1;case 1:return!0;default:return null}},vi=(e,t)=>{if(pt(e,kt,"VP8 "))return"lossy";if(pt(e,kt,"VP8L"))return"lossless";if(!pt(e,kt,"VP8X")||e.byteLength<gi)return null;if((e[zu]&Gu)!==0)return"animated";let r=!1,n=t;for(let o=kt;o+mo<=e.byteLength;){if(n-=1,n<0)return null;if(pt(e,o,"VP8L"))return"lossless";if(pt(e,o,"VP8 "))return r?"lossy-alpha":"lossy";pt(e,o,"ALPH")&&(r=!0);let a=Zt(e,o+4,4);o+=mo+a+a%2}return null},Li={png:ki,jpeg:yo,webp:Qu};var Qr=Object.freeze(["image/webp","image/jpeg","image/png"]),Xr=1024*1024;var Xu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Zu={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},ed=new Set(Qr),td=e=>typeof e=="string"&&ed.has(e),rd=256,Zr=(e,t)=>e.fileType===null||!Xu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,nd=[137,80,78,71,13,10,26,10],od=[255,216,255],ad=[[71,73,70,56,55,97],[71,73,70,56,57,97]],id=[82,73,70,70],sd=[87,69,66,80],Ar=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,o]of t.entries())if(e[r+n]!==o)return!1;return!0},ho=e=>{if(Ar(e,nd,0))return"png";if(Ar(e,od,0))return"jpeg";for(let t of ad)if(Ar(e,t,0))return"gif";return Ar(e,id,0)&&Ar(e,sd,8)?"webp":null},Ni=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:Za([t])}},Oi=(e,t)=>{if(!td(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Xr)return"too_large";let r=Zu[e.contentType];if(ho(e.bytes)!==r)return"signature";let n=Li[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Hi=e=>{ce("maxBytes",e.maxBytes,0),ce("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+rd;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let s of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(s)}}}};var fo=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ue(),l=new AbortController,s=!1,c,d,u=()=>{a(ue()-i)},h=S=>{c=ot(()=>{s=!0,S({timedOut:!0}),d=ot(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},m=new Promise(h),y=AbortSignal.any([r,l.signal]),R=S=>{S(n(y))},p=new Promise(R),f=S=>(clearTimeout(c),clearTimeout(d),s&&o(ue()-i,S.kind==="error"?{error:S.error}:null),S),D=p.then(S=>f({kind:"value",value:S}),S=>f({kind:"error",error:S}));return{outcome:Promise.race([p.then(S=>({timedOut:!1,value:S})),m]),settled:D}};var At={404:"Attachment not found",500:bt,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Fi=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=Oi(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},ld=e=>{let t=new AbortController,r=()=>{t.abort()},n=ot(r,Ye.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},$i=()=>{},cd=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),Ui=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(m,y)=>{let R=y.then($i,$i);l.set(m,R);let p=()=>{l.get(m)===R&&l.delete(m)};R.then(p)},c=async(m,y)=>{let R=l.get(m.key);if(R===void 0)return t.acquire(m.owner,y);let p=ld(y);try{if(await cd(R,p.signal),p.signal.aborted)return null;let f=r.get(m.key);return f!==void 0?{...f,identity:"verified"}:await t.acquire(m.owner,p.signal)}finally{p.end()}},d=(m,y)=>{if(m.fileSize===null)return y.kind==="exact"?"verified":"unrecorded";if(y.kind==="exact"?y.bytes===m.fileSize:m.fileSize>y.maxBytes)return"verified";let p=y.kind==="exact"?String(y.bytes):`>${y.maxBytes}`;return i.warn(`size_mismatch expected=${m.fileSize} got=${p} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`),"unverified"},u=(m,y)=>(R,p)=>{let f=p===null?"":` message=${p.error instanceof Error?p.error.message:"unknown"}`;i.warn(`${m}_overrun ms=${R} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail${f}`)},h=(m,y)=>R=>{i.warn(`${m}_stuck ms=${R} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail`)};return async(m,y)=>{let R=await c(m,y);if(R===null)return{kind:"failure",status:503,reason:y.aborted?"aborted":"queue"};if(typeof R!="function")return R;let p=R,f=null;try{if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let D=r.get(m.key);if(D!==void 0)return{...D,identity:"verified"};let w=fo({budgetMs:Ye.readMs,flightSignal:y,call:$=>m.readAttachment(m.filePath,{maxBytes:n,head:!1,principal:o(m.owner),signal:$}),onOverrun:u("read",m),onStuck:h("read",m)}),S=await w.outcome;if(S.timedOut)return f=w.settled,y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=S.value;if(!g.ok&&g.reason!=="too_large")return Kr(g.reason)?(g.reason==="not_found"&&a(m.attachmentId,!1),{kind:"failure",status:Jr(g.reason),reason:g.reason,code:g.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(g.ok&&g.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let M=d(m,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),T=$=>{M==="verified"&&r.set(m.key,$)},C=$=>(T($),{...$,identity:M});if(!g.ok)return C({kind:"unrenderable",reason:"too_large"});let H=ho(g.bytes);if(H===null)return C({kind:"unrenderable",reason:"signature"});let I=fo({budgetMs:Ye.renderMs,flightSignal:y,call:$=>m.renderer.render(g.bytes,{format:H,maxWidth:m.box.maxWidth,maxHeight:m.box.maxHeight,signal:$}),onOverrun:u("render",m),onStuck:h("render",m)}),L=$=>{if($.kind==="error")return;let _=Fi($.value,m.box);"entry"in _&&T(_.entry)},x=null,j=()=>(x===null&&(x=I.settled.then(L),s(m.key,x)),x);y.addEventListener("abort",j,{once:!0});let X=await I.outcome.finally(()=>y.removeEventListener("abort",j));if(X.timedOut||y.aborted)return f=j(),y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let J=Fi(X.value,m.box);return"entry"in J?C(J.entry):J.failure}finally{f===null?p():f.then(p,p)}}};var Bi=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let s=new AbortController,c=()=>{e.get(t)?.controller===s&&e.delete(t)},u={promise:n(s.signal).finally(c),controller:s,waiters:0};return e.set(t,u),u},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var ji=10,ud=1/ji,Vi=1-ud,dd=1024,pd=64,md=8,qi="private, no-cache",yd="no-store",hd=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),fd=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Wi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(S,g)=>Dt({reason:S,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:M=>`viewer=${M} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*ji),h=dt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:pd,maxPerOwner:md,maxWaitMs:Ye.queueWaitMs}}),m=Hi({maxBytes:l.cacheBytes,maxEntries:dd}),y=Bi(),R=Ui({gate:h,cache:m,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),p=(S,g,M,T)=>{let C=`attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail cache=${T}`;if(g.kind==="failure")return o[fd(g)](`${g.status} ${C} reason=${g.reason} code=${g.code??"-"}`),S.fail(g.status,At[g.status],_e(g.status));let H=hd[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${C} reason=${g.reason}${H}`),S.fail(404,At[404]);let I=g.identity==="verified"?{"Cache-Control":qi,ETag:M}:{"Cache-Control":yd},L=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...I,"Content-Security-Policy":"default-src 'none'; sandbox",...Xt});return S.cookie&&L.append("Set-Cookie",S.cookie),o.info(`200 ${C} type=${g.contentType} bytes=${g.bytes.byteLength}${H}`),new Response(g.bytes,{status:200,headers:L})},f=(S,g)=>{let M=S.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return M===null?null:g.fail(M.status,M.message,M.headers)},D=S=>f(d,S),w=(S,g)=>g?f(u,S):D(S);return async(S,g)=>{let{request:M,attachmentId:T,internalUserId:C,readAttachment:H,cookie:I,fail:L}=S,x=ro[g],j=M.headers.get("If-None-Match"),X=j!==null,J=w(S,X);if(J)return J;let $=await n(M,"initial");if(!$.ok)return L(503,At[503],_e(503));let _=await t.getAttachmentForUser($.scope,T,C),Y=_!==null&&Zr(_,i)?Ni({rendererId:s.id,box:x,attachmentId:T,filePath:_.filePath,fileType:_.fileType,fileSize:_.fileSize}):null;if(Y&&ao(j,Y.etag)){let b=new Headers({"Cache-Control":qi,ETag:Y.etag,...Xt});return I&&b.append("Set-Cookie",I),o.info(`304 attachment=${T} viewer=${C} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:b})}if(X){let b=D(S);if(b)return b}if(!_)return o.warn(`404 attachment=${T} viewer=${C} variant=thumbnail reason=not_visible`),L(404,At[404]);if(!Y)return d.refund(C,Vi),o.info(`404 attachment=${T} viewer=${C} variant=thumbnail reason=not_eligible`),L(404,At[404]);let{key:pe,etag:ie}=Y,me=m.get(pe);if(me)return d.refund(C,Vi),p(S,{...me,identity:"verified"},ie,"hit");let De=b=>R({key:pe,attachmentId:T,filePath:_.filePath,fileSize:_.fileSize,box:x,owner:C,readAttachment:H,renderer:s},b),Z;try{Z=await y.join(pe,M.signal,De)}catch(b){return o.error(`500 attachment=${T} viewer=${C} variant=thumbnail cache=miss reason=port_exception message=${b instanceof Error?b.message:"unknown"}`),L(500,At[500])}return p(S,Z,ie,"miss")}};var Rd='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Sd=()=>Gr(403,co,{cookie:null}),Yi=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=no(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Gr(404,Tr[404],{cookie:null}),crossSiteRejection:Sd}),zi=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,i=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:ii(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:pi({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Wi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,h=(m,y,R={})=>Gr(m,y,{cookie:u,extraHeaders:R});try{let{user:m,cookie:y}=await t(c,{failureRedirect:null});if(u=y??null,!m)return h(401,"Unauthorized");let R=no(new URL(c.url).searchParams);if(R.kind==="invalid")return h(400,"Invalid attachment request");if(R.kind==="thumbnail"&&c.method!=="GET")return h(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return h(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return h(404,"Attachment not found");if(d.token===void 0)throw new Error(Rd);let p=s.idCodec.decode(d.token);if(p===null||!ct(p))return h(400,"Invalid attachment token");let f=await r.getUserIdByExternalId(m.id);if(!f)return h(403,"Forbidden");let D={request:c,delivery:R,attachmentId:p,internalUserId:f,readAttachment:s.read,cookie:u,fail:h};return R.kind!=="thumbnail"?await s.serveOriginal(D):s.serveThumbnail===null?h(404,At[404]):await s.serveThumbnail(D,R.variant)}catch(m){if(m instanceof Response)throw m;return a.error(`500 attachment=? viewer=? reason=unexpected message=${m instanceof Error?m.message:"unknown"}`),h(500,bt)}}};var gd=32*1024*1024,bd=60,Dd=4,Td=120,Ad=2,Ed=8*1024*1024,en=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wd=e=>{if(e===void 0)throw Je("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!en(e))throw Q("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Je("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw Q("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Q("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Id=e=>{if(e===void 0)return null;if(!en(e))throw Q("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:wd(e.renderer),rateLimitPerMinute:Oe("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Td),concurrency:Oe("attachments.thumbnails.concurrency",e.concurrency,1,Ad),cacheBytes:Oe("attachments.thumbnails.cacheBytes",e.cacheBytes,0,Ed)})},Gi=e=>{let t=e;if(t===void 0)return null;if(!en(t))throw Q("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Je("attachments.idCodec","injected when attachments is given");if(!en(r)||typeof r.encode!="function"||typeof r.decode!="function")throw Q("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Je("attachments.read","injected when attachments is given");if(typeof n!="function")throw Q("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Oe("attachments.maxBytes",t.maxBytes,1,gd),rateLimitPerMinute:Oe("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,bd),concurrency:Oe("attachments.concurrency",t.concurrency,1,Dd),thumbnails:Id(t.thumbnails)})},_d=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),tn=e=>{for(let[t,r]of _d)if(Object.hasOwn(e,t))throw Je(r,`given in place of the flat key ${t}`)};var Ji=8,xd=8*Ji,Cd=128,Md=2,Qi=Md*Cd,kd=4*Qi,Pd=6e4,vd=6e4,Ld="Too many reads",Ki=Object.freeze(Object.keys(Vt).filter(e=>Vt[e].admission.includes("miss-gate"))),Xi=e=>{let t=dt({limit:xd,maxHeldPerOwner:Ji,queue:{max:kd,maxPerOwner:Qi,maxWaitMs:Pd}}),r=ve({windowMs:vd,tallies:Ki,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Ki.map(l=>`${l}:${i[l]}`).join(",")}`)}});return{admissionFor:(n,o,a)=>({signal:a,acquire:async i=>{let l=await t.acquire(n,i);return l===null&&!i.aborted&&r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=cache_miss_admission`)),l}})}},rn=(e,t,r)=>{let n=e(t,r,{error:{message:Ld}},503);for(let[o,a]of Object.entries(_e(503)))n.headers.set(o,a);return n};var Zi=e=>{let t=e.get(Ae.cursorReportHubId),r=e.get(Ae.cursorBusinessDate),n=e.get(Ae.cursorSnapshot),o=_a(n)?n:null,a=null;if(t!==null){let l=nt(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!Ia(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=br(e.get(Ae.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var nn=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Nd=2,Od=16,Hd=Nd*Od,Fd=6e4,es=()=>{},$d=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},ts=e=>{let t=dt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Hd,queue:null}),r=ve({windowMs:Fd,tallies:["sse","ids-stream"],writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`streams_per_viewer_suppressed count=${o} since=${a} viewer=${n} routes=sse:${i.sse},ids-stream:${i["ids-stream"]}`)}});return{admit:async(n,o,a)=>{if(n===null)return es;if(a.aborted){if(t.canAcquire(n))return es}else{let i=await t.acquire(n,a);if(i!==null)return $d(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var on=30,is=4e3,Ud="stream interrupted by server error",Bd="Too many streams",Vd=15e3,ss=Symbol("ids-stream-heartbeat"),rs=()=>{},ns=e=>e.return(void 0).then(rs,rs),qd=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(ss),Vd)}),stop:()=>clearTimeout(e)}};async function*os(e,t,r,n){let o=t?Ma(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:is),e.length),l=Ut(e,o,i),s=i>o?e[i-1]:void 0;o=i;let c=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:c||s===void 0?null:{businessDate:s.businessDate,reportHubId:s.reportHubId},isLast:c,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,c)return}}var ls=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...ut});return e&&t.append("Set-Cookie",e),t},as=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await ns(t);try{d.close()}catch{}},i=new TextEncoder,l=!1,s=null,c=new ReadableStream({async pull(d){if(l||r.aborted){await a(d,!0);return}let u=qd();try{s===null&&(s=t.next());let h=await Promise.race([s,u.fired]);if(u.stop(),h===ss){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
2
2
|
`));return}s=null;let{value:m,done:y}=h;if(y){await a(d,!1);return}if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`${JSON.stringify(m)}
|
|
3
3
|
`))}catch(h){if(u.stop(),s=null,o(),l||r.aborted)return;h instanceof rt||n.error(`ids-stream emission failed: ${h instanceof Error?h.message:String(h)}`);try{let m={kind:"error",error:Ud};d.enqueue(i.encode(`${JSON.stringify(m)}
|
|
4
4
|
`)),d.close()}catch{}}},cancel(){l=!0,o(),ns(t)}});return new Response(c,{status:200,headers:ls(e)})},cs=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,s,c,d,u,h,m)=>{let y=!1,R=null,p=null,f=new Promise((S,g)=>{R=S,p=g});f.catch(()=>{});let D=t.getDailyReportIdsByExternalId(c,s.id,{forceRefresh:l.forceRefresh,admission:m,onFetchStart:l.cursor?void 0:()=>{y=!0,t.readSseStreamAnchor().then(S=>t.getDailyReportIdsFirstPageByExternalId(c,s.id,on).then(g=>({items:g,streamAnchor:S}))).then(S=>R?.(S),S=>p?.(S))}});if(D.catch(()=>{}),l.cursor){let{items:S,streamAnchor:g,snapshot:M}=await D,T=l.snapshot!==null&&l.snapshot===M;return as(d,os(S,T?l.cursor:null,on,{snapshot:M,restarted:!T,streamAnchor:g}),u,r,h)}let w=(async function*(){let S=await Promise.race([D.then(T=>({kind:"full",source:T}),T=>({kind:"full-error",error:T})),f.then(T=>({kind:"page",page:T}),()=>({kind:"page-error"}))]),g=null,M=!1;if(S.kind==="full")g=S.source;else if(S.kind==="page"){let{items:T,streamAnchor:C}=S.page;if(T.length<on){yield{kind:"chunk",...Ut(T,0,T.length),nextCursor:null,isLast:!0,total:T.length,streamAnchor:C};return}yield{kind:"chunk",...Ut(T,0,T.length),nextCursor:null,isLast:!1,provisional:!0},M=!0}else if(S.kind==="full-error"&&y){let T=await f.catch(()=>null);T&&T.items.length>0&&(yield{kind:"chunk",...Ut(T.items,0,T.items.length),nextCursor:null,isLast:!1,provisional:!0})}g===null&&(g=await D),yield*os(g.items,null,M?is:on,{snapshot:g.snapshot,streamAnchor:g.streamAnchor})})();return as(d,w,u,r,h)};return async(l,s,c,d,u,h)=>{let m=Zi(l.searchParams);if("refused"in m)return h(c,s,{error:{message:m.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:y}=m;if(y.forceRefresh){let D=a(d,c,s,h);if(D!==null)return D}let R=nn(c),p=await t.getUserIdByExternalId(d.id),f=await n.admit(p,"ids-stream",R);if(f===null){let D=h(c,s,{error:{message:Bd}},503);for(let[w,S]of Object.entries(_e(503)))D.headers.set(w,S);return D}if(R.aborted)return new Response(null,{status:200,headers:ls(s)});try{return await i(y,d,u,s,R,f,p===null?void 0:o.admissionFor(p,de.idsStream,R))}catch(D){if(f(),D instanceof rt)return rn(h,c,s);throw D}}};var qt=require("drizzle-orm");var ze="Internal",us=e=>e.trim().toLowerCase();var jd="",Wd=64,Yd=e=>e.toLowerCase(),ds=e=>{let t=new Set;if(!Array.isArray(e))return t;for(let r of e){if(typeof r!="string")continue;let n=us(r);n.length>0&&t.add(n)}return t};function Me(e,t){return e===null?!0:t==null?!1:e.has(Yd(t))}function $e(e){return e!==null&&e.size===0}var zd=4e3,So=e=>{let t=e.getSQLType();if(!t.startsWith("nvarchar("))throw Q("tables.hub.sourceType","an nvarchar(n) column with a declared length (source types compare as UTF-16 bytes)",t);return ce("tables.hub.sourceType.length",e.length,1,zd)};function wr(e,t){if(t===null)return;let r=So(e),n=[...t].filter(a=>a.length<=r);if(n.length===0)return qt.sql`1 = 0`;let o=qt.sql.raw(`VARBINARY(${2*r})`);return(0,qt.inArray)(qt.sql`CAST(LOWER(${e}) AS ${o})`,n.map(a=>qt.sql`CAST(${a} AS ${o})`))}var er,tr,Er=class Er{constructor(t,r){Cn(this,er);Cn(this,tr);Mn(this,er,t),Mn(this,tr,r)}get visible(){return cr(this,er)===null?null:new Set(cr(this,er))}get commentable(){return cr(this,tr)===null?null:new Set(cr(this,tr))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=ds(r?t.read:t);if(!r||t.comment===void 0)return new Er(n,n);let o=new Set;for(let a of ds(t.comment))n.has(a)&&o.add(a);return new Er(n,o)}static unrestricted(t){return new Er(null,null)}};er=new WeakMap,tr=new WeakMap;var Xe=Er,Ro=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),Gd=new Set(["read","comment"]),ms=e=>{if(Ro(e))return Xe.restrictTo(e);if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=Object.keys(e);if("unrestricted"in e){let o=e.unrestricted;return t.length===1&&typeof o=="string"&&o.trim().length>0?Xe.unrestricted(o):null}let{read:r,comment:n}=e;return t.every(o=>Gd.has(o))&&Ro(r)?n===void 0?Xe.restrictTo({read:r}):Ro(n)?Xe.restrictTo({read:r,comment:n}):null:null};function an(e){let t=ps(e.visible),r=ps(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function ps(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(jd);if(t.length<=Wd)return`s:${t}`;let r=2166136261;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return`sh:${(r>>>0).toString(16)}`}var ys=(e,t,r,n)=>Me(n.commentable,t)||e.authorUserId===r;var Ms=require("@aiquants/fuzzy-search");var Ss=require("crypto"),go=require("timers/promises"),ge=require("@aiquants/fuzzy-search/normalize");var ln=`
|