@aiquants/daily-report 0.41.0 → 0.42.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 +159 -0
- package/README.md +473 -237
- package/dist/client.js +5 -7
- package/dist/client.mjs +5 -7
- package/dist/index.d.mts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/server.d.mts +20 -11
- package/dist/server.d.ts +20 -11
- package/dist/server.js +13 -10
- package/dist/server.mjs +13 -10
- package/dist/styles/daily-report.standalone.css +1 -1
- package/package.json +6 -4
package/dist/server.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
|
-
"use strict";var ln=Object.defineProperty;var Fl=Object.getOwnPropertyDescriptor;var Hl=Object.getOwnPropertyNames;var Bl=Object.prototype.hasOwnProperty;var Do=e=>{throw TypeError(e)};var Ul=(e,t)=>{for(var r in t)ln(e,r,{get:t[r],enumerable:!0})},$l=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Hl(t))!Bl.call(e,o)&&o!==r&&ln(e,o,{get:()=>t[o],enumerable:!(n=Fl(t,o))||n.enumerable});return e};var Vl=e=>$l(ln({},"__esModule",{value:!0}),e);var To=(e,t,r)=>t.has(e)||Do("Cannot "+r);var Jt=(e,t,r)=>(To(e,t,"read from private field"),r?r.call(e):t.get(e)),cn=(e,t,r)=>t.has(e)?Do("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),un=(e,t,r,n)=>(To(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var nm={};Ul(nm,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>Nr,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>kr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>Ro,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Rr,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>So,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>Kr,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>oo,DailyReportSseReader:()=>Wt,DailyReportViewerScope:()=>Ue,SqlResultCache:()=>Ft,buildDailyReportSseStreamKey:()=>fo,createDailyReportHandlers:()=>Jr,createDailyReportServer:()=>rm,createDailyReportService:()=>on,createEpochStore:()=>gr,createSharpThumbnailRenderer:()=>Tl,defineDailyReportSchema:()=>il,defineDailyReportSearchSchema:()=>sl,encodeIdsStreamRows:()=>Ct,isStreamIdLte:()=>pt,parseClientTempId:()=>_r,predictSharpThumbnailWorkingSetBytes:()=>Dl,readDailyReportSseStreamEntry:()=>qt,transformJsonArray:()=>al});module.exports=Vl(nm);var dn=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,X=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${dn(r)}`),it=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),pn=(e,t,r)=>X(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),de=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw X(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},Me=(e,t,r,n)=>t===void 0?n:de(e,t,r);var se=()=>Math.floor(performance.now());var mn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),je=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},gr=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{}}}),Qt=(e,t)=>t?e.map(r=>structuredClone(r)):e,Yl=8,ql=32,jl=24,Wl=16,zl=-(2**30),Gl=2**30-1,Kl=e=>Number.isInteger(e)&&e>=zl&&e<=Gl&&!Object.is(e,-0),Jl=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=ql,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=Yl*a.length;for(let i of a)typeof i=="string"?r+=jl+2*i.length:typeof i=="number"&&!Kl(i)?r+=Wl:typeof i=="object"&&i!==null&&n.push(i)}return r},Ft=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-se())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:c,expireAt:se()+a,epoch:s}),c})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&s===null)throw new je(o.signal.aborted?"aborted":"busy");try{for(let d of r)d();let c=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:c,expireAt:se()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),c}finally{s?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new je("aborted");return this.dropBucket(r),Qt(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>se())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),Qt(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),Qt(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return Qt(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new je("aborted");return Qt(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 je&&(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=Me("cacheDefaultTtlMs",t.defaultTtlMs,1,mn.defaultTtlMs),this.maxBuckets=Me("cacheMaxBuckets",t.maxBuckets,1,mn.maxBuckets),this.maxBytes=Me("cacheMaxBytes",t.maxBytes,1,mn.maxBytes),this.lastSweepAt=se()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=Jl(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=se();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};var Ql=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Ao=e=>e<10?`0${e}`:`${e}`,Xl=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Ao(e.getMonth()+1),n=Ao(e.getDate());return`${t}-${r}-${n}`},Ht=e=>{let t=Ql.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}`},br=e=>Ht(e)===e;var Pe=e=>e==null?null:e instanceof Date?Xl(e):Ht(e);var Eo=require("zod/v3"),Ze=e=>Number.isSafeInteger(e)&&e>0,Ae=Eo.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var pe=require("zod/v3");var Dr=/^(?:[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 It=Symbol("daily-report wire mismatch"),et=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),It),xo=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,_t=(e,t)=>({code:"invalid_type",expected:e,received:xo(t)}),Zl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ec=e=>{let t=0;for(let r in e)t+=1;return t},wo=(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},Bt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!Zl(n))return et(o,null,_t("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===It){i=!0;continue}a===null&&u!==d&&(a=wo(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?It:a!==null?a:ec(n)===l?n:wo(n,t,t.length)}},Xt=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},Zt=e=>(t,r,n)=>{if(!Array.isArray(t))return et(r,n,_t("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===It?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?It:o},le=(e,t,r)=>e==null||typeof e=="string"?e:et(t,r,_t("string",e)),Io=(e,t,r)=>e===null||typeof e=="string"?e:et(t,r,_t("string",e)),_o=(e,t,r)=>typeof e=="string"?e:et(t,r,_t("string",e)),tc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:et(t,r,_t("number",e)),er=(e,t,r)=>typeof e=="boolean"?e:et(t,r,_t("boolean",e)),yn=(e,t,r)=>{if(typeof e=="number"&&Ze(e))return e;for(let{message:n,path:o,...a}of Ae.safeParse(e).error.issues)et(t,r,a);return It},Co={present:!0,absent:!0,unknown:!0},Mo=Object.keys(Co),rc=Mo.map(e=>`'${e}'`).join(" | "),nc=(e,t,r)=>typeof e!="string"?et(t,r,{code:"invalid_type",expected:rc,received:xo(e)}):Object.hasOwn(Co,e)?e:et(t,r,{code:"invalid_enum_value",received:e,options:[...Mo]}),Po=Bt({name:le,affiliation:le}),Lo=Bt({name:le,text:le,color:le}),ko=Bt({id:yn,name:le,color:le}),No=Bt({id:yn,userId:le,userName:le,content:le,createdAt:le,isMine:er}),oc=Bt({id:_o,fileName:_o,fileType:Io,fileSize:tc,createdAt:Io,state:nc,hasThumbnail:er}),ac=Bt({reportHubId:yn,date:le,createdAt:le,author:le,userId:le,sourceType:le,employeeName:le,updatedBy:le,updatedAt:le,category:le,creationCategory:le,visitTimeFrom:le,visitTimeTo:le,customerName:le,interviewers:Zt(Xt(Po)),subject:le,content:le,externalComments:Zt(Xt(Lo)),isRead:er,isStarred:er,isDraft:er,labels:Zt(Xt(ko)),postedComments:Zt(Xt(No)),attachments:Zt(Xt(oc))}),tr=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===It?{ok:!1,issues:r.issues}:{ok:!0,value:n}},vo=e=>tr(ac,e),Oo=e=>tr(Po,e),Fo=e=>tr(Lo,e),Ho=e=>tr(ko,e),Bo=e=>tr(No,e);var Uo=15e3,$o="lastEventId",ic=/^\d{1,15}-\d{1,15}$/,Vo=e=>ic.test(e),rr=e=>pe.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 pe.z.NEVER}),Sm=rr(Oo),gm=rr(Fo),bm=rr(Ho),sc=rr(Bo),hn=rr(vo),xt=pe.z.string().regex(Dr),lc=pe.z.object({type:pe.z.literal("connected")}),Tr=pe.z.object({type:pe.z.literal("status-update"),reportHubId:Ae,statusType:pe.z.enum(["star","read"]),value:pe.z.boolean(),clientTempId:xt,recipientRawUserId:Ae.optional()}),fn=pe.z.string(),Rn=pe.z.object({type:pe.z.literal("comment-add"),reportHubId:Ae,comment:sc,clientTempId:xt,recipientRawUserId:Ae.optional(),sourceType:fn}),Sn=pe.z.object({type:pe.z.literal("comment-delete"),reportHubId:Ae,commentId:Ae,clientTempId:xt,recipientRawUserId:Ae.optional(),sourceType:fn}),gn=pe.z.object({type:pe.z.literal("report-create"),reportHubId:Ae,report:hn,clientTempId:xt,recipientRawUserId:Ae.optional()}),bn=pe.z.object({type:pe.z.literal("report-update"),reportHubId:Ae,report:hn,clientTempId:xt,recipientRawUserId:Ae.optional()}),Dn=pe.z.object({type:pe.z.literal("report-publish"),reportHubId:Ae,report:hn,clientTempId:xt,recipientRawUserId:Ae.optional()}),Tn=pe.z.object({type:pe.z.literal("report-delete"),reportHubId:Ae,clientTempId:xt,sourceType:fn}),Yo=pe.z.discriminatedUnion("type",[lc,Tr,Rn,Sn,gn,bn,Dn,Tn]);var qo="ids-columns";var cc=/^[0-9a-f]{1,16}$/,jo=e=>Ze(e.reportHubId)&&(e.businessDate===null||br(e.businessDate)),Wo=e=>typeof e=="string"&&cc.test(e),Em=Object.freeze({kind:"absent"}),wm=Object.freeze({kind:"value",value:null});var Ct=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:R}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let m=R===void 0?null:R,p=s.get(m);p===void 0&&(p=i.length,i.push(m),s.set(m,p)),l.push(p)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},Ar=e=>{let t=2166136261,r=-624069552;for(let n of e){let o=n.reportHubId;t^=o&255,t=Math.imul(t,16777619),t^=o>>>8&255,t=Math.imul(t,16777619),t^=o>>>16&255,t=Math.imul(t,16777619),t^=o>>>24&255,t=Math.imul(t,16777619),r^=o>>>24&255,r=Math.imul(r,16777619),r^=o>>>16&255,r=Math.imul(r,16777619),r^=o>>>8&255,r=Math.imul(r,16777619),r^=o&255,r=Math.imul(r,16777619);let a=n.businessDate;if(a===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let i=0;i<a.length;i++){let l=a.charCodeAt(i);t^=l&255,t=Math.imul(t,16777619),r^=l&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},zo=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,uc=(e,t,r,n)=>zo(e,t,r,n)<0,An=(e,t)=>zo(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Go=e=>{for(let t=1;t<e.length;t++)if(!uc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},Ko=(e,t)=>{let r=e.findIndex(n=>An({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var ie=Object.freeze({businessDate:"business-date",idsStream:qo,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),Se=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 Jo=(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)}}},Cm=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),Qo=e=>`[DailyReport${e}]`,ge=(e,t,r)=>e===void 0?Jo(t,Qo(r)):Jo(0,Qo(r),e);var dc="legacy-",En=e=>`${dc}${e}`;var pc=/^[1-9][0-9]*$/,mc=/^(?:0|[1-9][0-9]*)$/,We=e=>{if(e===null||!pc.test(e))return null;let t=Number(e);return Ze(t)?t:null},wn=e=>{if(e===null||!mc.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},In=e=>e==="true"?!0:e==="false"?!1:null,nr=e=>e===null?!1:In(e);var Xo=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 yc=16777619,_n=2166136261,xn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,yc);return o>>>0},Zo=e=>xn(_n,e,0,e.length),hc=String.fromCodePoint(3),fc=String.fromCodePoint(2),Rc=String.fromCodePoint(1),Er=e=>Zo(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(hc)).join(fc)).join(Rc));var ea=e=>e==="intersection"||e==="union",we=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Cn=2,wr=2,Mt=Object.freeze({word:0,reading:1});var Mn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var vm=2*(1+Cn);var Sc=require("zod/v3");var $e=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var Ir=Math.max(1,Math.floor(10.556701030927835));var ze=(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),ze(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var lt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var Vm=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),gc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Pn=e=>{let t=e.trim();return t.length===0?null:t.replace(gc,"\uFFFD")},bc=e=>{let t=Pn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>lt.maxValueLength?"filter-value-too-long":null},Dc=e=>{if(e.length>lt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=bc(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},Tc=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},ta=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Dc(t);if(r!==null)return r}return Tc(e)>lt.maxTotalValueLength?"filters-too-long":null};var ra=e=>e.trim().length===0;var _r=e=>e!==null&&Dr.test(e)?e:null,Ln=e=>ea(e)?e:null,kn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>we.maxDetailIds)return null;let r=[];for(let n of t){let o=We(n);if(o===null||r.includes(o))return null;r.push(o)}return r},na=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},oa=(e,t)=>{let r={authors:e.getAll(Se.searchAuthor),sourceTypes:e.getAll(Se.searchSourceType),customers:e.getAll(Se.searchCustomer)},n=ta(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:na(r.authors),customers:na(r.customers)}}},aa=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var sa=Object.freeze({status:400,error:"Invalid form"}),la=e=>({status:413,error:"Form too large",measuredBy:e}),Ac=(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)}}))},Ec=async e=>{let t=wn(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:la("declared")};let r=!1,n=e.body===null?null:Ac(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?la("counted"):sa}}let l=aa(i);return l===null?{refusal:sa}:{fields:l}},ca=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=In(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},da=Object.freeze({update:(e,t,r)=>{let n=e.get($e.title),o=e.get($e.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:ca("toggleStar",$e.isStarred),toggleRead:ca("toggleRead",$e.isRead),addComment:(e,t)=>{let r=e.get($e.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=We(e.get($e.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),wc=e=>Object.hasOwn(da,e),Ic=(e,t)=>{let r=e.get($e.intent),n=e.get($e.businessDate),o=n===null?null:Ht(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get($e.operationTimestamp),i=wn(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get($e.clientTempId);if(!l)return{error:"clientTempId required"};let s=_r(l);if(s===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:i}};let c=We(e.get($e.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!wc(r)?{error:"Invalid intent"}:da[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},pa=async(e,t)=>{let r=await Ec(e);if("refusal"in r)return r;let n=Ic(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},_c=6e4,xc="form_too_large",ua=["declared","counted"],ma=e=>{let t=Ve({windowMs:_c,tallies:ua,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${ua.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(xc,r,n)}};var Pt=Object.freeze({[ie.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ie.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[ie.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ie.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[ie.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[ie.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[ie.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),ya=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Nn=e=>e!==void 0&&Object.hasOwn(Pt,e);var vn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),ha=e=>Object.hasOwn(vn,e);var Cc="download",Mc="thumbnail",Pc="1";var On=e=>{let t=e.getAll(Mc),r=e.getAll(Cc);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&ha(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Pc?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var fa=require("crypto"),Fn=e=>`"${(0,fa.createHash)("sha256").update(e).digest("hex")}"`,Ra=e=>Fn(JSON.stringify(e));var tt=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),Hn=(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},Sa=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=Fn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...tt});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&Hn(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},Bn=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...tt});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},Un=e=>(t,r,n,o)=>{if(o!==200)return Bn(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)},Lc=5e3/1e3,kc=new Map([[503,Lc]]),He=e=>{let t=kc.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var Vn="Cross-site request rejected",Nc="Not Found",vc=new Set(["same-origin","none"]),Oc=new Set(["GET","HEAD","OPTIONS"]),ga=["api","action","sse","attachment"],ba=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...tt}}),Fc=()=>ba(403,Vn),xr=()=>ba(404,Nc),or=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:Fc}),Da=e=>new URL(e.url).pathname.endsWith(".data"),Hc=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},Ta=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Oc.has(e.method)||Hc(e)):vc.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},Bc=6e4,Uc="refusals",$c=32,Vc=/^[a-z-]+$/,$n=e=>{if(e===null)return"-";let t=e.slice(0,$c);return Vc.test(t)&&t===e?e:JSON.stringify(t)},Aa=e=>{let t=Ve({windowMs:Bc,tallies:ga,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${ga.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${$n(a.get("Sec-Fetch-Site"))} mode=${$n(a.get("Sec-Fetch-Mode"))} dest=${$n(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(Uc,r,o)}};var Ea=(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 Yc="same-origin",qc="SAMEORIGIN",Ut=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Yc,"X-Frame-Options":qc}),Cr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Ut});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},wa=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),jc=/^[\x20-\x7E]+$/,Wc=/^[\w.+-]+\/[\w.+-]+/,Yn=e=>e&&jc.test(e)&&Wc.test(e)?e:null,zc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Ia=e=>encodeURIComponent(e.replace(zc,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),_a=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),Mr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},xa={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Pr=e=>typeof e=="string"&&Object.hasOwn(xa,e),Lr=e=>xa[e],ct="Attachment request failed";var rt=e=>{let t=de("limit",e.limit,1),r=de("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:de("queue.max",e.queue.max,0),maxPerOwner:de("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:de("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(y,S)=>y.get(S)??0,c=(y,S,_)=>{let D=s(y,S)+_;D<=0?y.delete(S):y.set(S,D)},d=y=>s(l,y)<r,u=y=>o<t&&d(y),R=y=>(o+=1,c(l,y,1),f(y)),m=()=>{let y=-1,S=r;for(let[_,D]of a.entries()){let h=s(l,D.owner);if(h<S&&(y=_,S=h,h===0))break}return y},p=()=>{for(;o<t;){let y=m();if(y<0)return;let[S]=a.splice(y,1);c(i,S.owner,-1),S.grant(R(S.owner))}},f=y=>{let S=!1;return()=>{S||(S=!0,o-=1,c(l,y,-1),p())}};return{canAcquire:u,acquire:(y,S)=>{if(S.aborted)return Promise.resolve(null);if(u(y))return Promise.resolve(R(y));if(n===null||a.length>=n.max||s(i,y)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:_}=n,D=h=>{let g=()=>{let j=a.indexOf(M);j<0||(a.splice(j,1),c(i,y,-1),x(),h(null))},P=ze(g,_),x=()=>{clearTimeout(P),S.removeEventListener("abort",g)},M={owner:y,grant:j=>{x(),h(j)}};a.push(M),c(i,y,1),S.addEventListener("abort",g,{once:!0})};return new Promise(D)}}};var Gc=1024,qn="Too many requests",Kc=(e,t)=>{de("limitPerWindow",e,1),de("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<=Gc)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))}}},ut=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(de("windowMs",r,1e3)%1e3!==0)throw X("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Kc(e.limitPerWindow,r),i=Object.freeze({status:429,message:qn,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,se())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,se(),c)}}};var Qc=256*1024,Ca=6e4,Xc=e=>Math.ceil(e/2),Zc=new Uint8Array(new ArrayBuffer(0)),eu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Zc,t()},i=l=>{clearTimeout(o),o=ze(()=>{l.error(new Error(`attachment body idle for ${Ca} ms`)),a()},Ca)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Qc,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})},Ma=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=ut({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=rt({limit:e.concurrency,maxHeldPerOwner:Xc(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:R,readAttachment:m,cookie:p,fail:f}=s,y=e.maxBytes,S=i.spend(R,`attachment=${u} viewer=${R}`);if(S)return f(S.status,S.message,S.headers);let _=await n(c),D=await t.getAttachmentForUser(_,u,R);if(!D)return o.warn(`404 attachment=${u} viewer=${R} reason=not_visible`),f(404,"Attachment not found");if(D.fileSize!=null&&D.fileSize>y)return o.warn(`413 attachment=${u} viewer=${R} reason=db_size`),f(413,"Attachment too large");let h=Yn(D.fileType),g=`filename="${_a(D.fileName)}"; filename*=UTF-8''${Ia(D.fileName)}`,P=await l.acquire(R,c.signal);if(!P)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${R} reason=aborted`),f(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${R} reason=concurrency`),f(503,"Too many concurrent downloads",He(503)));let x=!1;try{let M=await m(D.filePath,{maxBytes:y,head:c.method==="HEAD",principal:r(R),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${R} reason=aborted`),f(503,"Attachment request aborted");if(!M.ok){if(!Pr(M.reason))return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=failure_reason`),f(500,ct);let H=Lr(M.reason);return M.reason==="not_found"&&a(u,!1),o.warn(`${H} attachment=${u} viewer=${R} reason=${M.reason} code=${M.code??"-"}`),f(H,Mr[H],He(H))}if(M.bytes.byteLength>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),f(500,ct);let j=c.method==="HEAD";if(j&&M.size!==void 0&&M.size>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),f(500,ct);if(!j&&M.size!==void 0&&M.size!==M.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=size_mismatch`),f(500,ct);let k=h??Yn(M.contentType),v=k!==null&&wa.has(k),b=v?k:"application/octet-stream",N=v&&d.kind!=="download"?"inline":"attachment",$=j?M.size:M.bytes.byteLength,F=new Headers({"Content-Type":b,"Content-Disposition":`${N}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Ut});return $!==void 0&&F.set("Content-Length",String($)),p&&F.append("Set-Cookie",p),a(u,!0),o.info(`200 attachment=${u} viewer=${R} type=${b} disposition=${N} bytes=${$??"-"}`),j?new Response(null,{status:200,headers:F}):(x=!0,new Response(eu(M.bytes,P),{status:200,headers:F}))}finally{x||P()}}};var Be=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Cy=Be.queueWaitMs+Be.readMs+Be.renderMs+Be.transferMarginMs;var ka=require("buffer"),Na=new Set([194,198,202,206]),tu=new Set([192,193,194,195]),va=216,ru=217,Oa=218,nu=4,ou=64,au=2,Pa=8,La=28,ft=12,jn=8,iu=20,Fa=ft+jn+10,su=2,dt=(e,t)=>e[t]<<8|e[t+1],$t=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},nt=(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},Ha=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Ba=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),Ua=e=>(e.stepsLeft-=1,e.stepsLeft>=0),$a=e=>e[0]===255&&e[1]===va,Va=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!Ua(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===ru)return"eoi";if(o===0||o===va)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=dt(e,n),i=n+a;return a<2||i>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=i,"segment")}},lu=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!Ua(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}},Ya=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=dt(e,r+1),a=dt(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}},qa=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>nu||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},ja=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:Na.has(e.marker)||t<e.components.length}),Wn=e=>{if(!$a(e))return null;let t=Ba(e.byteLength),r=null;for(let n=2;;){if(Va(e,n,t)!=="segment")return null;if(Ha(t.marker)){if(r!==null||(r=Ya(e,t),r===null))return null}else if(t.marker===Oa){if(r===null)return null;let o=qa(e,t);return o===null?null:ja(r,o.length)}n=t.end}},Wa=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*Pa)),i=Math.ceil(e.height*o/(r*Pa));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},za=e=>e.multiScan?Wa(e).reduce((r,n)=>r+n,0)*ou*au:0,cu=896,Ga=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!$a(e))return null;let n=ka.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=Ba(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let R=Va(e,u,o);if(R===null)return null;if(R==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,Ha(o.marker)){if(a!==null||!tu.has(o.marker)||(a=Ya(e,o),a===null))return null;let m=Wa(a);l=new Map;for(let[p,f]of a.components.entries()){let y=l.get(f.id);l.set(f.id,y===void 0?m[p]:Math.max(y,m[p]))}s=a.components.length*(Na.has(a.marker)?cu:1)}else if(o.marker===Oa){if(a===null||d===s)return null;let m=qa(e,o);if(m===null)return null;for(let f of m){let y=l.get(f);if(y===void 0)return null;c+=y}if(d+=1,i===null&&(i=ja(a,m.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let p=lu(n,o.end,o);if(p===null)return null;u=p}}},Ka=e=>{if(e.byteLength<24||dt(e,8)!==0||dt(e,10)!==13||!nt(e,12,"IHDR"))return null;let t=dt(e,16)*65536+dt(e,18),r=dt(e,20)*65536+dt(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},uu=e=>{if(nt(e,ft,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=$t(e,26,2)&16383,r=$t(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(nt(e,ft,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=$t(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return nt(e,ft,"VP8X")?e.byteLength<Fa?null:{width:$t(e,24,3)+1,height:$t(e,27,3)+1}:null},Ja=e=>{if(Ka(e)===null||e.byteLength<=La)return null;switch(e[La]){case 0:return!1;case 1:return!0;default:return null}},Qa=(e,t)=>{if(nt(e,ft,"VP8 "))return"lossy";if(nt(e,ft,"VP8L"))return"lossless";if(!nt(e,ft,"VP8X")||e.byteLength<Fa)return null;if((e[iu]&su)!==0)return"animated";let r=!1,n=t;for(let o=ft;o+jn<=e.byteLength;){if(n-=1,n<0)return null;if(nt(e,o,"VP8L"))return"lossless";if(nt(e,o,"VP8 "))return r?"lossy-alpha":"lossy";nt(e,o,"ALPH")&&(r=!0);let a=$t(e,o+4,4);o+=jn+a+a%2}return null},Xa={png:Ka,jpeg:Wn,webp:uu};var kr=Object.freeze(["image/webp","image/jpeg","image/png"]),Nr=1024*1024;var du=new Set(["image/png","image/jpeg","image/gif","image/webp"]),pu={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},mu=new Set(kr),yu=e=>typeof e=="string"&&mu.has(e),hu=256,vr=(e,t)=>e.fileType===null||!du.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,fu=[137,80,78,71,13,10,26,10],Ru=[255,216,255],Su=[[71,73,70,56,55,97],[71,73,70,56,57,97]],gu=[82,73,70,70],bu=[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},zn=e=>{if(ar(e,fu,0))return"png";if(ar(e,Ru,0))return"jpeg";for(let t of Su)if(ar(e,t,0))return"gif";return ar(e,gu,0)&&ar(e,bu,8)?"webp":null},Za=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:Ra([t])}},ei=(e,t)=>{if(!yu(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Nr)return"too_large";let r=pu[e.contentType];if(zn(e.bytes)!==r)return"signature";let n=Xa[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},ti=e=>{de("maxBytes",e.maxBytes,0),de("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)+hu;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 Gn=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=se(),l=new AbortController,s=!1,c,d,u=()=>{a(se()-i)},R=h=>{c=ze(()=>{s=!0,h({timedOut:!0}),d=ze(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},m=new Promise(R),p=AbortSignal.any([r,l.signal]),f=h=>{h(n(p))},y=new Promise(f),S=h=>(clearTimeout(c),clearTimeout(d),s&&o(se()-i,h.kind==="error"?{error:h.error}:null),h),_=y.then(h=>S({kind:"value",value:h}),h=>S({kind:"error",error:h}));return{outcome:Promise.race([y.then(h=>({timedOut:!1,value:h})),m]),settled:_}};var Rt={404:"Attachment not found",500:ct,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},ri=(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=ei(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Du=e=>{let t=new AbortController,r=()=>{t.abort()},n=ze(r,Be.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},ni=()=>{},Tu=(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)}),oi=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(m,p)=>{let f=p.then(ni,ni);l.set(m,f);let y=()=>{l.get(m)===f&&l.delete(m)};f.then(y)},c=async(m,p)=>{let f=l.get(m.key);if(f===void 0)return t.acquire(m.owner,p);let y=Du(p);try{if(await Tu(f,y.signal),y.signal.aborted)return null;let S=r.get(m.key);return S!==void 0?{...S,identity:"verified"}:await t.acquire(m.owner,y.signal)}finally{y.end()}},d=(m,p)=>{if(m.fileSize===null)return p.kind==="exact"?"verified":"unrecorded";if(p.kind==="exact"?p.bytes===m.fileSize:m.fileSize>p.maxBytes)return"verified";let y=p.kind==="exact"?String(p.bytes):`>${p.maxBytes}`;return i.warn(`size_mismatch expected=${m.fileSize} got=${y} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`),"unverified"},u=(m,p)=>(f,y)=>{let S=y===null?"":` message=${y.error instanceof Error?y.error.message:"unknown"}`;i.warn(`${m}_overrun ms=${f} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail${S}`)},R=(m,p)=>f=>{i.warn(`${m}_stuck ms=${f} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`)};return async(m,p)=>{let f=await c(m,p);if(f===null)return{kind:"failure",status:503,reason:p.aborted?"aborted":"queue"};if(typeof f!="function")return f;let y=f,S=null;try{if(p.aborted)return{kind:"failure",status:503,reason:"aborted"};let _=r.get(m.key);if(_!==void 0)return{..._,identity:"verified"};let D=Gn({budgetMs:Be.readMs,flightSignal:p,call:H=>m.readAttachment(m.filePath,{maxBytes:n,head:!1,principal:o(m.owner),signal:H}),onOverrun:u("read",m),onStuck:R("read",m)}),h=await D.outcome;if(h.timedOut)return S=D.settled,p.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(p.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=h.value;if(!g.ok&&g.reason!=="too_large")return Pr(g.reason)?(g.reason==="not_found"&&a(m.attachmentId,!1),{kind:"failure",status:Lr(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 P=d(m,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),x=H=>{P==="verified"&&r.set(m.key,H)},M=H=>(x(H),{...H,identity:P});if(!g.ok)return M({kind:"unrenderable",reason:"too_large"});let j=zn(g.bytes);if(j===null)return M({kind:"unrenderable",reason:"signature"});let k=Gn({budgetMs:Be.renderMs,flightSignal:p,call:H=>m.renderer.render(g.bytes,{format:j,maxWidth:m.box.maxWidth,maxHeight:m.box.maxHeight,signal:H}),onOverrun:u("render",m),onStuck:R("render",m)}),v=H=>{if(H.kind==="error")return;let K=ri(H.value,m.box);"entry"in K&&x(K.entry)},b=null,N=()=>(b===null&&(b=k.settled.then(v),s(m.key,b)),b);p.addEventListener("abort",N,{once:!0});let $=await k.outcome.finally(()=>p.removeEventListener("abort",N));if($.timedOut||p.aborted)return S=N(),p.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let F=ri($.value,m.box);return"entry"in F?M(F.entry):F.failure}finally{S===null?y():S.then(y,y)}}};var ai=()=>{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 li=10,Au=1/li,ii=1-Au,Eu=1024,wu=64,Iu=8,si="private, no-cache",_u="no-store",xu=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Cu=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},ci=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(h,g)=>ut({reason:h,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:P=>`viewer=${P} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*li),R=rt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:wu,maxPerOwner:Iu,maxWaitMs:Be.queueWaitMs}}),m=ti({maxBytes:l.cacheBytes,maxEntries:Eu}),p=ai(),f=oi({gate:R,cache:m,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),y=(h,g,P,x)=>{let M=`attachment=${h.attachmentId} viewer=${h.internalUserId} variant=thumbnail cache=${x}`;if(g.kind==="failure")return o[Cu(g)](`${g.status} ${M} reason=${g.reason} code=${g.code??"-"}`),h.fail(g.status,Rt[g.status],He(g.status));let j=xu[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${M} reason=${g.reason}${j}`),h.fail(404,Rt[404]);let k=g.identity==="verified"?{"Cache-Control":si,ETag:P}:{"Cache-Control":_u},v=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...k,"Content-Security-Policy":"default-src 'none'; sandbox",...Ut});return h.cookie&&v.append("Set-Cookie",h.cookie),o.info(`200 ${M} type=${g.contentType} bytes=${g.bytes.byteLength}${j}`),new Response(g.bytes,{status:200,headers:v})},S=(h,g)=>{let P=h.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return P===null?null:g.fail(P.status,P.message,P.headers)},_=h=>S(d,h),D=(h,g)=>g?S(u,h):_(h);return async(h,g)=>{let{request:P,attachmentId:x,internalUserId:M,readAttachment:j,cookie:k,fail:v}=h,b=vn[g],N=P.headers.get("If-None-Match"),$=N!==null,F=D(h,$);if(F)return F;let H=await n(P),K=await t.getAttachmentForUser(H,x,M),W=K!==null&&vr(K,i)?Za({rendererId:s.id,box:b,attachmentId:x,filePath:K.filePath,fileType:K.fileType,fileSize:K.fileSize}):null;if(W&&Hn(N,W.etag)){let w=new Headers({"Cache-Control":si,ETag:W.etag,...Ut});return k&&w.append("Set-Cookie",k),o.info(`304 attachment=${x} viewer=${M} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:w})}if($){let w=_(h);if(w)return w}if(!K)return o.warn(`404 attachment=${x} viewer=${M} variant=thumbnail reason=not_visible`),v(404,Rt[404]);if(!W)return d.refund(M,ii),o.info(`404 attachment=${x} viewer=${M} variant=thumbnail reason=not_eligible`),v(404,Rt[404]);let{key:ae,etag:Te}=W,ke=m.get(ae);if(ke)return d.refund(M,ii),y(h,{...ke,identity:"verified"},Te,"hit");let Re=w=>f({key:ae,attachmentId:x,filePath:K.filePath,fileSize:K.fileSize,box:b,owner:M,readAttachment:j,renderer:s},w),J;try{J=await p.join(ae,P.signal,Re)}catch(w){return o.error(`500 attachment=${x} viewer=${M} variant=thumbnail cache=miss reason=port_exception message=${w instanceof Error?w.message:"unknown"}`),v(500,Rt[500])}return y(h,J,Te,"miss")}};var Mu='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Pu=()=>Cr(403,Vn,{cookie:null}),ui=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=On(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Cr(404,Mr[404],{cookie:null}),crossSiteRejection:Pu}),di=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:Ea(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Ma({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:ci({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,R=(m,p,f={})=>Cr(m,p,{cookie:u,extraHeaders:f});try{let{user:m,cookie:p}=await t(c,{failureRedirect:null});if(u=p??null,!m)return R(401,"Unauthorized");let f=On(new URL(c.url).searchParams);if(f.kind==="invalid")return R(400,"Invalid attachment request");if(f.kind==="thumbnail"&&c.method!=="GET")return R(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return R(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return R(404,"Attachment not found");if(d.token===void 0)throw new Error(Mu);let y=s.idCodec.decode(d.token);if(y===null||!Ze(y))return R(400,"Invalid attachment token");let S=await r.getUserIdByExternalId(m.id);if(!S)return R(403,"Forbidden");let _={request:c,delivery:f,attachmentId:y,internalUserId:S,readAttachment:s.read,cookie:u,fail:R};return f.kind!=="thumbnail"?await s.serveOriginal(_):s.serveThumbnail===null?R(404,Rt[404]):await s.serveThumbnail(_,f.variant)}catch(m){if(m instanceof Response)throw m;return a.error(`500 attachment=? viewer=? reason=unexpected message=${m instanceof Error?m.message:"unknown"}`),R(500,ct)}}};var Lu=32*1024*1024,ku=60,Nu=4,vu=120,Ou=2,Fu=8*1024*1024,Or=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hu=e=>{if(e===void 0)throw it("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Or(e))throw X("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw it("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw X("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw X("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Bu=e=>{if(e===void 0)return null;if(!Or(e))throw X("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:Hu(e.renderer),rateLimitPerMinute:Me("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,vu),concurrency:Me("attachments.thumbnails.concurrency",e.concurrency,1,Ou),cacheBytes:Me("attachments.thumbnails.cacheBytes",e.cacheBytes,0,Fu)})},pi=e=>{let t=e;if(t===void 0)return null;if(!Or(t))throw X("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw it("attachments.idCodec","injected when attachments is given");if(!Or(r)||typeof r.encode!="function"||typeof r.decode!="function")throw X("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw it("attachments.read","injected when attachments is given");if(typeof n!="function")throw X("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Me("attachments.maxBytes",t.maxBytes,1,Lu),rateLimitPerMinute:Me("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,ku),concurrency:Me("attachments.concurrency",t.concurrency,1,Nu),thumbnails:Bu(t.thumbnails)})},Uu=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),Fr=e=>{for(let[t,r]of Uu)if(Object.hasOwn(e,t))throw it(r,`given in place of the flat key ${t}`)};var yi=8,$u=8*yi,Vu=128,Yu=2,hi=Yu*Vu,qu=4*hi,ju=6e4,Wu=6e4,zu="Too many reads",mi=Object.freeze(Object.keys(Pt).filter(e=>Pt[e].admission.includes("miss-gate"))),fi=e=>{let t=rt({limit:$u,maxHeldPerOwner:yi,queue:{max:qu,maxPerOwner:hi,maxWaitMs:ju}}),r=Ve({windowMs:Wu,tallies:mi,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${mi.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}})}},Hr=(e,t,r)=>{let n=e(t,r,{error:{message:zu}},503);for(let[o,a]of Object.entries(He(503)))n.headers.set(o,a);return n};var Ri=e=>{let t=e.get(Se.cursorReportHubId),r=e.get(Se.cursorBusinessDate),n=e.get(Se.cursorSnapshot),o=Wo(n)?n:null,a=null;if(t!==null){let l=We(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!jo(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=nr(e.get(Se.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var Br=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Gu=2,Ku=16,Ju=Gu*Ku,Qu=6e4,Si=()=>{},Xu=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},gi=e=>{let t=rt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Ju,queue:null}),r=Ve({windowMs:Qu,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 Si;if(a.aborted){if(t.canAcquire(n))return Si}else{let i=await t.acquire(n,a);if(i!==null)return Xu(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var Ur=30,Ei=4e3,Zu="stream interrupted by server error",ed="Too many streams",td=15e3,wi=Symbol("ids-stream-heartbeat"),bi=()=>{},Di=e=>e.return(void 0).then(bi,bi),rd=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(wi),td)}),stop:()=>clearTimeout(e)}};async function*Ti(e,t,r,n){let o=t?Ko(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Ei),e.length),l=Ct(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 Ii=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...tt});return e&&t.append("Set-Cookie",e),t},Ai=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await Di(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=rd();try{s===null&&(s=t.next());let R=await Promise.race([s,u.fired]);if(u.stop(),R===wi){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
2
|
-
`));return}s=null;let{value:
|
|
3
|
-
`))}catch(R){if(u.stop(),s=null,o(),l||r.aborted)return;R instanceof
|
|
4
|
-
`)),d.close()}catch{}}},cancel(){l=!0,o(),
|
|
5
|
-
`,
|
|
6
|
-
`)},
|
|
7
|
-
\u30C7\u30F3\u30D7\u30F3`,"\u30DD\u30C6\u30C8-25kg \u30A2--1 \u30FC\u30FC\u30E1\u30F3 \u4F50\u3005\u6728","\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CA",`\uFF71\uFF72\uFF73\uFF74\uFF75\uFF76\uFF9E\uFF77\uFF9E\uFF78\uFF9E\uFF79\uFF9E\uFF7A\uFF9E${String.fromCodePoint(8232)}\u6B21\u306E\u884C`],Cd=["","\u30A2","\u4F50"," "],Md=()=>JSON.stringify(xd.map(e=>qr(e,8))),Pd=e=>`dr-search-v${sd};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var Ld=async()=>{let e=(0,Ni.createHash)("sha256");e.update(JSON.stringify(ye.DEFAULT_NORMALIZE_OPTIONS));for(let t of Cd)await(0,Kn.setImmediate)(),e.update("\0"),e.update(Qn(_d(t)));return await(0,Kn.setImmediate)(),e.update("\0"),e.update(Md()),Pd(e.digest("hex"))},kd=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},ro=kd(Ld);var Nd=/^-+/u,vd=/\s+/u,ji=e=>{let t=Nd.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Od=(e,t)=>{let r=[...ji(e).map(n=>({text:n,tier:Mt.word})),...t.flatMap(n=>ji(n).map(o=>({text:o,tier:Mt.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},Fd=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),jr=(e,t)=>{if(e.length>we.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of(0,Wi.parseQuerySets)(Yr(e),t).sets){let i=[],l=new Set;for(let c of a.split(vd)){let d=$r(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>we.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=Od(d,Hi(c)),R=Fd(u);l.has(R)||(l.add(R),i.push({alternatives:u}))}if(i.length>we.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let s=JSON.stringify([...l].sort());n.has(s)||(n.add(s),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>we.maxSets?{ok:!1,reason:"too-many-sets"}:o>we.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},ur=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var zh=Object.freeze({sourceTypes:null,authors:null,customers:null}),Hd=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,zi=(e,t,r)=>{if(ra(e)&&Hd(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=jr(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var Gi=6e4,Bd=1,Ud=3200,Ki=2e3,$d=Object.freeze({search:Ud,reports:Ki,"search-marks":Ki,"search-facets":null}),Vd=(e,t)=>{let r=$d[e];return r===null?null:{max:t,maxPerOwner:wr,maxWaitMs:r}},dr=e=>{let{concurrency:t,route:r,logger:n}=e,o=ut({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:Gi,logger:n,windowFields:()=>`route=${r}`}),a=rt({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:Vd(r,t)}),i=Object.freeze({status:429,message:qn,headers:Object.freeze({"Retry-After":String(Bd)})}),l=Ve({windowMs:Gi,tallies:["busy"],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`busy_suppressed count=${c} since=${d} route=${r} concurrency=${t}`)}});return{admit:async(s,c)=>{let d=o.spend(s,r);if(d!==null)return{refusal:d};let u=await a.acquire(s,c);return u!==null?{release:u}:(o.refund(s,1),c.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};var ss=require("@aiquants/sse"),bt=require("@aiquants/sse/server");var qt=(e,t)=>{let r=e.message.data;if(!r)return{entry:{id:e.id,message:null},json:void 0};let n;try{n=JSON.parse(r)}catch(i){return t.error(`SSE message ${e.id} is not JSON:`,i),{entry:{id:e.id,message:null},json:void 0}}let o=Yo.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n,text:r});return{entry:Object.freeze({id:e.id,message:a}),json:n}},Yd=["externalComments","postedComments"],Ji=new WeakMap,qd=e=>{let t=Ji.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return Ji.set(e,r),r},Qi=e=>{let{recipientRawUserId:t,...r}=e;return r},Xi=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=qd(e);if(t){if(n.commentsRedacted===null){let o=Qi(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(Yd.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(Qi(r))),n.recipientRemoved};var ns=require("@aiquants/sse"),os=require("@aiquants/sse/shared-source");var St="daily-report:ids:",gt="daily-report:business-date:",Wr=(e,t)=>`${e}st:${t}`,no=e=>`${St}user:${e}:`,Zi=(e,t)=>Wr(no(e),t),jd=e=>`${gt}${e}:`,es=(e,t)=>Wr(jd(e),t),jt=e=>`daily-report:date:${e}:user:`,Lt=(e,t)=>`${jt(e)}${t}:`,ts=(e,t,r)=>Wr(Lt(e,t),r),Ye=e=>`daily-report:detail:${e}:user:`,zr=(e,t)=>`${Ye(e)}${t}:`,rs=(e,t,r)=>Wr(zr(e,t),r);var pt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},Wd=5e3,zd=Ir,Wt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=ge(t.logger,1,"SseReader"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return(0,os.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:ns.systemSseRuntime,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",i=>{this._logger.error("Redis client error:",i)});let o=!1,a=this._readLoop(n,t,r,()=>o);return async()=>{if(o=!0,n.isOpen)try{await n.quit()}catch{}await a}}async _readLoop(t,r,n,o){let a=n;try{for(;!o()&&t.isOpen;){let i=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:Wd,COUNT:zd});if(i)for(let l of i)for(let s of l.messages){a=s.id;let{entry:c,json:d}=qt(s,this._logger);this._invalidateCaches(d),r.next(c)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(St),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ye(n))}};var ls=Object.freeze({...or,route:"sse",frameworkDataRefusal:xr}),as=864e5,Gd={baseMs:2e3,jitterMs:8e3},oo=6e4,Kr=Ir,cs=JSON.stringify({type:"connected"}),is="0-0",Kd=(e,t,r)=>{if(t===null&&r===null)return!0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Ie(t,e.report.sourceType);case"comment-add":case"comment-delete":return Ie(r,e.sourceType);case"report-delete":return Ie(t,e.sourceType)}},Jd=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Ie(t,e.report.sourceType),Qd=(e,t)=>{e.writeEvent({event:null,id:t,data:cs})},Xd=(e,t,r)=>{let{message:n}=t;if(n===null)return;let{parsed:o,published:a}=n,i=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((o.type==="status-update"||i!==void 0)&&i!==r.internalUserId||!Kd(o,r.visibleSet,r.commentableSet)){Qd(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Xi(n,Jd(o,r.commentableSet))})},us=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:s}=e,c=async(d,u)=>{let{request:R,internalUserId:m,cursor:p}=u,f=u.initialScope.visible,y=u.initialScope.commentable,S=0,_=setInterval(()=>{let b=++S;n(R,"refresh").then(N=>{b===S&&(f=N.visible,y=N.commentable)})},oo);d.onClose(()=>clearInterval(_));let D=p===null?is:p,h=p!==null&&o!==void 0,g=[],P=null,x=b=>{pt(b.id,D)||(D=b.id,Xd(d,b,{internalUserId:m,visibleSet:f,commentableSet:y}))},M=async(b,N)=>{let[$]=await b.xRange(i,"-","+",{COUNT:1});return $!==void 0&&!pt($.id,N)},j=async(b,N)=>{if(await M(b,N))return!1;let $=N;for(;;){let F=await b.xRange(i,$,"+",{COUNT:Kr}),H=F[0];if(H!==void 0&&H.id!==$&&await M(b,$))return!1;for(let ee of F){if(P!==null&&pt(P,ee.id))return!0;pt(ee.id,D)||x(qt(ee,s).entry)}let K=F.at(-1);if(F.length<Kr||K===void 0||d.isClosed())return!0;$=K.id}},k=a.subscribe(b=>{if(!h){x(b);return}pt(b.id,D)||(P===null&&(P=b.id),g.push(b))},b=>{s.error(`[SSE:${m}] Fan-Out reader error:`,b),d.close()});if(d.onClose(k),p===null){await a.ready();try{let b=await o?.getClient();if(b){let N=await b.xRevRange(i,"+","-",{COUNT:1});N.length>0&&!pt(N[0].id,D)&&(D=N[0].id)}}catch{}}if(d.writeEvent({event:null,id:D===is?null:D,data:cs}),(0,bt.startSseHeartbeat)(d,{intervalMs:Uo,retry:Gd,runtime:ss.systemSseRuntime}),p===null||o===void 0)return;await a.ready();let v=await o.getClient();if(v===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await j(v,p)){d.writeRetry(as),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}h=!1;for(let b of g.splice(0))x(b)};return async({request:d,params:u})=>{let R,m=()=>{let f=new Headers;R!==void 0&&f.append("Set-Cookie",R);for(let[y,S]of Object.entries(tt))f.set(y,S);return f},p=f=>(0,bt.terminalStreamResponse)(f,{data:"",retryMs:as,headers:m()});try{let f=await t(d,{failureRedirect:null});R=f.cookie;let{user:y}=f;if(!y)return p("auth-required");let S=await r.getUserIdByExternalId(y.id);if(!S)return p("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:m()});let _=(0,bt.readLastEventId)(d,$o);if(_!==null&&!Vo(_))return s.warn(`[SSE:${S}] malformed resume cursor; asking the client to resync`),p("resync-required");let D=Br(d),h=await l.admit(S,"sse",D);if(h===null){let P=m();for(let[x,M]of Object.entries(He(503)))P.set(x,M);return new Response("Too many streams",{status:503,headers:P})}let g=!1;try{let P=await n(d,"initial");return(0,bt.createSseResponse)({requestSignal:D,headers:m(),onError:(x,M)=>s.error(`[SSE:${S}] ${M} failed:`,x),produce:x=>(g=!0,x.onClose(h),c(x,{request:d,internalUserId:S,cursor:_,initialScope:P}))})}finally{g||h()}}catch(f){if(f instanceof Response)throw f;let y=f instanceof Error?f:new Error(String(f));return s.error(`500 sse name=${y.name} message=${y.message}`),new Response("Internal Server Error",{status:500,headers:m()})}}};var ds=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...tt});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Zd=Object.freeze({...or,route:"api",frameworkDataRefusal:({params:e})=>Nn(e.endpoint)&&Pt[e.endpoint].body==="stream"?xr():null}),ep=Object.freeze({...or,route:"action"}),tp=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),fs=6e4,Rs=5,rp=Rs*Math.ceil(fs/500),np=2,op=6,ap=6e4,ip=Rs*np*op,sp=2,lp=10,cp=2,up=10,ps=(e,t)=>Math.max(e,wr)*t,Ss=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},dp=Object.freeze({etag:(e,t,r)=>Sa(e,t,r,200),"no-store":(e,t,r)=>Bn(t,r,200)}),pp=e=>Un(e.body==="json"?dp[e.cache]:null),ms=Un(null),ys=(e,t,r,n)=>Ss(e(t,r,{error:{message:n.message}},n.status),n.headers),hs=(e,t,r)=>Ss(e(t,r,null,503),He(503));function Jr(e){Fr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:de("service.titleMaxLength",r.titleMaxLength,1)},s=e.loginRedirectPath??"/auth/login",c=ge(e.logger,3,"API"),d=ge(e.logger,3,"Visibility"),u=ge(e.logger,1,"SSE"),R=ge(e.logger,1,"Attachment"),m=ge(e.logger,2,"Isolation"),p=ge(e.logger,2,"Action"),f=ge(e.logger,2,"Search"),y=ge(e.logger,2,"Refresh"),S=ge(e.logger,2,"Streams"),_=ge(e.logger,2,"Reads"),D=ut({reason:"refresh_rate_limit",limitPerWindow:ip,windowMs:ap,logger:y,windowFields:()=>"route=api"}),h=gi(S),g=fi(_),P=async(w,A,E,I,C,O)=>{let q=await r.getUserIdByExternalId(A.id);try{return await O(q===null?void 0:g.admissionFor(q,w,E.signal))}catch(B){if(B instanceof je)return Hr(C,E,I);throw B}},x=(w,A,E,I,C)=>{let O=D.spend(A.id,`endpoint=${w}`);return O===null?null:ys(C,E,I,O)},M=async(w,A="initial")=>{let E=e.resolveVisibleSourceTypes;if(!E)return Ue.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let I=await E(w,{reason:A});return I==null?Ue.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):Ue.restrictTo(I)}catch(I){return d.error("resolveVisibleSourceTypes threw; failing closed (deny all)",I),Ue.restrictTo([])}},j=async({request:w})=>{let{user:A,cookie:E}=await t(w,{failureRedirect:s}),I=new Headers;E&&I.append("Set-Cookie",E);let C=await r.getUserIdByExternalId(A.id),O=C?n(C):null;return{data:{user:A,userId:O},headers:I}},k=w=>{let{limiter:A}=w;return async(E,I,C,O,q,B)=>{if(A===null)return B(C,I,{error:{message:"Unknown endpoint"}},404);let z=w.parse(E);if(!z.ok)return B(C,I,z.invalid,400);let L=await r.getUserIdByExternalId(O.id);if(!L)return B(C,I,w.emptyAnswer(z.parsed),200);let{signal:G}=C,te=await A.admit(L,G);if("refusal"in te)return G.aborted?hs(B,C,I):ys(B,C,I,te.refusal);try{G.throwIfAborted();let Z=await w.read(z.parsed,{userId:L,user:O,scope:q},G);return G.throwIfAborted(),B(C,I,Z,200)}catch(Z){if(G.aborted&&Z===G.reason)return hs(B,C,I);throw Z}finally{te.release()}}},v=r.searchLimits===null?null:dr({...r.searchLimits,route:ie.search,logger:f}),b=r.searchLimits===null?null:dr({concurrency:ps(r.searchLimits.concurrency,sp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*lp,route:ie.reports,logger:f}),N=r.searchLimits===null?null:dr({concurrency:ps(r.searchLimits.concurrency,cp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*up,route:ie.searchMarks,logger:f}),$=r.searchLimits===null?null:dr({...r.searchLimits,route:ie.searchFacets,logger:f}),F={[ie.businessDate]:async(w,A,E,I,C,O)=>{let q=w.searchParams.get(Se.businessDate),B=q===null?null:Ht(q);if(B===null)return O(E,A,{error:{message:"Invalid business date"}},400);let z=nr(w.searchParams.get(Se.forceRefresh));if(z===null)return O(E,A,{error:{message:"Invalid forceRefresh"}},400);let L=z?x(ie.businessDate,I,E,A,O):null;return L!==null?L:P(ie.businessDate,I,E,A,O,async G=>{let te=await r.getDailyReportsByBusinessDateByExternalId(C,B,I.id,{forceRefresh:z,admission:G});return O(E,A,{businessDate:B,reports:te},200)})},[ie.idsStream]:_i({service:r,logger:c,streamSlots:h,missGate:g,refuseForcedRead:(w,A,E,I)=>x(ie.idsStream,w,A,E,I)}),[ie.report]:async(w,A,E,I,C,O)=>{let q=We(w.searchParams.get(Se.reportHubId));if(q===null)return O(E,A,{error:{message:"Invalid reportHubId"}},400);let B=nr(w.searchParams.get(Se.forceRefresh));if(B===null)return O(E,A,{error:{message:"Invalid forceRefresh"}},400);let z=B?x(ie.report,I,E,A,O):null;return z!==null?z:P(ie.report,I,E,A,O,async L=>{let G=await r.getDailyReportDetailByIdByExternalId(C,q,I.id,{snapshot:!0,forceRefresh:B,admission:L});return G?O(E,A,{report:G},200):O(E,A,{error:{message:"Report not found"}},404)})},[ie.search]:k({limiter:v,parse:w=>{let A=w.searchParams.get(Se.searchQuery),E=Ln(w.searchParams.get(Se.searchCombine));if(A===null||E===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let I=oa(w.searchParams,r.searchFilterSourceTypes);if(!I.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:I.reason}}};let C=zi(A,E,I.filters);if(!C.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:C.reason}}};let{criteria:O}=C;return{ok:!0,parsed:{criteria:O,words:O.plan===null?[]:ur(O.plan)}}},emptyAnswer:({words:w})=>Mn([],w),read:async({criteria:w,words:A},{userId:E,scope:I})=>Mn(await r.searchDailyReports(I,E,w),A)}),[ie.reports]:k({limiter:b,parse:w=>{let A=kn(w.searchParams.get(Se.reportIds));return A===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:A}},emptyAnswer:()=>({reports:[]}),read:async(w,{user:A,scope:E})=>({reports:await r.getDailyReportDetailsByIdsByExternalId(E,w,A.id)})}),[ie.searchMarks]:k({limiter:N,parse:w=>{let A=w.searchParams.get(Se.searchQuery),E=Ln(w.searchParams.get(Se.searchCombine));if(A===null||E===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let I=jr(A,E);if(!I.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:I.reason}}};let C=kn(w.searchParams.get(Se.reportIds));return C===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:I.plan,ids:C}}},emptyAnswer:({plan:w})=>({wordsDigest:Er(ur(w)),reports:[],deferred:[]}),read:({plan:w,ids:A},{userId:E,scope:I},C)=>r.markDailyReportSearchHits(I,E,w,A,{signal:C})}),[ie.searchFacets]:k({limiter:$,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(w,{userId:A,scope:E})=>r.listDailyReportSearchFacets(E,A)})},H=async({request:w,params:A})=>{let{user:E,cookie:I}=await t(w,{failureRedirect:null}),C=I??null;if(!E)return ms(w,C,{error:{message:"Unauthorized"}},401);let O=A.endpoint;if(!Nn(O))return ms(w,C,{error:{message:"Unknown endpoint"}},404);let q=Pt[O],B=pp(q),z=ya[q.body];if(!z.includes(w.method)){let G=B(w,C,{error:{message:"Method not allowed"}},405);return G.headers.set("Allow",z.join(", ")),G}let L=se();try{let G=new URL(w.url),te=await M(w),Z=await F[O](G,C,w,E,te,B);return q.body==="json"&&c.debug(Z.headers.has("ETag")?`${Z.status} endpoint=${O} etag_match=${Z.status===304}`:`${Z.status} endpoint=${O}`),Z}catch(G){let te=se()-L,Z=G instanceof Error?G:new Error(String(G));return c.error(`500 endpoint=${O} elapsed=${te}ms name=${Z.name} code=${"code"in Z?Z.code:"N/A"} message=${Z.message}`,Z),B(w,C,{error:{message:"Internal Server Error"}},500)}},K=ma(p),ee=ut({reason:"rate_limit",limitPerWindow:rp,windowMs:fs,logger:p,windowFields:()=>"route=action"}),W=async(w,A,E,I,C)=>{let{clientTempId:O}=w;if(w.intent==="create"){let L=await r.createDailyReport(A,w.businessDate,O);return C(w,L.reportHubId,{report:L})}let{reportHubId:q,businessDate:B}=w,z=async(L,G)=>{try{let te=await G(L.value);return C(L,q,{updatedStatus:{isStarred:te.isStarred,isRead:te.isRead},operationTimestamp:L.operationTimestamp})}catch(te){if(te instanceof Error&&te.message==="Not Found")return I({error:"Report not found"},{status:404});throw te}};switch(w.intent){case"update":try{return await r.updateDailyReport(q,A,w.changes,O),C(w,q,{})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return I({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return I({error:"Report not found"},{status:404})}throw L}case"publish":try{let L=await r.publishDailyReport(q,A,O);return C(w,q,{report:L})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return I({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return I({error:"Report not found"},{status:404})}throw L}case"delete":try{return await r.deleteDailyReport(q,A,O),C(w,q,{})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return I({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return I({error:"Report not found"},{status:404})}throw L}case"toggleStar":return await z(w,L=>r.setStarStatus(E,A,q,B,L,O));case"toggleRead":return await z(w,L=>r.setReadStatus(E,A,q,B,L,O));case"addComment":try{let L=await r.addComment(E,A,q,w.content,B,O);return C(w,q,{newComment:L})}catch(L){if(L instanceof Error){if(L.message==="Not Found")return I({error:"Report not found"},{status:404});if(L.message.startsWith("Comments are restricted"))return I({error:"Comments are restricted for this report"},{status:403})}throw L}case"deleteComment":try{return await r.deleteComment(E,A,q,w.commentId,B,O),C(w,q,{deletedCommentId:w.commentId})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return I({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return I({error:"Comment not found"},{status:404})}throw L}}},ae=async({request:w,params:A})=>{let{user:E,cookie:I}=await t(w,{failureRedirect:null}),C=(B,z)=>ds(B,{...z,setCookie:I}),O=(B,z,L)=>ds(tp(B,z,L),{setCookie:I});if(!E)return C({error:"Unauthorized"},{status:401});let q=se();try{if(A.endpoint!==ie.action)return C({error:"Unknown endpoint"},{status:404});let B=ee.spend(E.id,"action");if(B!==null)return C({error:B.message},{status:B.status,headers:B.headers});let z=await pa(w,l);if("refusal"in z){let{refusal:Z}=z;return Z.status===413&&K(Z.measuredBy),C({error:Z.error},{status:Z.status})}let{command:L}=z;if(L.intent==="clearCache"&&!e.enableDevCacheClear)return C({error:"Invalid intent"},{status:400});let G=await r.getUserIdByExternalId(E.id);if(!G)return C({error:"User not found"},{status:404});let te=await M(w);return L.intent==="clearCache"?(await r.clearCache(),C({status:"OK",intent:"clearCache"})):await W(L,G,te,C,O)}catch(B){if(B instanceof Response)throw B;let z=se()-q,L=B instanceof Error?B:new Error(String(B));return c.error(`500 action elapsed=${z}ms name=${L.name} message=${L.message}`,L),C({error:"Internal Server Error"},{status:500})}},Te=us({authenticate:t,service:r,resolveViewerScope:M,redis:o,sseReader:a,streamKey:i,streamSlots:h,logger:u}),ke=di({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:M,logger:R}),Re=Aa(m),J=(w,A)=>async E=>{let I=Da(E.request)?w.frameworkDataRefusal(E):null;if(I!==null)throw I;return Ta(E.request,w)?(Re(w.route,E.request),w.crossSiteRejection()):A(E)};return{index:{loader:j},api:{loader:J(Zd,H),action:J(ep,ae)},sse:{loader:J(ls,Te)},attachment:{loader:J(ui,ke)}}}var Gt=require("@aiquants/mssql"),fe=require("drizzle-orm");var mp=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],yp=["document","comment"],hp=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],fp=["hubId","ordinal","authorUserId","commentText"],ao=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},gs=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw pn(e,n,r)},bs=(e,t,r)=>{if(typeof t!="object"||t===null)throw X(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw X(`${e}.${o}`,"a column",n[o])},Ds=(e,t)=>{if(!ao(e))throw X("search","a plain object",e);gs("search key",e,mp);let{tables:r}=e;if(!ao(r))throw X("search.tables","a plain object with document and comment",r);gs("search.tables key",r,yp),bs("search.tables.document",r.document,hp),bs("search.tables.comment",r.comment,fp);let n=new Map;if(e.externalSourceTexts!==void 0){if(!ao(e.externalSourceTexts))throw X("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw pn("search.externalSourceTexts key",o,t);if(typeof a!="function")throw X(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:de("search.concurrency",e.concurrency,1),rateLimitPerMinute:de("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var Dt=e=>{let t=typeof e=="object"&&e!==null?e.recordset:void 0;if(!Array.isArray(t))throw new Error("[daily-report] search: the database result has no recordset");return t},kt=(e,t)=>{let r=typeof e=="string"?We(e):typeof e=="number"&&Ze(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},Nt=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};var U=require("drizzle-orm");var mt=require("drizzle-orm"),Ts=e=>{if(e.length===0)throw new Error("[daily-report] draft rule: draftLabelNames must hold at least one name (a rule without names would show every draft to every viewer)");return mt.sql.join(e.map(t=>mt.sql`${t}`),mt.sql`, `)},Qr=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return mt.sql`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${Ts(t)}))`},As=(e,t)=>{let{hubLabel:r,label:n}=e;return mt.sql`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${Ts(t)}))`},Xr=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?mt.sql`${o.userId} = ${t} OR ${o.userId} IS NULL`:mt.sql`${o.userId} = ${t}`;return mt.sql`(${a} OR NOT ${Qr(e,r)})`};var Rp=/[[%_]/gu,Sp=e=>e.replace(Rp,t=>`[${t}]`),Es=e=>`%${Sp(e)}%`;var Ge=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),vt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),mr=Object.freeze({value:"value"}),_e=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),V=e=>U.sql`${U.sql.identifier(e.name)}`,pr=e=>U.sql.join(e.map(t=>U.sql`${t}`),U.sql`, `),ws=(e,t)=>U.sql`SELECT ${V(e.id)} AS ${U.sql.identifier(_e.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${pr(t)}) ORDER BY ${e.id}`,gp=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>Es(u.text)),l=U.sql.join(i.map(u=>U.sql`${o.searchText} LIKE ${u}`),U.sql` OR `),s=U.sql.join(i.map(u=>U.sql`${a.commentText} LIKE ${u}`),U.sql` OR `),c=lr(n.sourceType,r.scope.commentable),d=c===void 0?U.sql``:U.sql` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return U.sql`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},Is=(e,t,r)=>U.sql`(${U.sql.join(t.words.map(n=>gp(e,n,r)),U.sql` AND `)})`,io=(e,t,r,n)=>{let{hub:o}=e,a=[U.sql`${o.deletedAt} IS NULL`,Xr(e,t.userId,r,"author")],i=lr(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(U.sql`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},bp=(e,t)=>{let{hub:r}=e,{document:n}=e.search,o=[];if(t.sourceTypes!==null){if(t.sourceTypes.size===0)throw new Error("[daily-report] search: a source-type filter must hold at least one source type");o.push(U.sql`LOWER(${r.sourceType}) IN (${pr([...t.sourceTypes])})`)}return t.authors!==null&&o.push(U.sql`${n.authorName} IN (${pr(t.authors)})`),t.customers!==null&&o.push(U.sql`${n.customerName} IN (${pr(t.customers)})`),o},_s=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...io(e,r,n,o),...bp(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?U.sql` AND `:U.sql` OR `;s.push(U.sql`(${U.sql.join(l.sets.map(d=>Is(e,d,r)),c)})`)}return U.sql`SELECT ${V(a.id)} AS ${U.sql.identifier(Ge.reportHubId)}, CONVERT(char(10), ${V(a.businessDate)}, 23) AS ${U.sql.identifier(Ge.businessDate)}, ${V(a.sourceType)} AS ${U.sql.identifier(Ge.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${U.sql.join(s,U.sql` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},xs=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=U.sql.join(t.sets.map((s,c)=>U.sql`(CASE WHEN ${Is(e,s,r)} THEN ${2**c} ELSE 0 END)`),U.sql` + `);return U.sql`SELECT ${V(a.id)} AS ${U.sql.identifier(vt.reportHubId)}, ${l} AS ${U.sql.identifier(vt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${U.sql.join(io(e,r,n,o),U.sql` AND `)}`},Cs=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...io(e,r,n),U.sql`${i} IS NOT NULL`];return U.sql`SELECT ${i} AS ${U.sql.identifier(mr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${U.sql.join(l,U.sql` AND `)} GROUP BY ${i} ORDER BY ${i}`},Ms=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(s=>({[n.hubId.name]:s.hubId,[n.searchText.name]:s.searchText,[n.sourceDigest.name]:s.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:s.authorName,[n.customerName.name]:s.customerName}))),i=JSON.stringify(t.flatMap(s=>s.comments.map(c=>({[o.hubId.name]:s.hubId,[o.ordinal.name]:c.ordinal,[o.authorUserId.name]:c.authorUserId,[o.commentText.name]:c.commentText})))),l=JSON.stringify(t.map(s=>s.hubId));return U.sql`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${V(n.hubId)} bigint, ${V(n.searchText)} nvarchar(max), ${V(n.sourceDigest)} char(64), ${V(n.normalizerVersion)} varchar(64), ${V(n.authorName)} nvarchar(max), ${V(n.customerName)} nvarchar(max))) AS s ON t.${V(n.hubId)} = s.${V(n.hubId)}
|
|
8
|
-
WHEN MATCHED THEN UPDATE SET t.${
|
|
9
|
-
WHEN NOT MATCHED THEN INSERT (${
|
|
1
|
+
"use strict";var cn=Object.defineProperty;var Xl=Object.getOwnPropertyDescriptor;var Zl=Object.getOwnPropertyNames;var ec=Object.prototype.hasOwnProperty;var _o=e=>{throw TypeError(e)};var tc=(e,t)=>{for(var r in t)cn(e,r,{get:t[r],enumerable:!0})},rc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Zl(t))!ec.call(e,o)&&o!==r&&cn(e,o,{get:()=>t[o],enumerable:!(n=Xl(t,o))||n.enumerable});return e};var nc=e=>rc(cn({},"__esModule",{value:!0}),e);var xo=(e,t,r)=>t.has(e)||_o("Cannot "+r);var Xt=(e,t,r)=>(xo(e,t,"read from private field"),r?r.call(e):t.get(e)),un=(e,t,r)=>t.has(e)?_o("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),dn=(e,t,r,n)=>(xo(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Em={};tc(Em,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>Nr,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>kr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>Ao,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>br,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>To,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>Gr,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>co,DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS:()=>Eo,DailyReportSseReader:()=>zt,DailyReportViewerScope:()=>qe,SqlResultCache:()=>Ht,buildDailyReportSseStreamKey:()=>Do,createDailyReportHandlers:()=>Kr,createDailyReportServer:()=>Tm,createDailyReportService:()=>an,createDailyReportVisibilityCache:()=>Ol,createEpochStore:()=>Dr,createSharpThumbnailRenderer:()=>vl,defineDailyReportSchema:()=>gl,defineDailyReportSearchSchema:()=>bl,encodeIdsStreamRows:()=>xt,isStreamIdLte:()=>pt,parseClientTempId:()=>xr,predictSharpThumbnailWorkingSetBytes:()=>Nl,readDailyReportSseStreamEntry:()=>Yt,transformJsonArray:()=>Sl});module.exports=nc(Em);var Et=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,Q=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Et(r)}`),Qe=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),pn=(e,t,r)=>Q(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ae=(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)},Me=(e,t,r,n)=>t===void 0?n:ae(e,t,r),Zt=(e,t)=>{if(t===void 0)throw Qe(e,"a function");if(typeof t!="function")throw Q(e,"a function",t);return t};var ie=()=>Math.floor(performance.now());var mn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),We=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},Dr=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),er=(e,t)=>t?e.map(r=>structuredClone(r)):e,oc=8,ac=32,ic=24,sc=16,lc=-(2**30),cc=2**30-1,uc=e=>Number.isInteger(e)&&e>=lc&&e<=cc&&!Object.is(e,-0),dc=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=ac,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=oc*a.length;for(let i of a)typeof i=="string"?r+=ic+2*i.length:typeof i=="number"&&!uc(i)?r+=sc:typeof i=="object"&&i!==null&&n.push(i)}return r},Ht=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-ie())<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:ie()+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 We(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:ie()+(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 We("aborted");return this.dropBucket(r),er(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ie())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),er(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),er(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return er(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new We("aborted");return er(await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};this.readOwnOrRetry=async(t,r)=>{try{return await t}catch(n){let{admission:o}=r;if(!(n instanceof We&&(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=Me("cacheDefaultTtlMs",t.defaultTtlMs,1,mn.defaultTtlMs),this.maxBuckets=Me("cacheMaxBuckets",t.maxBuckets,1,mn.maxBuckets),this.maxBytes=Me("cacheMaxBytes",t.maxBytes,1,mn.maxBytes),this.lastSweepAt=ie()}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=dc(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=ie();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 pc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Co=e=>e<10?`0${e}`:`${e}`,mc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Co(e.getMonth()+1),n=Co(e.getDate());return`${t}-${r}-${n}`},Ft=e=>{let t=pc.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}`},Ar=e=>Ft(e)===e;var He=e=>e==null?null:e instanceof Date?mc(e):Ft(e);var Mo=require("zod/v3"),Xe=e=>Number.isSafeInteger(e)&&e>0,we=Mo.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var me=require("zod/v3");var Tr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;var wt=Symbol("daily-report wire mismatch"),Ze=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),wt),No=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,It=(e,t)=>({code:"invalid_type",expected:e,received:No(t)}),yc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hc=e=>{let t=0;for(let r in e)t+=1;return t},Po=(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},Ut=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!yc(n))return Ze(o,null,It("object",n));let a=null,i=!1,l=0;for(let s=0;s<t.length;s+=1){let c=t[s],d=n[c];d!==void 0&&(l+=1);let u=r[s](d,o,c);if(u===wt){i=!0;continue}a===null&&u!==d&&(a=Po(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?wt:a!==null?a:hc(n)===l?n:Po(n,t,t.length)}},tr=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},rr=e=>(t,r,n)=>{if(!Array.isArray(t))return Ze(r,n,It("array",t));r.path.push(n);let o=t,a=!1;for(let i=0;i<t.length;i+=1){let l=t[i],s=e(l,r,i);s===wt?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?wt:o},ce=(e,t,r)=>e==null||typeof e=="string"?e:Ze(t,r,It("string",e)),Lo=(e,t,r)=>e===null||typeof e=="string"?e:Ze(t,r,It("string",e)),ko=(e,t,r)=>typeof e=="string"?e:Ze(t,r,It("string",e)),fc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:Ze(t,r,It("number",e)),nr=(e,t,r)=>typeof e=="boolean"?e:Ze(t,r,It("boolean",e)),yn=(e,t,r)=>{if(typeof e=="number"&&Xe(e))return e;for(let{message:n,path:o,...a}of we.safeParse(e).error.issues)Ze(t,r,a);return wt},vo={present:!0,absent:!0,unknown:!0},Oo=Object.keys(vo),Rc=Oo.map(e=>`'${e}'`).join(" | "),Sc=(e,t,r)=>typeof e!="string"?Ze(t,r,{code:"invalid_type",expected:Rc,received:No(e)}):Object.hasOwn(vo,e)?e:Ze(t,r,{code:"invalid_enum_value",received:e,options:[...Oo]}),Ho=Ut({name:ce,affiliation:ce}),Fo=Ut({name:ce,text:ce,color:ce}),Uo=Ut({id:yn,name:ce,color:ce}),$o=Ut({id:yn,userId:ce,userName:ce,content:ce,createdAt:ce,isMine:nr}),gc=Ut({id:ko,fileName:ko,fileType:Lo,fileSize:fc,createdAt:Lo,state:Sc,hasThumbnail:nr}),bc=Ut({reportHubId:yn,date:ce,createdAt:ce,author:ce,userId:ce,sourceType:ce,employeeName:ce,updatedBy:ce,updatedAt:ce,category:ce,creationCategory:ce,visitTimeFrom:ce,visitTimeTo:ce,customerName:ce,interviewers:rr(tr(Ho)),subject:ce,content:ce,externalComments:rr(tr(Fo)),isRead:nr,isStarred:nr,isDraft:nr,labels:rr(tr(Uo)),postedComments:rr(tr($o)),attachments:rr(tr(gc))}),or=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===wt?{ok:!1,issues:r.issues}:{ok:!0,value:n}},Bo=e=>or(bc,e),Vo=e=>or(Ho,e),qo=e=>or(Fo,e),Yo=e=>or(Uo,e),jo=e=>or($o,e);var Wo=15e3,zo="lastEventId",Dc=/^\d{1,15}-\d{1,15}$/,Go=e=>Dc.test(e),ar=e=>me.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 me.z.NEVER}),Um=ar(Vo),$m=ar(qo),Bm=ar(Yo),Ac=ar(jo),hn=ar(Bo),_t=me.z.string().regex(Tr),Tc=me.z.object({type:me.z.literal("connected")}),fn=me.z.object({type:me.z.literal("status-update"),reportHubId:we,statusType:me.z.enum(["star","read"]),value:me.z.boolean(),clientTempId:_t,recipientRawUserId:we.optional()}),Rn=me.z.string(),Sn=me.z.object({type:me.z.literal("comment-add"),reportHubId:we,comment:Ac,clientTempId:_t,recipientRawUserId:we.optional(),sourceType:Rn}),gn=me.z.object({type:me.z.literal("comment-delete"),reportHubId:we,commentId:we,clientTempId:_t,recipientRawUserId:we.optional(),sourceType:Rn}),bn=me.z.object({type:me.z.literal("report-create"),reportHubId:we,report:hn,clientTempId:_t,recipientRawUserId:we.optional()}),Dn=me.z.object({type:me.z.literal("report-update"),reportHubId:we,report:hn,clientTempId:_t,recipientRawUserId:we.optional()}),An=me.z.object({type:me.z.literal("report-publish"),reportHubId:we,report:hn,clientTempId:_t,recipientRawUserId:we.optional()}),Tn=me.z.object({type:me.z.literal("report-delete"),reportHubId:we,clientTempId:_t,sourceType:Rn}),Ko=me.z.discriminatedUnion("type",[Tc,fn,Sn,gn,bn,Dn,An,Tn]);var Jo="ids-columns";var Ec=/^[0-9a-f]{1,16}$/,Qo=e=>Xe(e.reportHubId)&&(e.businessDate===null||Ar(e.businessDate)),Xo=e=>typeof e=="string"&&Ec.test(e),jm=Object.freeze({kind:"absent"}),Wm=Object.freeze({kind:"value",value:null});var xt=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:R}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let p=R===void 0?null:R,m=s.get(p);m===void 0&&(m=i.length,i.push(p),s.set(p,m)),l.push(m)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},Er=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+(?=.)/,"")},Zo=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,wc=(e,t,r,n)=>Zo(e,t,r,n)<0,En=(e,t)=>Zo(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),ea=e=>{for(let t=1;t<e.length;t++)if(!wc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},ta=(e,t)=>{let r=e.findIndex(n=>En({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var se=Object.freeze({businessDate:"business-date",idsStream:Jo,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),be=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var ra=(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)}}},Jm=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),na=e=>`[DailyReport${e}]`,De=(e,t,r)=>e===void 0?ra(t,na(r)):ra(0,na(r),e);var Ic="legacy-",wn=e=>`${Ic}${e}`;var _c=/^[1-9][0-9]*$/,xc=/^(?:0|[1-9][0-9]*)$/,ze=e=>{if(e===null||!_c.test(e))return null;let t=Number(e);return Xe(t)?t:null},In=e=>{if(e===null||!xc.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},_n=e=>e==="true"?!0:e==="false"?!1:null,ir=e=>e===null?!1:_n(e);var oa=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),it=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var Cc=16777619,xn=2166136261,Cn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,Cc);return o>>>0},aa=e=>Cn(xn,e,0,e.length),Mc=String.fromCodePoint(3),Pc=String.fromCodePoint(2),Lc=String.fromCodePoint(1),wr=e=>aa(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Mc)).join(Pc)).join(Lc));var ia=e=>e==="intersection"||e==="union",xe=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Mn=2,Ir=2,Ct=Object.freeze({word:0,reading:1});var Pn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var ry=2*(1+Mn);var kc=require("zod/v3");var Be=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var _r=Math.max(1,Math.floor(10.556701030927835));var Ge=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Le=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),Ge(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var st=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var cy=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),Nc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Ln=e=>{let t=e.trim();return t.length===0?null:t.replace(Nc,"\uFFFD")},vc=e=>{let t=Ln(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>st.maxValueLength?"filter-value-too-long":null},Oc=e=>{if(e.length>st.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=vc(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},Hc=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},sa=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Oc(t);if(r!==null)return r}return Hc(e)>st.maxTotalValueLength?"filters-too-long":null};var la=e=>e.trim().length===0;var xr=e=>e!==null&&Tr.test(e)?e:null,kn=e=>ia(e)?e:null,Nn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>xe.maxDetailIds)return null;let r=[];for(let n of t){let o=ze(n);if(o===null||r.includes(o))return null;r.push(o)}return r},ca=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},ua=(e,t)=>{let r={authors:e.getAll(be.searchAuthor),sourceTypes:e.getAll(be.searchSourceType),customers:e.getAll(be.searchCustomer)},n=sa(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:ca(r.authors),customers:ca(r.customers)}}},da=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var ma=Object.freeze({status:400,error:"Invalid form"}),ya=e=>({status:413,error:"Form too large",measuredBy:e}),Fc=(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)}}))},Uc=async e=>{let t=In(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:ya("declared")};let r=!1,n=e.body===null?null:Fc(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?ya("counted"):ma}}let l=da(i);return l===null?{refusal:ma}:{fields:l}},ha=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=_n(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},Ra=Object.freeze({update:(e,t,r)=>{let n=e.get(Be.title),o=e.get(Be.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:ha("toggleStar",Be.isStarred),toggleRead:ha("toggleRead",Be.isRead),addComment:(e,t)=>{let r=e.get(Be.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=ze(e.get(Be.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),$c=e=>Object.hasOwn(Ra,e),Bc=(e,t)=>{let r=e.get(Be.intent),n=e.get(Be.businessDate),o=n===null?null:Ft(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Be.operationTimestamp),i=In(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Be.clientTempId);if(!l)return{error:"clientTempId required"};let s=xr(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=ze(e.get(Be.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!$c(r)?{error:"Invalid intent"}:Ra[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Sa=async(e,t)=>{let r=await Uc(e);if("refusal"in r)return r;let n=Bc(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Vc=6e4,qc="form_too_large",fa=["declared","counted"],ga=e=>{let t=Le({windowMs:Vc,tallies:fa,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${fa.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(qc,r,n)}};var Mt=Object.freeze({[se.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[se.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[se.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[se.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[se.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[se.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[se.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),ba=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),vn=e=>e!==void 0&&Object.hasOwn(Mt,e);var On=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Da=e=>Object.hasOwn(On,e);var Yc="download",jc="thumbnail",Wc="1";var Hn=e=>{let t=e.getAll(jc),r=e.getAll(Yc);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Da(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Wc?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var Aa=require("crypto"),Fn=e=>`"${(0,Aa.createHash)("sha256").update(e).digest("hex")}"`,Ta=e=>Fn(JSON.stringify(e));var et=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),Un=(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},Ea=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=Fn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...et});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&Un(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},$n=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...et});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},Bn=e=>(t,r,n,o)=>{if(o!==200)return $n(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)},zc=5e3/1e3,Gc=new Map([[503,zc]]),Ae=e=>{let t=Gc.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var qn="Cross-site request rejected",Kc="Not Found",Jc=new Set(["same-origin","none"]),Qc=new Set(["GET","HEAD","OPTIONS"]),wa=["api","action","sse","attachment"],Ia=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...et}}),Xc=()=>Ia(403,qn),Cr=()=>Ia(404,Kc),sr=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:Xc}),_a=e=>new URL(e.url).pathname.endsWith(".data"),Zc=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},xa=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Qc.has(e.method)||Zc(e)):Jc.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},eu=6e4,tu="refusals",ru=32,nu=/^[a-z-]+$/,Vn=e=>{if(e===null)return"-";let t=e.slice(0,ru);return nu.test(t)&&t===e?e:JSON.stringify(t)},Ca=e=>{let t=Le({windowMs:eu,tallies:wa,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${wa.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${Vn(a.get("Sec-Fetch-Site"))} mode=${Vn(a.get("Sec-Fetch-Mode"))} dest=${Vn(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(tu,r,o)}};var Ma=(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 ou="same-origin",au="SAMEORIGIN",$t=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":ou,"X-Frame-Options":au}),Mr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...$t});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Pa=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),iu=/^[\x20-\x7E]+$/,su=/^[\w.+-]+\/[\w.+-]+/,Yn=e=>e&&iu.test(e)&&su.test(e)?e:null,lu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,La=e=>encodeURIComponent(e.replace(lu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),ka=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),lr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},Na={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Pr=e=>typeof e=="string"&&Object.hasOwn(Na,e),Lr=e=>Na[e],lt="Attachment request failed";var tt=e=>{let t=ae("limit",e.limit,1),r=ae("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ae("queue.max",e.queue.max,0),maxPerOwner:ae("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ae("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(y,h)=>y.get(h)??0,c=(y,h,T)=>{let D=s(y,h)+T;D<=0?y.delete(h):y.set(h,D)},d=y=>s(l,y)<r,u=y=>o<t&&d(y),R=y=>(o+=1,c(l,y,1),S(y)),p=()=>{let y=-1,h=r;for(let[T,D]of a.entries()){let f=s(l,D.owner);if(f<h&&(y=T,h=f,f===0))break}return y},m=()=>{for(;o<t;){let y=p();if(y<0)return;let[h]=a.splice(y,1);c(i,h.owner,-1),h.grant(R(h.owner))}},S=y=>{let h=!1;return()=>{h||(h=!0,o-=1,c(l,y,-1),m())}};return{canAcquire:u,acquire:(y,h)=>{if(h.aborted)return Promise.resolve(null);if(u(y))return Promise.resolve(R(y));if(n===null||a.length>=n.max||s(i,y)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:T}=n,D=f=>{let b=()=>{let $=a.indexOf(_);$<0||(a.splice($,1),c(i,y,-1),C(),f(null))},M=Ge(b,T),C=()=>{clearTimeout(M),h.removeEventListener("abort",b)},_={owner:y,grant:$=>{C(),f($)}};a.push(_),c(i,y,1),h.addEventListener("abort",b,{once:!0})};return new Promise(D)}}};var cu=1024,jn="Too many requests",uu=(e,t)=>{ae("limitPerWindow",e,1),ae("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let s=l??{tokens:e,lastRefillMs:i};n(s,i),r.set(a,s);for(let c of r.keys()){if(r.size<=cu)break;r.delete(c)}return s};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let s=r.get(a);s&&(n(s,i),s.tokens=Math.min(e,s.tokens+l))}}},ct=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ae("windowMs",r,1e3)%1e3!==0)throw Q("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=uu(e.limitPerWindow,r),i=Object.freeze({status:429,message:jn,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Le({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,ie())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,ie(),c)}}};var pu=256*1024,va=6e4,mu=e=>Math.ceil(e/2),yu=new Uint8Array(new ArrayBuffer(0)),hu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=yu,t()},i=l=>{clearTimeout(o),o=Ge(()=>{l.error(new Error(`attachment body idle for ${va} ms`)),a()},va)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+pu,r.byteLength);if(s>n&&l.enqueue(r.slice(n,s)),n=s,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},Oa=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=ct({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=tt({limit:e.concurrency,maxHeldPerOwner:mu(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:R,readAttachment:p,cookie:m,fail:S}=s,y=e.maxBytes,h=i.spend(R,`attachment=${u} viewer=${R}`);if(h)return S(h.status,h.message,h.headers);let T=await n(c,"initial");if(!T.ok)return S(503,lr[503],Ae(503));let D=await t.getAttachmentForUser(T.scope,u,R);if(!D)return o.warn(`404 attachment=${u} viewer=${R} reason=not_visible`),S(404,"Attachment not found");if(D.fileSize!=null&&D.fileSize>y)return o.warn(`413 attachment=${u} viewer=${R} reason=db_size`),S(413,"Attachment too large");let f=Yn(D.fileType),b=`filename="${ka(D.fileName)}"; filename*=UTF-8''${La(D.fileName)}`,M=await l.acquire(R,c.signal);if(!M)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${R} reason=aborted`),S(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${R} reason=concurrency`),S(503,"Too many concurrent downloads",Ae(503)));let C=!1;try{let _=await p(D.filePath,{maxBytes:y,head:c.method==="HEAD",principal:r(R),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${R} reason=aborted`),S(503,"Attachment request aborted");if(!_.ok){if(!Pr(_.reason))return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=failure_reason`),S(500,lt);let E=Lr(_.reason);return _.reason==="not_found"&&a(u,!1),o.warn(`${E} attachment=${u} viewer=${R} reason=${_.reason} code=${_.code??"-"}`),S(E,lr[E],Ae(E))}if(_.bytes.byteLength>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),S(500,lt);let $=c.method==="HEAD";if($&&_.size!==void 0&&_.size>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),S(500,lt);if(!$&&_.size!==void 0&&_.size!==_.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=size_mismatch`),S(500,lt);let N=f??Yn(_.contentType),H=N!==null&&Pa.has(N),k=H?N:"application/octet-stream",K=H&&d.kind!=="download"?"inline":"attachment",G=$?_.size:_.bytes.byteLength,O=new Headers({"Content-Type":k,"Content-Disposition":`${K}; ${b}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...$t});return G!==void 0&&O.set("Content-Length",String(G)),m&&O.append("Set-Cookie",m),a(u,!0),o.info(`200 attachment=${u} viewer=${R} type=${k} disposition=${K} bytes=${G??"-"}`),$?new Response(null,{status:200,headers:O}):(C=!0,new Response(hu(_.bytes,M),{status:200,headers:O}))}finally{C||M()}}};var Fe=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Jy=Fe.queueWaitMs+Fe.readMs+Fe.renderMs+Fe.transferMarginMs;var Ua=require("buffer"),$a=new Set([194,198,202,206]),fu=new Set([192,193,194,195]),Ba=216,Ru=217,Va=218,Su=4,gu=64,bu=2,Ha=8,Fa=28,ft=12,Wn=8,Du=20,qa=ft+Wn+10,Au=2,ut=(e,t)=>e[t]<<8|e[t+1],Bt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},rt=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},Ya=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,ja=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),Wa=e=>(e.stepsLeft-=1,e.stepsLeft>=0),za=e=>e[0]===255&&e[1]===Ba,Ga=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!Wa(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===Ru)return"eoi";if(o===0||o===Ba)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=ut(e,n),i=n+a;return a<2||i>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=i,"segment")}},Tu=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!Wa(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}},Ka=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=ut(e,r+1),a=ut(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let s=0;s<i;s+=1){let c=e[r+7+3*s],d=c>>4,u=c&15;if(d<1||d>4||u<1||u>4)return null;l.push({id:e[r+6+3*s],horizontal:d,vertical:u})}return{marker:t,width:a,height:o,components:l}},Ja=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>Su||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},Qa=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:$a.has(e.marker)||t<e.components.length}),zn=e=>{if(!za(e))return null;let t=ja(e.byteLength),r=null;for(let n=2;;){if(Ga(e,n,t)!=="segment")return null;if(Ya(t.marker)){if(r!==null||(r=Ka(e,t),r===null))return null}else if(t.marker===Va){if(r===null)return null;let o=Ja(e,t);return o===null?null:Qa(r,o.length)}n=t.end}},Xa=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*Ha)),i=Math.ceil(e.height*o/(r*Ha));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},Za=e=>e.multiScan?Xa(e).reduce((r,n)=>r+n,0)*gu*bu:0,Eu=896,ei=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!za(e))return null;let n=Ua.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=ja(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let R=Ga(e,u,o);if(R===null)return null;if(R==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,Ya(o.marker)){if(a!==null||!fu.has(o.marker)||(a=Ka(e,o),a===null))return null;let p=Xa(a);l=new Map;for(let[m,S]of a.components.entries()){let y=l.get(S.id);l.set(S.id,y===void 0?p[m]:Math.max(y,p[m]))}s=a.components.length*($a.has(a.marker)?Eu:1)}else if(o.marker===Va){if(a===null||d===s)return null;let p=Ja(e,o);if(p===null)return null;for(let S of p){let y=l.get(S);if(y===void 0)return null;c+=y}if(d+=1,i===null&&(i=Qa(a,p.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let m=Tu(n,o.end,o);if(m===null)return null;u=m}}},ti=e=>{if(e.byteLength<24||ut(e,8)!==0||ut(e,10)!==13||!rt(e,12,"IHDR"))return null;let t=ut(e,16)*65536+ut(e,18),r=ut(e,20)*65536+ut(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},wu=e=>{if(rt(e,ft,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Bt(e,26,2)&16383,r=Bt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(rt(e,ft,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Bt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return rt(e,ft,"VP8X")?e.byteLength<qa?null:{width:Bt(e,24,3)+1,height:Bt(e,27,3)+1}:null},ri=e=>{if(ti(e)===null||e.byteLength<=Fa)return null;switch(e[Fa]){case 0:return!1;case 1:return!0;default:return null}},ni=(e,t)=>{if(rt(e,ft,"VP8 "))return"lossy";if(rt(e,ft,"VP8L"))return"lossless";if(!rt(e,ft,"VP8X")||e.byteLength<qa)return null;if((e[Du]&Au)!==0)return"animated";let r=!1,n=t;for(let o=ft;o+Wn<=e.byteLength;){if(n-=1,n<0)return null;if(rt(e,o,"VP8L"))return"lossless";if(rt(e,o,"VP8 "))return r?"lossy-alpha":"lossy";rt(e,o,"ALPH")&&(r=!0);let a=Bt(e,o+4,4);o+=Wn+a+a%2}return null},oi={png:ti,jpeg:zn,webp:wu};var kr=Object.freeze(["image/webp","image/jpeg","image/png"]),Nr=1024*1024;var Iu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),_u={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},xu=new Set(kr),Cu=e=>typeof e=="string"&&xu.has(e),Mu=256,vr=(e,t)=>e.fileType===null||!Iu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Pu=[137,80,78,71,13,10,26,10],Lu=[255,216,255],ku=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Nu=[82,73,70,70],vu=[87,69,66,80],cr=(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},Gn=e=>{if(cr(e,Pu,0))return"png";if(cr(e,Lu,0))return"jpeg";for(let t of ku)if(cr(e,t,0))return"gif";return cr(e,Nu,0)&&cr(e,vu,8)?"webp":null},ai=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:Ta([t])}},ii=(e,t)=>{if(!Cu(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Nr)return"too_large";let r=_u[e.contentType];if(Gn(e.bytes)!==r)return"signature";let n=oi[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},si=e=>{ae("maxBytes",e.maxBytes,0),ae("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)+Mu;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 Kn=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ie(),l=new AbortController,s=!1,c,d,u=()=>{a(ie()-i)},R=f=>{c=Ge(()=>{s=!0,f({timedOut:!0}),d=Ge(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},p=new Promise(R),m=AbortSignal.any([r,l.signal]),S=f=>{f(n(m))},y=new Promise(S),h=f=>(clearTimeout(c),clearTimeout(d),s&&o(ie()-i,f.kind==="error"?{error:f.error}:null),f),T=y.then(f=>h({kind:"value",value:f}),f=>h({kind:"error",error:f}));return{outcome:Promise.race([y.then(f=>({timedOut:!1,value:f})),p]),settled:T}};var dt={404:"Attachment not found",500:lt,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},li=(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=ii(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Ou=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ge(r,Fe.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},ci=()=>{},Hu=(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=(p,m)=>{let S=m.then(ci,ci);l.set(p,S);let y=()=>{l.get(p)===S&&l.delete(p)};S.then(y)},c=async(p,m)=>{let S=l.get(p.key);if(S===void 0)return t.acquire(p.owner,m);let y=Ou(m);try{if(await Hu(S,y.signal),y.signal.aborted)return null;let h=r.get(p.key);return h!==void 0?{...h,identity:"verified"}:await t.acquire(p.owner,y.signal)}finally{y.end()}},d=(p,m)=>{if(p.fileSize===null)return m.kind==="exact"?"verified":"unrecorded";if(m.kind==="exact"?m.bytes===p.fileSize:p.fileSize>m.maxBytes)return"verified";let y=m.kind==="exact"?String(m.bytes):`>${m.maxBytes}`;return i.warn(`size_mismatch expected=${p.fileSize} got=${y} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`),"unverified"},u=(p,m)=>(S,y)=>{let h=y===null?"":` message=${y.error instanceof Error?y.error.message:"unknown"}`;i.warn(`${p}_overrun ms=${S} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail${h}`)},R=(p,m)=>S=>{i.warn(`${p}_stuck ms=${S} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`)};return async(p,m)=>{let S=await c(p,m);if(S===null)return{kind:"failure",status:503,reason:m.aborted?"aborted":"queue"};if(typeof S!="function")return S;let y=S,h=null;try{if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let T=r.get(p.key);if(T!==void 0)return{...T,identity:"verified"};let D=Kn({budgetMs:Fe.readMs,flightSignal:m,call:E=>p.readAttachment(p.filePath,{maxBytes:n,head:!1,principal:o(p.owner),signal:E}),onOverrun:u("read",p),onStuck:R("read",p)}),f=await D.outcome;if(f.timedOut)return h=D.settled,m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let b=f.value;if(!b.ok&&b.reason!=="too_large")return Pr(b.reason)?(b.reason==="not_found"&&a(p.attachmentId,!1),{kind:"failure",status:Lr(b.reason),reason:b.reason,code:b.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(b.ok&&b.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let M=d(p,b.ok?{kind:"exact",bytes:b.bytes.byteLength}:{kind:"over",maxBytes:n}),C=E=>{M==="verified"&&r.set(p.key,E)},_=E=>(C(E),{...E,identity:M});if(!b.ok)return _({kind:"unrenderable",reason:"too_large"});let $=Gn(b.bytes);if($===null)return _({kind:"unrenderable",reason:"signature"});let N=Kn({budgetMs:Fe.renderMs,flightSignal:m,call:E=>p.renderer.render(b.bytes,{format:$,maxWidth:p.box.maxWidth,maxHeight:p.box.maxHeight,signal:E}),onOverrun:u("render",p),onStuck:R("render",p)}),H=E=>{if(E.kind==="error")return;let F=li(E.value,p.box);"entry"in F&&C(F.entry)},k=null,K=()=>(k===null&&(k=N.settled.then(H),s(p.key,k)),k);m.addEventListener("abort",K,{once:!0});let G=await N.outcome.finally(()=>m.removeEventListener("abort",K));if(G.timedOut||m.aborted)return h=K(),m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let O=li(G.value,p.box);return"entry"in O?_(O.entry):O.failure}finally{h===null?y():h.then(y,y)}}};var di=()=>{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 yi=10,Fu=1/yi,pi=1-Fu,Uu=1024,$u=64,Bu=8,mi="private, no-cache",Vu="no-store",qu=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Yu=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},hi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(f,b)=>ct({reason:f,limitPerWindow:b,windowMs:6e4,logger:o,windowFields:M=>`viewer=${M} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*yi),R=tt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:$u,maxPerOwner:Bu,maxWaitMs:Fe.queueWaitMs}}),p=si({maxBytes:l.cacheBytes,maxEntries:Uu}),m=di(),S=ui({gate:R,cache:p,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),y=(f,b,M,C)=>{let _=`attachment=${f.attachmentId} viewer=${f.internalUserId} variant=thumbnail cache=${C}`;if(b.kind==="failure")return o[Yu(b)](`${b.status} ${_} reason=${b.reason} code=${b.code??"-"}`),f.fail(b.status,dt[b.status],Ae(b.status));let $=qu[b.identity];if(b.kind==="unrenderable")return o.info(`404 ${_} reason=${b.reason}${$}`),f.fail(404,dt[404]);let N=b.identity==="verified"?{"Cache-Control":mi,ETag:M}:{"Cache-Control":Vu},H=new Headers({"Content-Type":b.contentType,"Content-Length":String(b.bytes.byteLength),...N,"Content-Security-Policy":"default-src 'none'; sandbox",...$t});return f.cookie&&H.append("Set-Cookie",f.cookie),o.info(`200 ${_} type=${b.contentType} bytes=${b.bytes.byteLength}${$}`),new Response(b.bytes,{status:200,headers:H})},h=(f,b)=>{let M=f.spend(b.internalUserId,`attachment=${b.attachmentId} viewer=${b.internalUserId} variant=thumbnail`);return M===null?null:b.fail(M.status,M.message,M.headers)},T=f=>h(d,f),D=(f,b)=>b?h(u,f):T(f);return async(f,b)=>{let{request:M,attachmentId:C,internalUserId:_,readAttachment:$,cookie:N,fail:H}=f,k=On[b],K=M.headers.get("If-None-Match"),G=K!==null,O=D(f,G);if(O)return O;let E=await n(M,"initial");if(!E.ok)return H(503,dt[503],Ae(503));let F=await t.getAttachmentForUser(E.scope,C,_),J=F!==null&&vr(F,i)?ai({rendererId:s.id,box:k,attachmentId:C,filePath:F.filePath,fileType:F.fileType,fileSize:F.fileSize}):null;if(J&&Un(K,J.etag)){let g=new Headers({"Cache-Control":mi,ETag:J.etag,...$t});return N&&g.append("Set-Cookie",N),o.info(`304 attachment=${C} viewer=${_} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:g})}if(G){let g=T(f);if(g)return g}if(!F)return o.warn(`404 attachment=${C} viewer=${_} variant=thumbnail reason=not_visible`),H(404,dt[404]);if(!J)return d.refund(_,pi),o.info(`404 attachment=${C} viewer=${_} variant=thumbnail reason=not_eligible`),H(404,dt[404]);let{key:ue,etag:he}=J,le=p.get(ue);if(le)return d.refund(_,pi),y(f,{...le,identity:"verified"},he,"hit");let fe=g=>S({key:ue,attachmentId:C,filePath:F.filePath,fileSize:F.fileSize,box:k,owner:_,readAttachment:$,renderer:s},g),P;try{P=await m.join(ue,M.signal,fe)}catch(g){return o.error(`500 attachment=${C} viewer=${_} variant=thumbnail cache=miss reason=port_exception message=${g instanceof Error?g.message:"unknown"}`),H(500,dt[500])}return y(f,P,he,"miss")}};var ju='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Wu=()=>Mr(403,qn,{cookie:null}),fi=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Hn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Mr(404,lr[404],{cookie:null}),crossSiteRejection:Wu}),Ri=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:Ma(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Oa({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:hi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,R=(p,m,S={})=>Mr(p,m,{cookie:u,extraHeaders:S});try{let{user:p,cookie:m}=await t(c,{failureRedirect:null});if(u=m??null,!p)return R(401,"Unauthorized");let S=Hn(new URL(c.url).searchParams);if(S.kind==="invalid")return R(400,"Invalid attachment request");if(S.kind==="thumbnail"&&c.method!=="GET")return R(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return R(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return R(404,"Attachment not found");if(d.token===void 0)throw new Error(ju);let y=s.idCodec.decode(d.token);if(y===null||!Xe(y))return R(400,"Invalid attachment token");let h=await r.getUserIdByExternalId(p.id);if(!h)return R(403,"Forbidden");let T={request:c,delivery:S,attachmentId:y,internalUserId:h,readAttachment:s.read,cookie:u,fail:R};return S.kind!=="thumbnail"?await s.serveOriginal(T):s.serveThumbnail===null?R(404,dt[404]):await s.serveThumbnail(T,S.variant)}catch(p){if(p instanceof Response)throw p;return a.error(`500 attachment=? viewer=? reason=unexpected message=${p instanceof Error?p.message:"unknown"}`),R(500,lt)}}};var zu=32*1024*1024,Gu=60,Ku=4,Ju=120,Qu=2,Xu=8*1024*1024,Or=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zu=e=>{if(e===void 0)throw Qe("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Or(e))throw Q("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Qe("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw Q("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Q("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},ed=e=>{if(e===void 0)return null;if(!Or(e))throw Q("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:Zu(e.renderer),rateLimitPerMinute:Me("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Ju),concurrency:Me("attachments.thumbnails.concurrency",e.concurrency,1,Qu),cacheBytes:Me("attachments.thumbnails.cacheBytes",e.cacheBytes,0,Xu)})},Si=e=>{let t=e;if(t===void 0)return null;if(!Or(t))throw Q("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Qe("attachments.idCodec","injected when attachments is given");if(!Or(r)||typeof r.encode!="function"||typeof r.decode!="function")throw Q("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Qe("attachments.read","injected when attachments is given");if(typeof n!="function")throw Q("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Me("attachments.maxBytes",t.maxBytes,1,zu),rateLimitPerMinute:Me("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,Gu),concurrency:Me("attachments.concurrency",t.concurrency,1,Ku),thumbnails:ed(t.thumbnails)})},td=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),Hr=e=>{for(let[t,r]of td)if(Object.hasOwn(e,t))throw Qe(r,`given in place of the flat key ${t}`)};var bi=8,rd=8*bi,nd=128,od=2,Di=od*nd,ad=4*Di,id=6e4,sd=6e4,ld="Too many reads",gi=Object.freeze(Object.keys(Mt).filter(e=>Mt[e].admission.includes("miss-gate"))),Ai=e=>{let t=tt({limit:rd,maxHeldPerOwner:bi,queue:{max:ad,maxPerOwner:Di,maxWaitMs:id}}),r=Le({windowMs:sd,tallies:gi,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${gi.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}})}},Fr=(e,t,r)=>{let n=e(t,r,{error:{message:ld}},503);for(let[o,a]of Object.entries(Ae(503)))n.headers.set(o,a);return n};var Ti=e=>{let t=e.get(be.cursorReportHubId),r=e.get(be.cursorBusinessDate),n=e.get(be.cursorSnapshot),o=Xo(n)?n:null,a=null;if(t!==null){let l=ze(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!Qo(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=ir(e.get(be.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var Ur=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,cd=2,ud=16,dd=cd*ud,pd=6e4,Ei=()=>{},md=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},wi=e=>{let t=tt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:dd,queue:null}),r=Le({windowMs:pd,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 Ei;if(a.aborted){if(t.canAcquire(n))return Ei}else{let i=await t.acquire(n,a);if(i!==null)return md(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var $r=30,Mi=4e3,yd="stream interrupted by server error",hd="Too many streams",fd=15e3,Pi=Symbol("ids-stream-heartbeat"),Ii=()=>{},_i=e=>e.return(void 0).then(Ii,Ii),Rd=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Pi),fd)}),stop:()=>clearTimeout(e)}};async function*xi(e,t,r,n){let o=t?ta(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Mi),e.length),l=xt(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 Li=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...et});return e&&t.append("Set-Cookie",e),t},Ci=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await _i(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=Rd();try{s===null&&(s=t.next());let R=await Promise.race([s,u.fired]);if(u.stop(),R===Pi){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
2
|
+
`));return}s=null;let{value:p,done:m}=R;if(m){await a(d,!1);return}if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`${JSON.stringify(p)}
|
|
3
|
+
`))}catch(R){if(u.stop(),s=null,o(),l||r.aborted)return;R instanceof We||n.error(`ids-stream emission failed: ${R instanceof Error?R.message:String(R)}`);try{let p={kind:"error",error:yd};d.enqueue(i.encode(`${JSON.stringify(p)}
|
|
4
|
+
`)),d.close()}catch{}}},cancel(){l=!0,o(),_i(t)}});return new Response(c,{status:200,headers:Li(e)})},ki=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,s,c,d,u,R,p)=>{let m=!1,S=null,y=null,h=new Promise((f,b)=>{S=f,y=b});h.catch(()=>{});let T=t.getDailyReportIdsByExternalId(c,s.id,{forceRefresh:l.forceRefresh,admission:p,onFetchStart:l.cursor?void 0:()=>{m=!0,t.readSseStreamAnchor().then(f=>t.getDailyReportIdsFirstPageByExternalId(c,s.id,$r).then(b=>({items:b,streamAnchor:f}))).then(f=>S?.(f),f=>y?.(f))}});if(T.catch(()=>{}),l.cursor){let{items:f,streamAnchor:b,snapshot:M}=await T,C=l.snapshot!==null&&l.snapshot===M;return Ci(d,xi(f,C?l.cursor:null,$r,{snapshot:M,restarted:!C,streamAnchor:b}),u,r,R)}let D=(async function*(){let f=await Promise.race([T.then(C=>({kind:"full",source:C}),C=>({kind:"full-error",error:C})),h.then(C=>({kind:"page",page:C}),()=>({kind:"page-error"}))]),b=null,M=!1;if(f.kind==="full")b=f.source;else if(f.kind==="page"){let{items:C,streamAnchor:_}=f.page;if(C.length<$r){yield{kind:"chunk",...xt(C,0,C.length),nextCursor:null,isLast:!0,total:C.length,streamAnchor:_};return}yield{kind:"chunk",...xt(C,0,C.length),nextCursor:null,isLast:!1,provisional:!0},M=!0}else if(f.kind==="full-error"&&m){let C=await h.catch(()=>null);C&&C.items.length>0&&(yield{kind:"chunk",...xt(C.items,0,C.items.length),nextCursor:null,isLast:!1,provisional:!0})}b===null&&(b=await T),yield*xi(b.items,null,M?Mi:$r,{snapshot:b.snapshot,streamAnchor:b.streamAnchor})})();return Ci(d,D,u,r,R)};return async(l,s,c,d,u,R)=>{let p=Ti(l.searchParams);if("refused"in p)return R(c,s,{error:{message:p.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:m}=p;if(m.forceRefresh){let T=a(d,c,s,R);if(T!==null)return T}let S=Ur(c),y=await t.getUserIdByExternalId(d.id),h=await n.admit(y,"ids-stream",S);if(h===null){let T=R(c,s,{error:{message:hd}},503);for(let[D,f]of Object.entries(Ae(503)))T.headers.set(D,f);return T}if(S.aborted)return new Response(null,{status:200,headers:Li(s)});try{return await i(m,d,u,s,S,h,y===null?void 0:o.admissionFor(y,se.idsStream,S))}catch(T){if(h(),T instanceof We)return Fr(R,c,s);throw T}}};var Pt=require("drizzle-orm");var Ve="Internal",Ni=e=>e.trim().toLowerCase();var Sd="",gd=64,bd=e=>e.toLowerCase(),vi=e=>{let t=new Set;if(!Array.isArray(e))return t;for(let r of e){if(typeof r!="string")continue;let n=Ni(r);n.length>0&&t.add(n)}return t};function Ie(e,t){return e===null?!0:t==null?!1:e.has(bd(t))}function ke(e){return e!==null&&e.size===0}var Dd=4e3,Qn=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 ae("tables.hub.sourceType.length",e.length,1,Dd)};function dr(e,t){if(t===null)return;let r=Qn(e),n=[...t].filter(a=>a.length<=r);if(n.length===0)return Pt.sql`1 = 0`;let o=Pt.sql.raw(`VARBINARY(${2*r})`);return(0,Pt.inArray)(Pt.sql`CAST(LOWER(${e}) AS ${o})`,n.map(a=>Pt.sql`CAST(${a} AS ${o})`))}var Vt,qt,ur=class ur{constructor(t,r){un(this,Vt);un(this,qt);dn(this,Vt,t),dn(this,qt,r)}get visible(){return Xt(this,Vt)===null?null:new Set(Xt(this,Vt))}get commentable(){return Xt(this,qt)===null?null:new Set(Xt(this,qt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=vi(r?t.read:t);if(!r||t.comment===void 0)return new ur(n,n);let o=new Set;for(let a of vi(t.comment))n.has(a)&&o.add(a);return new ur(n,o)}static unrestricted(t){return new ur(null,null)}};Vt=new WeakMap,qt=new WeakMap;var qe=ur,Jn=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),Ad=new Set(["read","comment"]),Hi=e=>{if(Jn(e))return qe.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?qe.unrestricted(o):null}let{read:r,comment:n}=e;return t.every(o=>Ad.has(o))&&Jn(r)?n===void 0?qe.restrictTo({read:r}):Jn(n)?qe.restrictTo({read:r,comment:n}):null:null};function Br(e){let t=Oi(e.visible),r=Oi(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Oi(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Sd);if(t.length<=gd)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 Fi=(e,t,r,n)=>Ie(n.commentable,t)||e.authorUserId===r;var es=require("@aiquants/fuzzy-search");var Vi=require("crypto"),Xn=require("timers/promises"),Re=require("@aiquants/fuzzy-search/normalize");var qr=`
|
|
5
|
+
`,Zn=4e3,Td=1,qi=new Set([8203,8288,65279,173]),Ed=new RegExp(`[${String.fromCodePoint(...qi)}]`,"gu"),Yi=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),ji=/(\s+)/u,wd=/^\s+$/u,Id=new RegExp(ji.source,"gu"),_d=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,xd=new Set([8205,1536,1537,1538,1539,1540,1541,1757,1807,2192,2193,2274,69821,69837,70082,70083,71999,72001,72250,72324,72325,72326,72327,72328,72329,73030,73474]),Yr=e=>e.replace(Ed,"");var eo=e=>(0,Re.normalizeText)(e,Re.DEFAULT_NORMALIZE_OPTIONS),Vr=e=>eo(Yr(e)),Cd=(0,Re.resolveNormalizeOptions)({...Re.DEFAULT_NORMALIZE_OPTIONS,convertRomaji:!0},"[daily-report] search reading options"),Md=3,Pd=/^[-ー]+/u,Ld=/[^\p{L}\p{M}]/gu,kd=/ー{2,}/gu,Nd=/\p{Script=Latin}/u,Ui=/(?=\p{L})\p{Script=Latin}/u,vd=e=>(0,Re.clusterCountOf)(e.replace(Pd,"").replace(Ld,"").replace(kd,"\u30FC")),Od=(e,t)=>{for(let r of t)if(!(0,Re.isAnswerTier)(r.tier)||r.splitTier!==null)throw new Error(`[daily-report] search readings: queryNeedles gave an unfinished needle for the word ${JSON.stringify(e)} (text ${JSON.stringify(r.text)}, tier ${r.tier}, splitTier ${r.splitTier})`)},Wi=e=>{if(!Ui.test(e))return[];let t=Vr(e);if(!Ui.test(t))return[];let r=(0,Re.queryNeedles)(t,Cd,!1);Od(t,r);let n=[];for(let o of r){if(o.tier===Ct.word)continue;let a=Vr(o.text);if(!(a.length===0||a.length>xe.maxWordLength)&&!(a===t||Nd.test(a))&&!(vd(a)<Md||n.includes(a))&&(n.push(a),n.length===Mn))break}return n},to=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},zi=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&to(e,t-1)?t-2:t-1;return _d.test(String.fromCodePoint(r))&&!xd.has(e.codePointAt(n))},Hd=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!zi(e,i);)i--;i===a&&(i=a+r,to(e,i)&&i--,o++),n.push({start:t+a,end:t+i}),a=i}return n.push({start:t+a,end:t+e.length}),{pieces:n,forcedCuts:o}},ro=(e,t)=>{if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let r=[],n=0,o=0,a=0,i=0,l=()=>{i>0&&r.push([{start:a,end:a+i}]),i=0};for(let s of e.split(ji)){let c=o;if(o+=s.length,i+s.length<=t){i===0&&(a=c),i+=s.length;continue}if(l(),wd.test(s))continue;if(s.length<=t){a=c,i=s.length;continue}let d=Hd(s,c,t);n+=d.forcedCuts,r.push(d.pieces)}return l(),{chunks:r,forcedCuts:n}},no=(e,t)=>{let r=ro(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>eo(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},Fd=(e,t)=>{let r=0;for(let n of e.matchAll(Yi))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},Ud=(e,t)=>{if(e.partialReadings!==null)throw new Error(`[daily-report] search marks: the mapped forms of the piece ${JSON.stringify(t)} carry partial readings`);return e.canonical},Gi=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],s=[];for(let c of a){let d=e.slice(c.start,c.end),u=Ud((0,Re.toMappedFormsInto)(d,Re.DEFAULT_NORMALIZE_OPTIONS,new Re.InteriorPairs(0)),d),[R,p]=(0,Re.trimmedRange)(u.text);i+=u.text.slice(R,p);for(let m=R;m<p;m++)l.push(c.start+u.start[m]),s.push(c.start+u.end[m])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let c=0;c<l.length;c++)n.push(l[c]),o.push(s[c])}}return{text:r,start:n,end:o}},jr=(e,t=Zn)=>{let r=[],n=0;return Fd(Yr(e),o=>{let a=no(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(qr),forcedCuts:n}},Ki=e=>e.filter(t=>t.length>0).join(qr),oo=(e,t)=>{let r=null;return{advance:n=>{if(r!==null)return 0;e.units=ae("search text steps: units",n,1);let o=t.next();return o.done===!0&&(r={result:o.value}),n-e.units},done:()=>r!==null,result:()=>{if(r===null)throw new Error("[daily-report] search text: the steps are not done (advance until done() is true)");return r.result}}},$i=4096;function*$d(e,t){let r=[],n=new Uint32Array(e.length),o=0,a=!1;for(let i=0;i<e.length;){for(;t.units===0;)yield;let l=Math.min(e.length,i+t.units);t.units-=l-i;let s=o,c=new Uint16Array(l-i);for(let d=i;d<l;d++){let u=e.charCodeAt(d);qi.has(u)||(c[o-s]=u,n[o++]=d)}if(o-s===l-i)a&&r.push(e.slice(i,l));else{a||r.push(e.slice(0,i)),a=!0;for(let d=s;d<o;d+=$i)r.push(Reflect.apply(String.fromCharCode,null,c.subarray(d-s,Math.min(o,d+$i)-s)))}i=l}return a?{text:r.join(""),rawIndex:n.subarray(0,o)}:{text:e,rawIndex:null}}var Ji=e=>{let t={units:0};return oo(t,$d(e,t))};function*Bd(e,t,r){let n=0;for(let o=0;o<e.length;){for(;r.units===0;)yield;let a=Math.min(e.length,o+r.units);r.units-=a-o;let i=a;for(let l of e.slice(o,Math.min(e.length,a+1)).matchAll(Yi)){let s=o+l.index;if(s>=a)break;t(e.slice(n,s),n),n=s+l[0].length,i=Math.max(i,n)}o=i}t(e.slice(n),n)}var Qi=(e,t)=>{let r={units:0};return oo(r,Bd(e,t,r))};function*Bi(e,t,r,n,o){let a=[],i=0,l=t;for(;r-l>n;){let s=l+n;for(;s>l;s--){for(;o.units===0;)yield;if(o.units-=1,zi(e,s))break}s===l&&(s=l+n,to(e,s)&&s--,i++),a.push({start:l,end:s}),l=s}return a.push({start:l,end:r}),{pieces:a,forcedCuts:i}}function*Vd(e,t,r){if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let n=[],o=0,a=0,i=0,l=0,s=0,c=!1,d=(p,m,S)=>{let y=m-p;return i+y<=t?(i===0&&(a=p),i+=y,!1):(i>0&&n.push([{start:a,end:a+i}]),i=0,S?!1:y<=t?(a=p,i=y,!1):!0)},u=p=>{c&&(d(l,s,!0),l=s),c=!1,s=p},R=p=>{let m=-1;return!c&&s>l&&(d(l,s,!1)&&(m=l),l=s),c=!0,s=p,m};for(let p=0;p<e.length;){for(;r.units===0;)yield;let m=Math.min(e.length,p+r.units);r.units-=m-p;let S=p;for(let y of e.slice(p,m).matchAll(Id)){let h=p+y.index;h>S&&u(h),S=h+y[0].length;let T=R(S);if(T>=0){let D=yield*Bi(e,T,h,t,r);o+=D.forcedCuts,n.push(D.pieces)}}m>S&&u(m),p=m}if(d(l,s,c)){let p=yield*Bi(e,l,s,t,r);o+=p.forcedCuts,n.push(p.pieces)}return i>0&&n.push([{start:a,end:a+i}]),{chunks:n,forcedCuts:o}}var Xi=(e,t)=>{let r={units:0};return oo(r,Vd(e,t,r))},qd=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
|
|
6
|
+
`)},Yd=[`\u3067\u3093${String.fromCodePoint(8203)}\u3077\u3093 \uFF83\uFF9E\uFF9D\uFF8C\uFF9F\uFF9D\r
|
|
7
|
+
\u30C7\u30F3\u30D7\u30F3`,"\u30DD\u30C6\u30C8-25kg \u30A2--1 \u30FC\u30FC\u30E1\u30F3 \u4F50\u3005\u6728","\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CA",`\uFF71\uFF72\uFF73\uFF74\uFF75\uFF76\uFF9E\uFF77\uFF9E\uFF78\uFF9E\uFF79\uFF9E\uFF7A\uFF9E${String.fromCodePoint(8232)}\u6B21\u306E\u884C`],jd=["","\u30A2","\u4F50"," "],Wd=()=>JSON.stringify(Yd.map(e=>jr(e,8))),zd=e=>`dr-search-v${Td};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var Gd=async()=>{let e=(0,Vi.createHash)("sha256");e.update(JSON.stringify(Re.DEFAULT_NORMALIZE_OPTIONS));for(let t of jd)await(0,Xn.setImmediate)(),e.update("\0"),e.update(eo(qd(t)));return await(0,Xn.setImmediate)(),e.update("\0"),e.update(Wd()),zd(e.digest("hex"))},Kd=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},ao=Kd(Gd);var Jd=/^-+/u,Qd=/\s+/u,Zi=e=>{let t=Jd.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Xd=(e,t)=>{let r=[...Zi(e).map(n=>({text:n,tier:Ct.word})),...t.flatMap(n=>Zi(n).map(o=>({text:o,tier:Ct.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},Zd=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),Wr=(e,t)=>{if(e.length>xe.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of(0,es.parseQuerySets)(Yr(e),t).sets){let i=[],l=new Set;for(let c of a.split(Qd)){let d=Vr(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>xe.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=Xd(d,Wi(c)),R=Zd(u);l.has(R)||(l.add(R),i.push({alternatives:u}))}if(i.length>xe.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let s=JSON.stringify([...l].sort());n.has(s)||(n.add(s),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>xe.maxSets?{ok:!1,reason:"too-many-sets"}:o>xe.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},pr=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var Sf=Object.freeze({sourceTypes:null,authors:null,customers:null}),ep=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,ts=(e,t,r)=>{if(la(e)&&ep(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=Wr(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var rs=6e4,tp=1,rp=3200,ns=2e3,np=Object.freeze({search:rp,reports:ns,"search-marks":ns,"search-facets":null}),op=(e,t)=>{let r=np[e];return r===null?null:{max:t,maxPerOwner:Ir,maxWaitMs:r}},mr=e=>{let{concurrency:t,route:r,logger:n}=e,o=ct({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:rs,logger:n,windowFields:()=>`route=${r}`}),a=tt({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:op(r,t)}),i=Object.freeze({status:429,message:jn,headers:Object.freeze({"Retry-After":String(tp)})}),l=Le({windowMs:rs,tallies:["busy"],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`busy_suppressed count=${c} since=${d} route=${r} concurrency=${t}`)}});return{admit:async(s,c)=>{let d=o.spend(s,r);if(d!==null)return{refusal:d};let u=await a.acquire(s,c);return u!==null?{release:u}:(o.refund(s,1),c.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};var Ss=require("@aiquants/sse"),St=require("@aiquants/sse/server");var Yt=(e,t)=>{let r=e.message.data;if(!r)return{entry:{id:e.id,message:null},json:void 0};let n;try{n=JSON.parse(r)}catch(i){return t.error(`SSE message ${e.id} is not JSON:`,i),{entry:{id:e.id,message:null},json:void 0}}let o=Ko.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n,text:r});return{entry:Object.freeze({id:e.id,message:a}),json:n}},ap=["externalComments","postedComments"],os=new WeakMap,ip=e=>{let t=os.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return os.set(e,r),r},as=e=>{let{recipientRawUserId:t,...r}=e;return r},is=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=ip(e);if(t){if(n.commentsRedacted===null){let o=as(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(ap.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(as(r))),n.recipientRemoved};var us=require("@aiquants/sse"),ds=require("@aiquants/sse/shared-source");var Rt="daily-report:ids:",io=(e,t)=>`${e}st:${t}`,so=e=>`${Rt}user:${e}:`,ss=(e,t)=>io(so(e),t),jt=e=>`daily-report:date:${e}:user:`,Wt=(e,t)=>`${jt(e)}${t}:`,ls=(e,t,r)=>io(Wt(e,t),r),Ye=e=>`daily-report:detail:${e}:user:`,lo=(e,t)=>`${Ye(e)}${t}:`,cs=(e,t,r)=>io(lo(e,t),r);var pt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},sp=5e3,lp=_r,zt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=De(t.logger,1,"SseReader"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return(0,ds.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:us.systemSseRuntime,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",i=>{this._logger.error("Redis client error:",i)});let o=!1,a=this._readLoop(n,t,r,()=>o);return async()=>{if(o=!0,n.isOpen)try{await n.quit()}catch{}await a}}async _readLoop(t,r,n,o){let a=n;try{for(;!o()&&t.isOpen;){let i=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:sp,COUNT:lp});if(i)for(let l of i)for(let s of l.messages){a=s.id;let{entry:c,json:d}=Yt(s,this._logger);this._invalidateCaches(d),r.next(c)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(Rt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ye(n))}};var cp=6e4,yr="Report visibility is unavailable",ps=["initial","refresh"],ms=Object.freeze({ok:!1}),up=e=>e===null?"null":Array.isArray(e)?"array":typeof e,ys=(e,t)=>{let r=Le({windowMs:cp,tallies:ps,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{t.error(`visibility_unavailable_suppressed count=${o} since=${a} cause=${n} reasons=${ps.map(l=>`${l}:${i[l]}`).join(",")}`)}});return async(n,o)=>{let a;try{a=await e(n,{reason:o})}catch(l){return r.record("port_failure",o,()=>t.error(`visibility unavailable cause=port_failure reason=${o}`,l)),ms}let i=Hi(a);return i===null?(r.record("port_contract",o,()=>t.error(`visibility unavailable cause=port_contract reason=${o} answer=${up(a)}`)),ms):{ok:!0,scope:i}}},hs=(e,t,r)=>{let n=e(t,r,{error:{message:yr}},503);for(let[o,a]of Object.entries(Ae(503)))n.headers.set(o,a);return n};var gs=Object.freeze({...sr,route:"sse",frameworkDataRefusal:Cr}),fs=864e5,dp={baseMs:2e3,jitterMs:8e3},co=6e4,Gr=_r,bs=JSON.stringify({type:"connected"}),Rs="0-0",pp=(e,t,r)=>{if(t===null&&r===null)return!0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Ie(t,e.report.sourceType);case"comment-add":case"comment-delete":return Ie(r,e.sourceType);case"report-delete":return Ie(t,e.sourceType)}},mp=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Ie(t,e.report.sourceType),yp=(e,t)=>{e.writeEvent({event:null,id:t,data:bs})},hp=(e,t,r)=>{let{message:n}=t;if(n===null)return;let{parsed:o,published:a}=n,i=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((o.type==="status-update"||i!==void 0)&&i!==r.internalUserId||!pp(o,r.visibleSet,r.commentableSet)){yp(e,t.id);return}e.writeEvent({event:null,id:t.id,data:is(n,mp(o,r.commentableSet))})},Ds=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:s}=e,c=async(d,u)=>{let{request:R,internalUserId:p,cursor:m}=u,S=u.initialScope.visible,y=u.initialScope.commentable,h=0,T=setInterval(()=>{let k=++h;n(R,"refresh").then(K=>{if(k===h){if(!K.ok){d.close();return}S=K.scope.visible,y=K.scope.commentable}})},co);d.onClose(()=>clearInterval(T));let D=m===null?Rs:m,f=m!==null&&o!==void 0,b=[],M=null,C=k=>{pt(k.id,D)||(D=k.id,hp(d,k,{internalUserId:p,visibleSet:S,commentableSet:y}))},_=async(k,K)=>{let[G]=await k.xRange(i,"-","+",{COUNT:1});return G!==void 0&&!pt(G.id,K)},$=async(k,K)=>{if(await _(k,K))return!1;let G=K;for(;;){let O=await k.xRange(i,G,"+",{COUNT:Gr}),E=O[0];if(E!==void 0&&E.id!==G&&await _(k,G))return!1;for(let te of O){if(M!==null&&pt(M,te.id))return!0;pt(te.id,D)||C(Yt(te,s).entry)}let F=O.at(-1);if(O.length<Gr||F===void 0||d.isClosed())return!0;G=F.id}},N=a.subscribe(k=>{if(!f){C(k);return}pt(k.id,D)||(M===null&&(M=k.id),b.push(k))},k=>{s.error(`[SSE:${p}] Fan-Out reader error:`,k),d.close()});if(d.onClose(N),m===null){await a.ready();try{let k=await o?.getClient();if(k){let K=await k.xRevRange(i,"+","-",{COUNT:1});K.length>0&&!pt(K[0].id,D)&&(D=K[0].id)}}catch{}}if(d.writeEvent({event:null,id:D===Rs?null:D,data:bs}),(0,St.startSseHeartbeat)(d,{intervalMs:Wo,retry:dp,runtime:Ss.systemSseRuntime}),m===null||o===void 0)return;await a.ready();let H=await o.getClient();if(H===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await $(H,m)){d.writeRetry(fs),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}f=!1;for(let k of b.splice(0))C(k)};return async({request:d,params:u})=>{let R,p=()=>{let S=new Headers;R!==void 0&&S.append("Set-Cookie",R);for(let[y,h]of Object.entries(et))S.set(y,h);return S},m=S=>(0,St.terminalStreamResponse)(S,{data:"",retryMs:fs,headers:p()});try{let S=await t(d,{failureRedirect:null});R=S.cookie;let{user:y}=S;if(!y)return m("auth-required");let h=await r.getUserIdByExternalId(y.id);if(!h)return m("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:p()});let T=(0,St.readLastEventId)(d,zo);if(T!==null&&!Go(T))return s.warn(`[SSE:${h}] malformed resume cursor; asking the client to resync`),m("resync-required");let D=Ur(d),f=await l.admit(h,"sse",D);if(f===null){let M=p();for(let[C,_]of Object.entries(Ae(503)))M.set(C,_);return new Response("Too many streams",{status:503,headers:M})}let b=!1;try{let M=await n(d,"initial");if(!M.ok){let _=p();for(let[$,N]of Object.entries(Ae(503)))_.set($,N);return new Response(yr,{status:503,headers:_})}let C=M.scope;return(0,St.createSseResponse)({requestSignal:D,headers:p(),onError:(_,$)=>s.error(`[SSE:${h}] ${$} failed:`,_),produce:_=>(b=!0,_.onClose(f),c(_,{request:d,internalUserId:h,cursor:T,initialScope:C}))})}finally{b||f()}}catch(S){if(S instanceof Response)throw S;let y=S instanceof Error?S:new Error(String(S));return s.error(`500 sse name=${y.name} message=${y.message}`),new Response("Internal Server Error",{status:500,headers:p()})}}};var As=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...et});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},fp=Object.freeze({...sr,route:"api",frameworkDataRefusal:({params:e})=>vn(e.endpoint)&&Mt[e.endpoint].body==="stream"?Cr():null}),Rp=Object.freeze({...sr,route:"action"}),Sp=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),_s=6e4,xs=5,gp=xs*Math.ceil(_s/500),bp=2,Dp=6,Ap=6e4,Tp=xs*bp*Dp,Ep=2,wp=10,Ip=2,_p=10,Ts=(e,t)=>Math.max(e,Ir)*t,Cs=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},xp=Object.freeze({etag:(e,t,r)=>Ea(e,t,r,200),"no-store":(e,t,r)=>$n(t,r,200)}),Cp=e=>Bn(e.body==="json"?xp[e.cache]:null),Es=Bn(null),ws=(e,t,r,n)=>Cs(e(t,r,{error:{message:n.message}},n.status),n.headers),Is=(e,t,r)=>Cs(e(t,r,null,503),Ae(503));function Kr(e){Hr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:ae("service.titleMaxLength",r.titleMaxLength,1)},{loginRedirectPath:s}=e;if(typeof s!="string"||s.trim()==="")throw Q("loginRedirectPath","the non-blank path of the host's sign-in route",s);let c=De(e.logger,3,"API"),d=De(e.logger,3,"Visibility"),u=ys(Zt("resolveVisibleSourceTypes",e.resolveVisibleSourceTypes),d),R=De(e.logger,1,"SSE"),p=De(e.logger,1,"Attachment"),m=De(e.logger,2,"Isolation"),S=De(e.logger,2,"Action"),y=De(e.logger,2,"Search"),h=De(e.logger,2,"Refresh"),T=De(e.logger,2,"Streams"),D=De(e.logger,2,"Reads"),f=ct({reason:"refresh_rate_limit",limitPerWindow:Tp,windowMs:Ap,logger:h,windowFields:()=>"route=api"}),b=wi(T),M=Ai(D),C=async(g,I,w,x,v,V)=>{let j=await r.getUserIdByExternalId(I.id);try{return await V(j===null?void 0:M.admissionFor(j,g,w.signal))}catch(U){if(U instanceof We)return Fr(v,w,x);throw U}},_=(g,I,w,x,v)=>{let V=f.spend(I.id,`endpoint=${g}`);return V===null?null:ws(v,w,x,V)},$=async({request:g})=>{let{user:I,cookie:w}=await t(g,{failureRedirect:s}),x=new Headers;w&&x.append("Set-Cookie",w);let v=await r.getUserIdByExternalId(I.id),V=v?n(v):null;return{data:{user:I,userId:V},headers:x}},N=g=>{let{limiter:I}=g;return async(w,x,v,V,j,U)=>{if(I===null)return U(v,x,{error:{message:"Unknown endpoint"}},404);let z=g.parse(w);if(!z.ok)return U(v,x,z.invalid,400);let L=await r.getUserIdByExternalId(V.id);if(!L)return U(v,x,g.emptyAnswer(z.parsed),200);let{signal:X}=v,Y=await I.admit(L,X);if("refusal"in Y)return X.aborted?Is(U,v,x):ws(U,v,x,Y.refusal);try{X.throwIfAborted();let Z=await g.read(z.parsed,{userId:L,user:V,scope:j},X);return X.throwIfAborted(),U(v,x,Z,200)}catch(Z){if(X.aborted&&Z===X.reason)return Is(U,v,x);throw Z}finally{Y.release()}}},H=r.searchLimits===null?null:mr({...r.searchLimits,route:se.search,logger:y}),k=r.searchLimits===null?null:mr({concurrency:Ts(r.searchLimits.concurrency,Ep),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*wp,route:se.reports,logger:y}),K=r.searchLimits===null?null:mr({concurrency:Ts(r.searchLimits.concurrency,Ip),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*_p,route:se.searchMarks,logger:y}),G=r.searchLimits===null?null:mr({...r.searchLimits,route:se.searchFacets,logger:y}),O={[se.businessDate]:async(g,I,w,x,v,V)=>{let j=g.searchParams.get(be.businessDate),U=j===null?null:Ft(j);if(U===null)return V(w,I,{error:{message:"Invalid business date"}},400);let z=ir(g.searchParams.get(be.forceRefresh));if(z===null)return V(w,I,{error:{message:"Invalid forceRefresh"}},400);let L=z?_(se.businessDate,x,w,I,V):null;return L!==null?L:C(se.businessDate,x,w,I,V,async X=>{let Y=await r.getDailyReportsByBusinessDateByExternalId(v,U,x.id,{forceRefresh:z,admission:X});return V(w,I,{businessDate:U,reports:Y},200)})},[se.idsStream]:ki({service:r,logger:c,streamSlots:b,missGate:M,refuseForcedRead:(g,I,w,x)=>_(se.idsStream,g,I,w,x)}),[se.report]:async(g,I,w,x,v,V)=>{let j=ze(g.searchParams.get(be.reportHubId));if(j===null)return V(w,I,{error:{message:"Invalid reportHubId"}},400);let U=ir(g.searchParams.get(be.forceRefresh));if(U===null)return V(w,I,{error:{message:"Invalid forceRefresh"}},400);let z=U?_(se.report,x,w,I,V):null;return z!==null?z:C(se.report,x,w,I,V,async L=>{let X=await r.getDailyReportDetailByIdByExternalId(v,j,x.id,{snapshot:!0,forceRefresh:U,admission:L});return X?V(w,I,{report:X},200):V(w,I,{error:{message:"Report not found"}},404)})},[se.search]:N({limiter:H,parse:g=>{let I=g.searchParams.get(be.searchQuery),w=kn(g.searchParams.get(be.searchCombine));if(I===null||w===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let x=ua(g.searchParams,r.searchFilterSourceTypes);if(!x.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:x.reason}}};let v=ts(I,w,x.filters);if(!v.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:v.reason}}};let{criteria:V}=v;return{ok:!0,parsed:{criteria:V,words:V.plan===null?[]:pr(V.plan)}}},emptyAnswer:({words:g})=>Pn([],g),read:async({criteria:g,words:I},{userId:w,scope:x})=>Pn(await r.searchDailyReports(x,w,g),I)}),[se.reports]:N({limiter:k,parse:g=>{let I=Nn(g.searchParams.get(be.reportIds));return I===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:I}},emptyAnswer:()=>({reports:[]}),read:async(g,{user:I,scope:w})=>({reports:await r.getDailyReportDetailsByIdsByExternalId(w,g,I.id)})}),[se.searchMarks]:N({limiter:K,parse:g=>{let I=g.searchParams.get(be.searchQuery),w=kn(g.searchParams.get(be.searchCombine));if(I===null||w===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let x=Wr(I,w);if(!x.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:x.reason}}};let v=Nn(g.searchParams.get(be.reportIds));return v===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:x.plan,ids:v}}},emptyAnswer:({plan:g})=>({wordsDigest:wr(pr(g)),reports:[],deferred:[]}),read:({plan:g,ids:I},{userId:w,scope:x},v)=>r.markDailyReportSearchHits(x,w,g,I,{signal:v})}),[se.searchFacets]:N({limiter:G,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(g,{userId:I,scope:w})=>r.listDailyReportSearchFacets(w,I)})},E=async({request:g,params:I})=>{let{user:w,cookie:x}=await t(g,{failureRedirect:null}),v=x??null;if(!w)return Es(g,v,{error:{message:"Unauthorized"}},401);let V=I.endpoint;if(!vn(V))return Es(g,v,{error:{message:"Unknown endpoint"}},404);let j=Mt[V],U=Cp(j),z=ba[j.body];if(!z.includes(g.method)){let X=U(g,v,{error:{message:"Method not allowed"}},405);return X.headers.set("Allow",z.join(", ")),X}let L=ie();try{let X=new URL(g.url),Y=await u(g,"initial"),Z=Y.ok?await O[V](X,v,g,w,Y.scope,U):hs(U,g,v);return j.body==="json"&&c.debug(Z.headers.has("ETag")?`${Z.status} endpoint=${V} etag_match=${Z.status===304}`:`${Z.status} endpoint=${V}`),Z}catch(X){let Y=ie()-L,Z=X instanceof Error?X:new Error(String(X));return c.error(`500 endpoint=${V} elapsed=${Y}ms name=${Z.name} code=${"code"in Z?Z.code:"N/A"} message=${Z.message}`,Z),U(g,v,{error:{message:"Internal Server Error"}},500)}},F=ga(S),te=ct({reason:"rate_limit",limitPerWindow:gp,windowMs:_s,logger:S,windowFields:()=>"route=action"}),J=async(g,I,w,x,v)=>{let{clientTempId:V}=g;if(g.intent==="create")try{let L=await r.createDailyReport(w,I,g.businessDate,V);return v(g,L.reportHubId,{report:L})}catch(L){if(L instanceof Error&&L.message==="Forbidden")return x({error:"Creating reports is restricted"},{status:403});throw L}let{reportHubId:j,businessDate:U}=g,z=async(L,X)=>{try{let Y=await X(L.value);return v(L,j,{updatedStatus:{isStarred:Y.isStarred,isRead:Y.isRead},operationTimestamp:L.operationTimestamp})}catch(Y){if(Y instanceof Error&&Y.message==="Not Found")return x({error:"Report not found"},{status:404});throw Y}};switch(g.intent){case"update":try{return await r.updateDailyReport(w,j,I,g.changes,V),v(g,j,{})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return x({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return x({error:"Report not found"},{status:404})}throw L}case"publish":try{let L=await r.publishDailyReport(w,j,I,V);return v(g,j,{report:L})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return x({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return x({error:"Report not found"},{status:404})}throw L}case"delete":try{return await r.deleteDailyReport(w,j,I,V),v(g,j,{})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return x({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return x({error:"Report not found"},{status:404})}throw L}case"toggleStar":return await z(g,L=>r.setStarStatus(w,I,j,U,L,V));case"toggleRead":return await z(g,L=>r.setReadStatus(w,I,j,U,L,V));case"addComment":try{let L=await r.addComment(w,I,j,g.content,U,V);return v(g,j,{newComment:L})}catch(L){if(L instanceof Error){if(L.message==="Not Found")return x({error:"Report not found"},{status:404});if(L.message.startsWith("Comments are restricted"))return x({error:"Comments are restricted for this report"},{status:403})}throw L}case"deleteComment":try{return await r.deleteComment(w,I,j,g.commentId,U,V),v(g,j,{deletedCommentId:g.commentId})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return x({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return x({error:"Comment not found"},{status:404})}throw L}}},ue=async({request:g,params:I})=>{let{user:w,cookie:x}=await t(g,{failureRedirect:null}),v=(U,z)=>As(U,{...z,setCookie:x}),V=(U,z,L)=>As(Sp(U,z,L),{setCookie:x});if(!w)return v({error:"Unauthorized"},{status:401});let j=ie();try{if(I.endpoint!==se.action)return v({error:"Unknown endpoint"},{status:404});let U=te.spend(w.id,"action");if(U!==null)return v({error:U.message},{status:U.status,headers:U.headers});let z=await Sa(g,l);if("refusal"in z){let{refusal:Z}=z;return Z.status===413&&F(Z.measuredBy),v({error:Z.error},{status:Z.status})}let{command:L}=z;if(L.intent==="clearCache"&&!e.enableDevCacheClear)return v({error:"Invalid intent"},{status:400});let X=await u(g,"initial");if(!X.ok)return v({error:yr},{status:503,headers:{...Ae(503),"Cache-Control":"no-store"}});let Y=await r.getUserIdByExternalId(w.id);return Y?L.intent==="clearCache"?(await r.clearCache(),v({status:"OK",intent:"clearCache"})):await J(L,Y,X.scope,v,V):v({error:"User not found"},{status:404})}catch(U){if(U instanceof Response)throw U;let z=ie()-j,L=U instanceof Error?U:new Error(String(U));return c.error(`500 action elapsed=${z}ms name=${L.name} message=${L.message}`,L),v({error:"Internal Server Error"},{status:500})}},he=Ds({authenticate:t,service:r,resolveViewerScope:u,redis:o,sseReader:a,streamKey:i,streamSlots:b,logger:R}),le=Ri({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:u,logger:p}),fe=Ca(m),P=(g,I)=>async w=>{let x=_a(w.request)?g.frameworkDataRefusal(w):null;if(x!==null)throw x;return xa(w.request,g)?(fe(g.route,w.request),g.crossSiteRejection()):I(w)};return{index:{loader:$},api:{loader:P(fp,E),action:P(Rp,ue)},sse:{loader:P(gs,he)},attachment:{loader:P(fi,le)}}}var Kt=require("@aiquants/mssql"),ge=require("drizzle-orm");var Mp=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],Pp=["document","comment"],Lp=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],kp=["hubId","ordinal","authorUserId","commentText"],uo=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Ms=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw pn(e,n,r)},Ps=(e,t,r)=>{if(typeof t!="object"||t===null)throw Q(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw Q(`${e}.${o}`,"a column",n[o])},Ls=(e,t)=>{if(!uo(e))throw Q("search","a plain object",e);Ms("search key",e,Mp);let{tables:r}=e;if(!uo(r))throw Q("search.tables","a plain object with document and comment",r);Ms("search.tables key",r,Pp),Ps("search.tables.document",r.document,Lp),Ps("search.tables.comment",r.comment,kp);let n=new Map;if(e.externalSourceTexts!==void 0){if(!uo(e.externalSourceTexts))throw Q("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw pn("search.externalSourceTexts key",o,t);if(typeof a!="function")throw Q(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:ae("search.concurrency",e.concurrency,1),rateLimitPerMinute:ae("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var gt=e=>{let t=typeof e=="object"&&e!==null?e.recordset:void 0;if(!Array.isArray(t))throw new Error("[daily-report] search: the database result has no recordset");return t},Lt=(e,t)=>{let r=typeof e=="string"?ze(e):typeof e=="number"&&Xe(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},kt=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};var B=require("drizzle-orm");var mt=require("drizzle-orm"),ks=e=>{if(e.length===0)throw new Error("[daily-report] draft rule: draftLabelNames must hold at least one name (a rule without names would show every draft to every viewer)");return mt.sql.join(e.map(t=>mt.sql`${t}`),mt.sql`, `)},Jr=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return mt.sql`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${ks(t)}))`},Ns=(e,t)=>{let{hubLabel:r,label:n}=e;return mt.sql`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${ks(t)}))`},Qr=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?mt.sql`${o.userId} = ${t} OR ${o.userId} IS NULL`:mt.sql`${o.userId} = ${t}`;return mt.sql`(${a} OR NOT ${Jr(e,r)})`};var Np=/[[%_]/gu,vp=e=>e.replace(Np,t=>`[${t}]`),vs=e=>`%${vp(e)}%`;var Ke=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),Nt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),fr=Object.freeze({value:"value"}),Ce=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),q=e=>B.sql`${B.sql.identifier(e.name)}`,hr=e=>B.sql.join(e.map(t=>B.sql`${t}`),B.sql`, `),Os=(e,t)=>B.sql`SELECT ${q(e.id)} AS ${B.sql.identifier(Ce.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${hr(t)}) ORDER BY ${e.id}`,Op=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>vs(u.text)),l=B.sql.join(i.map(u=>B.sql`${o.searchText} LIKE ${u}`),B.sql` OR `),s=B.sql.join(i.map(u=>B.sql`${a.commentText} LIKE ${u}`),B.sql` OR `),c=dr(n.sourceType,r.scope.commentable),d=c===void 0?B.sql``:B.sql` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return B.sql`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},Hs=(e,t,r)=>B.sql`(${B.sql.join(t.words.map(n=>Op(e,n,r)),B.sql` AND `)})`,po=(e,t,r,n)=>{let{hub:o}=e,a=[B.sql`${o.deletedAt} IS NULL`,Qr(e,t.userId,r,"author")],i=dr(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(B.sql`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},Hp=(e,t)=>{let{hub:r}=e,{document:n}=e.search,o=[];if(t.sourceTypes!==null){if(t.sourceTypes.size===0)throw new Error("[daily-report] search: a source-type filter must hold at least one source type");o.push(B.sql`LOWER(${r.sourceType}) IN (${hr([...t.sourceTypes])})`)}return t.authors!==null&&o.push(B.sql`${n.authorName} IN (${hr(t.authors)})`),t.customers!==null&&o.push(B.sql`${n.customerName} IN (${hr(t.customers)})`),o},Fs=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...po(e,r,n,o),...Hp(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?B.sql` AND `:B.sql` OR `;s.push(B.sql`(${B.sql.join(l.sets.map(d=>Hs(e,d,r)),c)})`)}return B.sql`SELECT ${q(a.id)} AS ${B.sql.identifier(Ke.reportHubId)}, CONVERT(char(10), ${q(a.businessDate)}, 23) AS ${B.sql.identifier(Ke.businessDate)}, ${q(a.sourceType)} AS ${B.sql.identifier(Ke.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.sql.join(s,B.sql` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},Us=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=B.sql.join(t.sets.map((s,c)=>B.sql`(CASE WHEN ${Hs(e,s,r)} THEN ${2**c} ELSE 0 END)`),B.sql` + `);return B.sql`SELECT ${q(a.id)} AS ${B.sql.identifier(Nt.reportHubId)}, ${l} AS ${B.sql.identifier(Nt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.sql.join(po(e,r,n,o),B.sql` AND `)}`},$s=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...po(e,r,n),B.sql`${i} IS NOT NULL`];return B.sql`SELECT ${i} AS ${B.sql.identifier(fr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${B.sql.join(l,B.sql` AND `)} GROUP BY ${i} ORDER BY ${i}`},Bs=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(s=>({[n.hubId.name]:s.hubId,[n.searchText.name]:s.searchText,[n.sourceDigest.name]:s.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:s.authorName,[n.customerName.name]:s.customerName}))),i=JSON.stringify(t.flatMap(s=>s.comments.map(c=>({[o.hubId.name]:s.hubId,[o.ordinal.name]:c.ordinal,[o.authorUserId.name]:c.authorUserId,[o.commentText.name]:c.commentText})))),l=JSON.stringify(t.map(s=>s.hubId));return B.sql`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${q(n.hubId)} bigint, ${q(n.searchText)} nvarchar(max), ${q(n.sourceDigest)} char(64), ${q(n.normalizerVersion)} varchar(64), ${q(n.authorName)} nvarchar(max), ${q(n.customerName)} nvarchar(max))) AS s ON t.${q(n.hubId)} = s.${q(n.hubId)}
|
|
8
|
+
WHEN MATCHED THEN UPDATE SET t.${q(n.searchText)} = s.${q(n.searchText)}, t.${q(n.sourceDigest)} = CONVERT(binary(32), s.${q(n.sourceDigest)}, 2), t.${q(n.normalizerVersion)} = s.${q(n.normalizerVersion)}, t.${q(n.authorName)} = s.${q(n.authorName)}, t.${q(n.customerName)} = s.${q(n.customerName)}, t.${q(n.indexedAt)} = SYSUTCDATETIME()
|
|
9
|
+
WHEN NOT MATCHED THEN INSERT (${q(n.hubId)}, ${q(n.searchText)}, ${q(n.sourceDigest)}, ${q(n.normalizerVersion)}, ${q(n.authorName)}, ${q(n.customerName)}) VALUES (s.${q(n.hubId)}, s.${q(n.searchText)}, CONVERT(binary(32), s.${q(n.sourceDigest)}, 2), s.${q(n.normalizerVersion)}, s.${q(n.authorName)}, s.${q(n.customerName)});
|
|
10
10
|
DELETE FROM ${o} WHERE ${o.hubId} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${l}));
|
|
11
|
-
INSERT INTO ${o} (${V(o.hubId)}, ${V(o.ordinal)}, ${V(o.authorUserId)}, ${V(o.commentText)}) SELECT ${V(o.hubId)}, ${V(o.ordinal)}, ${V(o.authorUserId)}, ${V(o.commentText)} FROM OPENJSON(${i}) WITH (${V(o.hubId)} bigint, ${V(o.ordinal)} int, ${V(o.authorUserId)} bigint, ${V(o.commentText)} nvarchar(max));`},Ps=(e,t)=>U.sql`SELECT ${V(e.hubId)} AS ${U.sql.identifier(_e.hubId)}, LOWER(CONVERT(char(64), ${V(e.sourceDigest)}, 2)) AS ${U.sql.identifier(_e.sourceDigest)}, ${V(e.normalizerVersion)} AS ${U.sql.identifier(_e.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${pr(t)})`,Ls=(e,t,r)=>U.sql`SELECT TOP (${r}) ${V(e.id)} AS ${U.sql.identifier(_e.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var ks=e=>({search:async(t,r)=>Le(r.scope.visible)?[]:Dt(await t.execute(_s(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Nt(o[Ge.sourceType],Ge.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${Ge.sourceType} is null`);return{reportHubId:kt(o[Ge.reportHubId],Ge.reportHubId),businessDate:Nt(o[Ge.businessDate],Ge.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Le(r.scope.visible))return new Map;let n=Dt(await t.execute(xs(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames,r.ids))),o=2**r.plan.sets.length-1,a=new Map;for(let i of n){let l=i[vt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${vt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(kt(i[vt.reportHubId],vt.reportHubId),l)}return a},facetValues:async(t,r)=>Le(r.scope.visible)?[]:Dt(await t.execute(Cs(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Nt(o[mr.value],mr.value);if(a===null)throw new Error(`[daily-report] search: column ${mr.value} is null`);return a})});var ot=require("@aiquants/mssql"),co=require("drizzle-orm");var vs=require("crypto");var Dp=Object.freeze({authorName:"author",customerName:"customer"}),so=e=>e===null?null:Pn(e),Ns=(e,t,r)=>{let n=so(r);if(n!==null&&n.length>lt.maxValueLength){let o=lt.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${Dp[t]} display value has ${n.length} UTF-16 units after trimming; the host must keep the author and customer display values at most ${o} UTF-16 units`)}return n},yr=e=>e===null?"n;":`s${e.length}:${e}`,hr="utf16le",Tp=e=>{let t=(0,vs.createHash)("sha256");t.update(`F${e.fields.length};`,hr);for(let[r,n]of e.fields)t.update(yr(r)+yr(n),hr);return t.update(`C${e.comments.length};`,hr),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${yr(r.text)}`,hr)}),t.update(`P;${yr(so(e.filterValues.authorName))}${yr(so(e.filterValues.customerName))}`,hr),t.digest("hex")},lo=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=qr(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=qr(o.text);t+=a.forcedCuts,a.text.length!==0&&n.push({ordinal:n.length,authorUserId:o.authorUserId,commentText:a.text})}return{hubId:e.hubId,searchText:$i(r),comments:n,sourceDigest:Tp(e),forcedCuts:t,authorName:Ns(e.hubId,"authorName",e.filterValues.authorName),customerName:Ns(e.hubId,"customerName",e.filterValues.customerName)}};var Os=e=>{let t=async(s,c)=>{let d=[];for(let u of(0,ot.chunk)(c,ot.MAX_IN_LIST))for(let R of Dt(await s.execute(ws(e.hub,u))))d.push(kt(R[_e.hubId],_e.hubId));return d},r=async(s,c)=>{for(let d of(0,ot.chunk)(c,ot.MAX_IN_LIST))await s.execute(Ms(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of(0,ot.chunk)(c,ot.MAX_IN_LIST))for(let R of Dt(await s.execute(Ps(e.tables.document,u))))d.set(kt(R[_e.hubId],_e.hubId),{sourceDigest:Nt(R[_e.sourceDigest],_e.sourceDigest),normalizerVersion:Nt(R[_e.normalizerVersion],_e.normalizerVersion)});return d},o=async(s,c,d)=>Dt(await s.execute(Ls(e.hub,c,d))).map(u=>kt(u[_e.hubId],_e.hubId)),a=async(s,c)=>{let d=await t(s,[...new Set(c)].sort((R,m)=>R-m));if(d.length===0)return;let u=(await e.loadSources(s,d)).map(lo);u.length>0&&await r(s,u)},i=s=>e.inTransaction(async c=>{await c.execute(co.sql`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),R=(await e.loadSources(c,d)).map(lo),m=R.filter(p=>{let f=u.get(p.hubId);return f===void 0||f.sourceDigest!==p.sourceDigest||f.normalizerVersion!==e.normalizerVersion});return m.length>0&&await r(c,m),await c.execute(co.sql`SET DEADLOCK_PRIORITY NORMAL`),{scanned:R.length,written:m.length,forcedCuts:R.reduce((p,f)=>p+f.forcedCuts,0)}});return{writeHubs:a,reconcile:async(s,c)=>{let{batchSize:d,hubIds:u,signal:R,onProgress:m}=c;de("reconcileSearchIndex: batchSize",d,1,ot.MAX_IN_LIST);let p=se(),f=u===void 0?null:(0,ot.chunk)([...new Set(u)].sort((S,_)=>S-_),d),y={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let S=0;;S++){R?.throwIfAborted();let _=f===null?await o(s,y.lastHubId===null?0:y.lastHubId,d):f[S];if(_===void 0||_.length===0)break;let D=await i(_);y={scanned:y.scanned+D.scanned,written:y.written+D.written,skipped:y.skipped+D.scanned-D.written,forcedCuts:y.forcedCuts+D.forcedCuts,lastHubId:_[_.length-1]},m?.(y)}return{...y,elapsedMs:se()-p}}}};var Bs=require("@aiquants/fuzzy-search/normalize");var uo=255,Zr=Object.values(Mt).sort((e,t)=>e-t),Ap=new Intl.Segmenter("und",{granularity:"grapheme"}),he=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),at=5e5,en=Math.floor(at/he.linear),Ep=Math.floor(at/he.segment),Fs=Math.floor(at/he.sweep),Us=Math.floor(at/he.scan),yo=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),$s=(e,t)=>{let r=0,n=t(),o=at,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+at,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=at,a=!1}}},gR=Object.freeze({fits:()=>!0,charge:()=>{}}),Vs=e=>{let t=null;return{step:()=>{if(t!==null)return!0;let r=e.next();return r.done!==!0?!1:(t={result:r.value},!0)},result:()=>{if(t===null)throw new Error("[daily-report] search marks: the walk is not done (step until it returns true)");return t.result}}};var wp=(e,t)=>{if(e.text!==t)throw new Error(`[daily-report] search marks: the position-mapped line (${e.text.length} units) differs from the index line (${t.length} units)`);return e},Ip=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length;function*_p(e,t,r,n){let o=!1;for(let c=t;c<r&&!o;c+=en){let d=Math.min(r,c+en),u=(d-c)*he.linear;n.fits(u)||(yield),o=(0,Bs.holdsMultiUnitCluster)(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=Ap.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(Ep,s.value.segment.length);n.fits(c*he.segment)||(yield);let d=0;for(;!s.done&&d+s.value.segment.length<=c;){let{index:u,segment:R}=s.value;a.fill(t+u,u,u+R.length),i.fill(t+u+R.length,u,u+R.length),d+=R.length,s=l.next()}n.charge(d*he.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var xp=256,Cp=e=>{let t=new Int32Array(e.length),r=0;for(let n=1;n<e.length;n++){for(;r>0&&e.charCodeAt(n)!==e.charCodeAt(r);)r=t[r-1];e.charCodeAt(n)===e.charCodeAt(r)&&r++,t[n]=r}return e.length-t[e.length-1]},Mp=e=>{let t=new Map;for(let r of e){if(r.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let n=t.get(r.text);(n===void 0||r.tier<n)&&t.set(r.text,r.tier)}return[...t].map(([r,n])=>{let o=Cp(r),a=Math.max(Us-r.length+1,r.length);if(o===r.length)return{text:r,tier:n,periodic:null,windowStarts:a};let i=r.length%o,l=r.slice(i,o)+r.slice(0,i);return{text:r,tier:n,periodic:{period:o,continuation:l.repeat(Math.ceil(xp/o))},windowStarts:a}})},tn=(e,t)=>{let{pieces:r}=e,n=r[e.lastPiece];if(n.plainStart<=t&&t<n.plainStart+n.text.length)return e.lastPiece;let o=0,a=r.length-1;for(;o<a;){let i=o+a+1>>1;r[i].plainStart<=t?o=i:a=i-1}return t>=r[o].plainStart+r[o].text.length?-1:(e.lastPiece=o,o)},Hs=(e,t,r)=>{let n=tn(e,t);return e.pieces[n>=0?n:tn(e,r==="start"?t-1:t+1)]},Ys=(e,t)=>{let r=tn(e,t);if(r<0)return qs(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},qs=(e,t)=>{let r=tn(e,t);if(r<0)return Ys(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},Pp=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),Lp=Object.freeze({kind:"done"}),po=Object.freeze({kind:"slice"}),kp=Object.freeze({kind:"clusters"}),Np=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:s,periodic:c}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(he.run))return po;let m=Hs(e,n.closedStart,"start"),p=Hs(e,n.closedEnd-1,"end");if(m.mapped===null)return{kind:"map",piece:m};if(p.mapped===null)return{kind:"map",piece:p};if(e.isCut&&e.clusters===void 0)return kp;let f=t(e.offset+Ys(e,n.closedStart)),y=t(e.offset+qs(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let S=e.clusters;S==null?a(f,y,s):a(S.clusterStarts[f-S.start],S.clusterEnds[y-1-S.start],s),o.charge(he.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(at))return po;let{period:m,continuation:p}=c,f=n.periodicEnd,y=Math.min(i.length,f+Math.max(Us,p.length)),S=f;for(;S+p.length<=y&&i.startsWith(p,S);)S+=p.length;let _=S+p.length>y&&y<i.length;if(!_)for(;S<i.length&&i.charCodeAt(S)===i.charCodeAt(S-m);)S++;if(o.charge((S-f)*he.scan),_){n.periodicEnd=S;continue}n.periodicEnd=-1,n.last+=Math.floor((S-n.last-l.length)/m)*m,n.from=n.last+l.length-m+1;continue}if(n.from<0){if(n.runStart<0)return Lp;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(at))return po;n.from>=n.windowEnd&&(n.windowStart=n.from,n.windowEnd=n.from+r.windowStarts,n.window=i.slice(n.from,n.windowEnd+l.length-1));let d=n.from-n.windowStart,u=n.window.indexOf(l,d);if(u<0){o.charge((n.window.length-d)*he.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*he.scan);let R=n.windowStart+u;(n.runStart<0||R>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=R),n.last=R,c===null?n.from=R+1:n.periodicEnd=R+l.length}};function*mo(e,t,r){let n=Math.floor(at/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*vp(e,t,r,n,o){if(t.length===0)return;let a=yield*mo(Vi(e),he.strip,n),i=[],l=[];yield*mo(Yi(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),he.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(he.line)||(yield),n.charge(he.line);let d=i[c],u=a.text.slice(d,l[c]),R=yield*mo(qi(u,r),he.plan,n),m=[],p="";for(let y of R.chunks){let S="",_=[];for(let D of y){let h=(D.end-D.start)*he.normalize;n.fits(h)||(yield);let g=eo(D.start===0&&D.end===u.length?u:u.slice(D.start,D.end),r).text;n.charge(h),g.length>0&&_.push({start:D.start,end:D.end,text:g,chunkStart:S.length}),S+=g}if(S.length!==0){p.length>0&&(p+=" ");for(let D of _)m.push({start:D.start,end:D.end,text:D.text,plainStart:p.length+D.chunkStart,mapped:null});p+=S}}if(p.length===0)continue;let f={offset:d,plain:p,pieces:m,isCut:!Ip(R,u),lastPiece:0,clusters:void 0};for(let y of t){let S=Pp();for(;;){let _=Np(f,s,y,S,n,o);if(_.kind==="done")break;if(_.kind==="slice"){yield;continue}if(_.kind==="clusters"){f.clusters=yield*_p(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:D}=_,h=(D.end-D.start)*he.map;n.fits(h)||(yield);let g=u.slice(D.start,D.end);D.mapped=wp(Ui(g,Zn(g,r)),D.text),n.charge(h)}}}}function*Op(e,t,r,n){let o=new Int32Array(Zr.length),a=0,i=uo;for(let l=0;l<=e;l+=Fs){let s=Math.min(e+1,l+Fs),c=(s-l)*he.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=uo;for(let R=Zr.length-1;R>=0;R--){let m=Zr[R];o[m]+=t[m][d],o[m]>0&&(u=m)}if(u!==i){if(i!==uo&&!n(a,d,i))return!1;a=d,i=u}}r.charge(c)}return!0}function*Fp(e,t,r,n,o){let a=null;return yield*vp(e,t,r,n,(l,s,c)=>{a===null&&(a=Zr.map(()=>new Int32Array(e.length+1))),a[c][l]++,a[c][s]--}),a===null?!0:yield*Op(e.length,a,n,o)}var Hp=(e,t,r,n)=>{let o=Mp(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return Vs(function*(){return(yield*Fp(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var js=(e,t)=>{if(e.combine==="intersection"||e.sets.length===1)return e.sets.flatMap(r=>r.words);if(t===null)throw new Error(`[daily-report] search marks: a union of ${e.sets.length} keywords needs the report's mask of matched keywords`);return e.sets.flatMap((r,n)=>(t&1<<n)===0?[]:r.words)},Ws=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of Xo)r(st.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(st.interviewer(o,"name"),n.name),r(st.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(st.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(st.comment(En(o),"author"),n.name),r(st.comment(En(o),"content"),n.text)});for(let n of e.postedComments)r(st.comment(n.id,"author"),n.userName),r(st.comment(n.id,"content"),n.content);return t};function*Bp(e,t){let r=_n;for(let n=0;n<e.length;n+=en){let o=Math.min(e.length,n+en),a=(o-n)*he.linear;t.fits(a)||(yield),r=xn(r,e,n,o),t.charge(a)}return r}var zs=async(e,t,r,n)=>{let o=0,a=0,i=async c=>{for(;!c.step();)await r(),n.startSlice();return c.result()},l=async(c,d)=>{if(!d&&a>t.maxRanges)return null;let u={};for(let{key:R,value:m}of c.fields){if(!d&&o+m.length>t.maxUnits)return null;let p=await i(Vs(Bp(m,n))),f=await i(Hp(m,c.alternatives,{maxLength:Jn,maxRanges:t.maxFieldRanges},n));if(o+=m.length,f.dense){u[R]={fingerprint:p,dense:!0};continue}if(u[R]={fingerprint:p,ranges:f.ranges},a+=f.ranges.length/3,!d&&a>t.maxRanges)return null}return u},s=[];for(let c=0;c<e.length;c++){let d=e[c],u=await l(d,s.length===0);if(u===null)return{reports:s,deferred:e.slice(c).map(R=>R.reportHubId)};s.push({reportHubId:d.reportHubId,matchedSets:d.matchedSets,fields:u})}return{reports:s,deferred:[]}};var Oe=require("drizzle-orm");var ve=require("drizzle-orm");var Ke="Internal";var Je=e=>(0,ve.getColumns)(e),be=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},Gs=e=>{let{db:t,tables:r,encodeUserId:n,settings:o,draftVisibilityTables:a}=e,{hub:i,label:l}=r,{externalSources:s,draftLabelNames:c,canonicalDraftLabelName:d}=o,u=k=>lr(i.sourceType,k),R=(k,v)=>Xr(a,k,c,v),m=ve.sql`CASE WHEN ${Qr(a,c)} THEN 1 ELSE 0 END`,p=async k=>{let[v]=await t.select({id:i.id}).top(1).from(i).where((0,ve.and)((0,ve.eq)(i.id,k),Qr(a,c)));return v!==void 0},f=k=>k==null||k===""?null:/^\d+$/.test(k)?n(Number(k)):k,y=()=>{let k={};for(let v of s)k[`ext_${v.sourceType}`]=Je(v.table);return k},S=k=>{let v=k;for(let b of s)v=v.leftJoin(b.table,(0,ve.and)((0,ve.eq)(i.sourceType,b.sourceType),(0,ve.eq)(i.sourceIdNum,b.idColumn)));return v},_=k=>{let{hub:v,internal:b}=k,N=v.summary,$=[],F=null,H=null,K=null,ee=null,W=null,ae=null,Te=[],ke=s.find(J=>J.sourceType===v.sourceType),Re=ke?k[`ext_${ke.sourceType}`]:void 0;if(ke&&Re){let J=ke.mapRow(Re);J.content!==void 0&&(N=J.content),J.employeeName!==void 0&&(ae=J.employeeName),J.category!==void 0&&(F=J.category),J.creationCategory!==void 0&&(H=J.creationCategory),J.visitTimeFrom!==void 0&&(K=J.visitTimeFrom),J.visitTimeTo!==void 0&&(ee=J.visitTimeTo),J.customerName!==void 0&&(W=J.customerName),J.interviewers!==void 0&&($=J.interviewers),J.externalComments!==void 0&&(Te=J.externalComments)}else v.sourceType===Ke&&b&&(N=b.body);return{content:N,author:k.creatorName??f(v.createdBy)??"",employeeName:ae??k.creatorName??f(v.createdBy),updatedBy:f(v.updatedBy),category:F,creationCategory:H,visitTimeFrom:K,visitTimeTo:ee,customerName:W,interviewers:$,externalComments:Te}},D=k=>{if(k===1)return!0;if(k===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${dn(k)}`)},h=k=>k.creationCategory!==null&&c.includes(k.creationCategory),g=(k,v)=>D(k.hasDraftLabel)?!0:h(v),P=async k=>{let[v]=await k.select({id:l.id}).top(1).from(l).where((0,ve.eq)(l.name,d)).orderBy((0,ve.asc)(l.id));return v===void 0?null:v.id},x=()=>P(t);return{visibleSourceTypeCondition:u,draftVisibleTo:R,draftLabelFlag:m,isDraftReport:p,externalSelections:y,applyExternalJoins:S,resolveHubDisplayFields:_,readCanonicalDraftLabelId:P,getDraftLabelId:x,resolveCreationCategoryDraftLabelId:k=>k.some(h)?x():Promise.resolve(null),mapHubRecord:(k,v,b,N,$)=>{let{hub:F}=v,H=(v.labels??[]).map(W=>({id:W.id,name:W.name,color:W.color})),K=v.postedCommentRows??[],ee=Ie(k.commentable,F.sourceType);return N!==null&&h(b)&&!H.some(W=>W.id===N)&&H.push({id:N,name:d,color:null}),{reportHubId:F.id,date:be(F.businessDate,"YYYY-MM-DD"),author:b.author,userId:F.userId?n(F.userId):"",sourceType:F.sourceType,createdAt:be(F.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:be(F.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:b.updatedBy,employeeName:b.employeeName,category:b.category,creationCategory:b.creationCategory,visitTimeFrom:b.visitTimeFrom,visitTimeTo:b.visitTimeTo,customerName:b.customerName,interviewers:b.interviewers,subject:F.title,content:b.content,externalComments:ee?b.externalComments:[],isRead:v.isRead??!1,isStarred:v.isStarred??!1,isDraft:g(v,b),labels:H,postedComments:K.filter(W=>Mi({authorUserId:W.userId},F.sourceType,$??null,k)).map(W=>({...W,userId:n(W.userId),isMine:$?W.userId===$:!1})),attachments:v.attachments}}}};var Ks=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r})=>{let{db:n,tables:o,logger:a,settings:i}=e,{hub:l}=o,{attachmentDelivery:s}=i,c=(p,f)=>f!=null?"absent":p!=null?"present":"unknown";return{getAttachmentsByHubIds:async p=>{let f=new Map,y=o.attachment;if(p.length===0||!y||s===null)return f;let S=s.idCodec,_=s.thumbnails!==null,D=await n.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where((0,Oe.inArray)(y.hubId,p)).orderBy((0,Oe.asc)(y.createdAt),(0,Oe.asc)(y.id));for(let h of D){let g=h.fileType?String(h.fileType):null,P=h.fileSize!=null?Number(h.fileSize):null,x=c(h.objectCheckedAt,h.objectMissingAt),M={id:S.encode(Number(h.id)),fileName:String(h.fileName),fileType:g,fileSize:P,createdAt:be(h.createdAt,"YYYY-MM-DD HH:mm:ss"),state:x,hasThumbnail:_&&x!=="absent"&&vr({fileType:g,fileSize:P},s.maxBytes)},j=f.get(Number(h.hubId));j?j.push(M):f.set(Number(h.hubId),[M])}return f},getAttachmentForUser:async(p,f,y)=>{let S=o.attachment;return!S||Le(p.visible)?null:(await n.select({fileName:S.fileName,filePath:S.filePath,fileType:S.fileType,fileSize:S.fileSize}).top(1).from(S).innerJoin(l,(0,Oe.eq)(l.id,S.hubId)).where((0,Oe.and)((0,Oe.eq)(S.id,f),(0,Oe.isNull)(l.deletedAt),t(y,"author"),r(p.visible))))[0]??null},markAttachmentMissing:async p=>{let f=o.attachment;if(!f)return;let y=new Date;try{await n.update(f).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where((0,Oe.eq)(f.id,p))}catch(S){a.error("markAttachmentMissing failed",S)}},markAttachmentPresent:async p=>{let f=o.attachment;if(!f)return;let y=new Date;try{await n.update(f).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where((0,Oe.eq)(f.id,p))}catch(S){a.error("markAttachmentPresent failed",S)}}}};var zt=require("drizzle-orm");var Tt="daily-report:ids:epoch",Fe="daily-report:date-epoch:",Qe="daily-report:detail-epoch:",Js=({redis:e,logger:t,epochs:r,streamKey:n,streamMaxLen:o})=>({incrementRedisEpoch:s=>r.incrementEpoch(s),publishToSseStream:async(s,c)=>{let d=await e?.getClient();if(!d){t.warn(`[SSE] Redis client unavailable (${c})`);return}let u=JSON.stringify(s),R=Buffer.byteLength(u);if(R>6356992){t.warn(`[SSE] Event too large (${c}): ${R} bytes > ${6356992}; not published`);return}let m=se();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let p=se()-m;p>1e3&&t.warn(`[SSE] Slow publish (${c}): ${p}ms`)}catch(p){t.error(`[SSE] Redis publish failed (${c}):`,p)}},readSseStreamAnchor:async()=>{try{let s=await e?.getClient();if(s===void 0)return null;let[c]=await s.xRevRange(n,"+","-",{COUNT:1});return c===void 0?null:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});var Qs=(e,{isDraftReport:t,assertHubMutable:r,incrementRedisEpoch:n})=>{let{db:o,tables:a,users:i,encodeUserId:l,cache:s,inTransaction:c,prepareSearchIndex:d,publishToSseStream:u}=e,{hub:R,comment:m}=a,p=async(_,D)=>{if(D!==null)return await t(_)?D:void 0},f=async(_,D,h,g,P,x)=>{let[M]=await o.select({sourceType:R.sourceType,deletedAt:R.deletedAt,userId:R.userId}).top(1).from(R).where((0,zt.eq)(R.id,h));if(!M||M.deletedAt)throw new Error("Not Found");if(await r(_,h,D),!Ie(_.commentable,M.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(M.sourceType.toLowerCase()!==Ke.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let j=await p(h,M.userId),k=await d(),v=await c(async F=>{let[H]=await F.insert(m).output().values({hubId:h,userId:D,body:g,createdAt:new Date,createdBy:String(D),updatedAt:new Date,updatedBy:String(D)});return k!==null&&await k.writeHubs(F,[h]),H}),[b]=await o.select({displayName:i.displayName}).top(1).from(i).where((0,zt.eq)(i.id,D)),N=b?.displayName??"";if(P){let F=Pe(P);F&&(s.invalidatePrefix(jt(F)),await n(`${Fe}${F}`))}s.invalidatePrefix(Ye(h)),await n(`${Qe}${h}`);let $={id:v.id,userId:l(v.userId),userName:N,content:v.body,createdAt:be(v.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(Rn.parse({type:"comment-add",reportHubId:h,comment:$,clientTempId:x,recipientRawUserId:j,sourceType:M.sourceType}),"addComment"),$},y=async(_,D)=>await _.select().top(1).from(m).where((0,zt.eq)(m.id,D));return{addComment:f,deleteComment:async(_,D,h,g,P,x)=>{let M=await y(o,g);if(M.length===0)throw new Error("Not Found");if(M[0].hubId!==h)throw new Error("Not Found");let[j]=await o.select({userId:R.userId,sourceType:R.sourceType}).top(1).from(R).where((0,zt.eq)(R.id,M[0].hubId));if(!(j&&Ie(_.visible,j.sourceType)))throw new Error("Not Found");if(M[0].userId!==D)throw new Error("Unauthorized");let k=await p(h,j.userId),v=await d();if(await c(async b=>{await b.delete(m).where((0,zt.eq)(m.id,g)),v!==null&&await v.writeHubs(b,[h])}),P){let b=Pe(P);b&&(s.invalidatePrefix(jt(b)),await n(`${Fe}${b}`))}s.invalidatePrefix(Ye(h)),await n(`${Qe}${h}`),await u(Sn.parse({type:"comment-delete",reportHubId:h,commentId:g,clientTempId:x,recipientRawUserId:k,sourceType:j.sourceType}),"deleteComment")}}};var yt=require("drizzle-orm");var Xs=e=>e===""?null:e,Zs=(e,{readCanonicalDraftLabelId:t,isDraftReport:r,getDailyReportDetailById:n,incrementRedisEpoch:o})=>{let{db:a,tables:i,users:l,encodeUserId:s,cache:c,logger:d,inTransaction:u,prepareSearchIndex:R,publishToSseStream:m,settings:p,draftVisibilityTables:f}=e,{hub:y,internal:S,hubLabel:_}=i,{canonicalDraftLabelName:D,draftLabelNames:h}=p,g=async(b,N,$)=>{if(!br(N))throw X("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",N);d.info("createDailyReport called",{userId:b,businessDate:N});let[F]=await a.select({displayName:l.displayName}).from(l).where((0,yt.eq)(l.id,b)),H=F?.displayName??s(b),K=await R();try{let ee=await u(async ae=>{d.info("Starting transaction");let Te=await t(ae);if(Te===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(D)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let ke=`internal-temp-${Date.now()}-${Math.random()}`,[Re]=await ae.insert(y).output().values({sourceType:Ke,sourceId:ke,businessDate:new Date(`${N}T00:00:00Z`),userId:b,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(b),updatedAt:new Date,updatedBy:String(b)});await ae.update(y).set({sourceId:String(Re.id)}).where((0,yt.eq)(y.id,Re.id)),d.info("Hub created",Re),await ae.insert(S).values({hubId:Re.id,body:"",createdAt:new Date,createdBy:String(b),updatedAt:new Date,updatedBy:String(b)}),d.info("Internal created"),await ae.insert(_).values({hubId:Re.id,labelId:Te,createdAt:new Date,createdBy:String(b)});let J=[{id:Te,name:D,color:null}];return d.info("Label assigned"),K!==null&&await K.writeHubs(ae,[Re.id]),{reportHubId:Re.id,date:N,createdAt:be(Re.createdAt,"YYYY-MM-DD HH:mm:ss"),author:H,userId:s(b),sourceType:Ke,employeeName:H,updatedBy:s(b),updatedAt:be(Re.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:Re.title,content:"",externalComments:[],isRead:!0,isStarred:!1,isDraft:!0,labels:J,postedComments:[],attachments:[]}});c.invalidatePrefix(Lt(N,b)),c.invalidatePrefix(gt),c.invalidatePrefix(no(b)),await o(Tt),await o(`${Fe}${N}`);let W=await n(Ue.unrestricted("post-write self read: the writer always sees the row they just wrote"),ee.reportHubId,b,{forceRefresh:!0});if(W){let ae=await r(W.reportHubId);await m(gn.parse({type:"report-create",reportHubId:W.reportHubId,report:W,clientTempId:$,recipientRawUserId:ae?b:void 0}),"createDailyReport")}return W??ee}catch(ee){throw d.error("Error in createDailyReport",ee),ee}},P=async(b,N)=>await b.select().top(1).from(y).where((0,yt.eq)(y.id,N)),x=async(b,N,$)=>{await b.update(y).set($).where((0,yt.eq)(y.id,N))},M=async(b,N,$)=>{await b.update(S).set($).where((0,yt.eq)(S.hubId,N))};return{createDailyReport:g,updateDailyReport:async(b,N,$,F)=>{let H=await P(a,b);if(!H.length||H[0].deletedAt)throw new Error("Not Found");if(H[0].userId!==N)throw new Error("Unauthorized");let K=await R();await u(async ae=>{$.title!==void 0&&await x(ae,b,{title:Xs($.title),updatedAt:new Date,updatedBy:String(N)}),$.content!==void 0&&await M(ae,b,{body:Xs($.content),updatedAt:new Date,updatedBy:String(N)}),K!==null&&await K.writeHubs(ae,[b])}),c.invalidatePrefix(Ye(b)),c.invalidatePrefix(gt),await o(`${Qe}${b}`);let ee=Pe(be(H[0].businessDate,"YYYY-MM-DD"));ee&&(c.invalidatePrefix(jt(ee)),await o(`${Fe}${ee}`));let W=await n(Ue.unrestricted("post-write self read: the writer always sees the row they just wrote"),b,N,{forceRefresh:!0});if(W){let ae=await r(b);await m(bn.parse({type:"report-update",reportHubId:W.reportHubId,report:W,clientTempId:F,recipientRawUserId:ae?N:void 0}),"updateDailyReport")}},publishDailyReport:async(b,N,$)=>{let F=await P(a,b);if(!F.length)throw new Error("Not Found");if(F[0].userId!==N)throw new Error("Unauthorized");let H=await R();if(await u(async W=>{await W.delete(_).where((0,yt.and)((0,yt.eq)(_.hubId,b),As(f,h))),H!==null&&await H.writeHubs(W,[b])}),c.invalidatePrefix(Ye(b)),c.invalidatePrefix(gt),c.invalidatePrefix(St),await o(Tt),F[0].businessDate){let W=Pe(be(F[0].businessDate,"YYYY-MM-DD"));W&&await o(`${Fe}${W}`)}let K=Pe(be(F[0].businessDate,"YYYY-MM-DD"));K&&c.invalidatePrefix(Lt(K,N));let ee=await n(Ue.unrestricted("post-write self read: the writer always sees the row they just wrote"),b,N,{forceRefresh:!0});if(ee){let W=await r(b);await m(Dn.parse({type:"report-publish",reportHubId:ee.reportHubId,report:ee,clientTempId:$,recipientRawUserId:W?N:void 0}),"publishDailyReport")}return ee??null},deleteDailyReport:async(b,N,$)=>{let F=await P(a,b);if(!F.length||F[0].deletedAt)throw new Error("Not Found");if(F[0].userId!==N)throw new Error("Unauthorized");if(await u(async H=>{await x(H,b,{deletedAt:new Date,deletedBy:String(N),updatedAt:new Date,updatedBy:String(N)})}),c.invalidatePrefix(Ye(b)),c.invalidatePrefix(gt),c.invalidatePrefix(St),await o(Tt),F[0].businessDate){let H=Pe(be(F[0].businessDate,"YYYY-MM-DD"));H&&await o(`${Fe}${H}`)}await m(Tn.parse({type:"report-delete",reportHubId:b,clientTempId:$,sourceType:F[0].sourceType}),"deleteDailyReport")}}};var Y=require("drizzle-orm");var el=Ar([]),tl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r,draftLabelFlag:n,externalSelections:o,applyExternalJoins:a,resolveHubDisplayFields:i,resolveCreationCategoryDraftLabelId:l,mapHubRecord:s,getAttachmentsByHubIds:c,readSseStreamAnchor:d,incrementRedisEpoch:u})=>{let{db:R,tables:m,users:p,resolveUserId:f,cache:y,epochs:S,logger:_,settings:D}=e,{hub:h,internal:g,comment:P,label:x,hubLabel:M,userStatus:j}=m,k=D.idsTtlMs,v=D.businessDateTtlMs,b=async(A,E)=>(await R.select({reportHubId:h.id,businessDate:h.businessDate,sourceType:h.sourceType}).from(h).where((0,Y.and)((0,Y.isNull)(h.deletedAt),t(E,"author-or-authorless"),r(A.visible))).orderBy((0,Y.desc)(h.businessDate),(0,Y.desc)(h.id))).map(C=>({...C,businessDate:be(C.businessDate,"YYYY-MM-DD")})),N=async(A,E,I)=>{let C=await H(E);return C?Le(A.visible)?[]:(await R.select({reportHubId:h.id,businessDate:h.businessDate,sourceType:h.sourceType}).top(I).from(h).where((0,Y.and)((0,Y.isNull)(h.deletedAt),t(C,"author-or-authorless"),r(A.visible))).orderBy((0,Y.desc)(h.businessDate),(0,Y.desc)(h.id))).map(q=>({...q,businessDate:be(q.businessDate,"YYYY-MM-DD")})):[]},$=async(A,E)=>{let I=await a(R.select({hub:Je(h),internal:Je(g),creatorName:p.displayName,hasDraftLabel:n,...o()}).from(h)).leftJoin(g,(0,Y.eq)(h.id,g.hubId)).leftJoin(p,(0,Y.eq)(h.userId,p.id)).where((0,Y.and)((0,Y.eq)(h.businessDate,Y.sql`${E}`),(0,Y.isNull)(h.deletedAt),r(A.visible))).orderBy((0,Y.desc)(h.id)),C=await c(I.map(B=>B.hub.id)),O=I.map(i),q=await l(O);return I.map((B,z)=>s(A,{...B,attachments:C.get(B.hub.id)??[]},O[z],q))},F=new Map,H=async A=>{if(!D.disableUserIdCache&&F.has(A))return F.get(A)??null;let E=await f(A);return E!==null&&!D.disableUserIdCache&&F.set(A,E),E},K=async(A,E,{forceRefresh:I=!1,snapshot:C=!1,ttlMsOverride:O,onFetchStart:q,admission:B}={})=>{let z=await H(E);if(!z)return{items:[],streamAnchor:null,snapshot:el};if(Le(A.visible))return{items:[],streamAnchor:await d(),snapshot:el};let L=Zi(z,cr(A)),[G]=await y.getOrFetch({cacheKey:L,fetcher:async()=>{let te=await d(),Z=await b(A,z);if(!Go(Z)){_.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let ce=[...Z].sort(An);return[{items:ce,streamAnchor:te,snapshot:Ar(ce)}]}return[{items:Z,streamAnchor:te,snapshot:Ar(Z)}]},onFetchStart:q,forceRefresh:I,snapshot:C,admission:B,ttlMsOverride:O??k,epochKey:Tt,refreshAheadRatio:.5});if(G===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return G},ee=(A,E,{forceRefresh:I=!1,snapshot:C=!1,ttlMsOverride:O}={})=>{let q=Pe(E);return q?Le(A.visible)?Promise.resolve([]):y.getOrFetch({cacheKey:es(q,cr(A)),fetcher:()=>$(A,q),forceRefresh:I,snapshot:C,ttlMsOverride:O??v}):Promise.resolve([])},W=async(A,E,I)=>{let C=await a(R.select({hub:Je(h),internal:Je(g),isRead:j.isRead,isStarred:j.isStarred,creatorName:p.displayName,hasDraftLabel:n,...o()}).from(h)).leftJoin(g,(0,Y.eq)(h.id,g.hubId)).leftJoin(j,(0,Y.and)((0,Y.eq)(h.id,j.hubId),(0,Y.eq)(j.userId,E))).leftJoin(p,(0,Y.eq)(h.userId,p.id)).where((0,Y.and)(I,(0,Y.isNull)(h.deletedAt),t(E,"author"),r(A.visible))).orderBy((0,Y.desc)(h.id));if(C.length===0)return[];let O=C.map(ce=>ce.hub.id),q=await R.select({hubId:M.hubId,id:x.id,name:x.name,color:x.color}).from(M).innerJoin(x,(0,Y.eq)(M.labelId,x.id)).where((0,Y.inArray)(M.hubId,O)),B=await R.select({hubId:P.hubId,id:P.id,body:P.body,createdAt:P.createdAt,userId:P.userId,userName:p.displayName}).from(P).leftJoin(p,(0,Y.eq)(P.userId,p.id)).where((0,Y.inArray)(P.hubId,O)).orderBy((0,Y.asc)(P.createdAt)),z=await c(O),L=new Map,G=new Map;for(let ce of q){let Ce=L.get(ce.hubId);Ce||(Ce=[],L.set(ce.hubId,Ce)),Ce.push({id:ce.id,name:ce.name,color:ce.color})}for(let ce of B){let Ce=G.get(ce.hubId);Ce||(Ce=[],G.set(ce.hubId,Ce)),Ce.push({id:ce.id,content:ce.body,createdAt:be(ce.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ce.userId,userName:ce.userName||""})}let te=C.map(i),Z=await l(te);return C.map((ce,Ce)=>{let At=ce.hub.id;return s(A,{...ce,attachments:z.get(At)??[],labels:L.get(At)||[],postedCommentRows:G.get(At)||[]},te[Ce],Z,E)})},ae=async(A,E,I,{forceRefresh:C=!1,snapshot:O=!1,ttlMsOverride:q,admission:B}={})=>{let z=await H(I);if(!z)return[];let L=Pe(E);if(!L)return[];if(Le(A.visible))return[];let G=ts(L,z,cr(A));return y.getOrFetch({cacheKey:G,fetcher:()=>W(A,z,(0,Y.eq)(h.businessDate,Y.sql`${L}`)),forceRefresh:C,snapshot:O,admission:B,ttlMsOverride:q??v,epochKey:`${Fe}${L}`})},Te=async(A,E,I,{forceRefresh:C=!1,snapshot:O=!1,ttlMsOverride:q,admission:B}={})=>{if(Le(A.visible))return null;let z=rs(E,I,cr(A));return(await y.getOrFetch({cacheKey:z,fetcher:async()=>{let G=await a(R.select({hub:Je(h),internal:Je(g),isRead:j.isRead,isStarred:j.isStarred,creatorName:p.displayName,hasDraftLabel:n,...o()}).from(h)).leftJoin(g,(0,Y.eq)(h.id,g.hubId)).leftJoin(j,(0,Y.and)((0,Y.eq)(h.id,j.hubId),(0,Y.eq)(j.userId,I))).leftJoin(p,(0,Y.eq)(h.userId,p.id)).where((0,Y.and)((0,Y.eq)(h.id,E),(0,Y.isNull)(h.deletedAt),t(I,"author"),r(A.visible)));if(G.length===0)return[];let te=G[0].hub.id,Z=await R.select({id:x.id,name:x.name,color:x.color}).from(M).innerJoin(x,(0,Y.eq)(M.labelId,x.id)).where((0,Y.eq)(M.hubId,te)),ce=await R.select({id:P.id,body:P.body,createdAt:P.createdAt,userId:P.userId,userName:p.displayName}).from(P).leftJoin(p,(0,Y.eq)(P.userId,p.id)).where((0,Y.eq)(P.hubId,te)).orderBy((0,Y.asc)(P.createdAt)),Ce=await c([te]),At=Z.map(qe=>({id:qe.id,name:qe.name,color:qe.color})),an=ce.map(qe=>({id:qe.id,content:qe.body,createdAt:be(qe.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:qe.userId,userName:qe.userName||""})),Sr=i(G[0]),sn=await l([Sr]);return[s(A,{...G[0],attachments:Ce.get(te)??[],labels:At,postedCommentRows:an},Sr,sn,I)]},forceRefresh:C,snapshot:O,admission:B,ttlMsOverride:q??v,epochKey:`${Qe}${E}`}))[0]??null};return{getUserIdByExternalId:H,getDailyReportIdsByExternalId:K,getDailyReportIdsFirstPageByExternalId:N,getDailyReportsByBusinessDate:ee,getDailyReportsByBusinessDateByExternalId:ae,getDailyReportDetailById:Te,getDailyReportDetailByIdByExternalId:async(A,E,I,C={})=>{let O=await H(I);return O?Te(A,E,O,C):null},getDailyReportDetailsByIdsByExternalId:async(A,E,I)=>{if(E.length>we.maxDetailIds)throw X("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${we.maxDetailIds} ids`,E.length);let C=await H(I);return!C||E.length===0?[]:Le(A.visible)?[]:W(A,C,(0,Y.inArray)(h.id,[...E]))},fetchVisibleHubDetails:W,invalidateHubReadCaches:async(A,E)=>{y.invalidatePrefix(gt),y.invalidatePrefix(St),await u(Tt);for(let I of new Set(A))y.invalidatePrefix(Ye(I)),await u(`${Qe}${I}`);for(let I of new Set(E)){let C=Pe(I);C&&await u(`${Fe}${C}`)}},clearCache:async()=>{y.clearAll(),F.clear(),S&&await u(Tt),_.info("Server-side DB/SQL caches cleared successfully.")}}};var rn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,streamKey:"daily-report:sse-stream",streamMaxLen:1e4}),$p=e=>{let{length:t}=e;if(t===void 0)throw X("tables.hub.title","a character column with a declared length",t);return de("tables.hub.title.length",t,1)},Vp=e=>{if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0)||new Set(e).size!==e.length)throw X("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},Yp=e=>{let t=new Map([[Ke.toLowerCase(),`the internal source type ${JSON.stringify(Ke)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw X(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([Ke,...e.map(r=>r.sourceType)])},rl=e=>{let t=e.externalSources??[],r=Vp(e.draftLabelNames);Fr(e);let n=pi(e.attachments),o=$p(e.tables.hub.title),a=Me("idsTtlMs",e.idsTtlMs,1,rn.idsTtlMs),i=Me("businessDateTtlMs",e.businessDateTtlMs,1,rn.businessDateTtlMs),l=Me("streamMaxLen",e.streamMaxLen,1,rn.streamMaxLen);return Object.freeze({externalSources:t,sourceTypes:Yp(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamKey:e.streamKey??rn.streamKey,streamMaxLen:l,disableUserIdCache:!!e.disableUserIdCache})};var xe=require("drizzle-orm");var nl=(e,{draftVisibleTo:t,incrementRedisEpoch:r})=>{let{db:n,tables:o,cache:a,publishToSseStream:i}=e,{hub:l,userStatus:s}=o,c=async(m,p)=>{let[f]=await n.select({sourceType:l.sourceType,deletedAt:l.deletedAt}).top(1).from(l).where((0,xe.and)((0,xe.eq)(l.id,m),t(p,"author")));return f??null},d=async(m,p,f)=>{let y=await c(p,f);if(!y||y.deletedAt||!Ie(m.visible,y.sourceType))throw new Error("Not Found")};return{assertHubMutable:d,setStarStatus:async(m,p,f,y,S,_)=>{await d(m,f,p);let D=await n.select().top(1).from(s).where((0,xe.and)((0,xe.eq)(s.hubId,f),(0,xe.eq)(s.userId,p))),h;if(D.length>0?D[0].isStarred!==S?h=(await n.update(s).set({isStarred:S,updatedAt:new Date,updatedBy:String(p)}).output().where((0,xe.and)((0,xe.eq)(s.hubId,f),(0,xe.eq)(s.userId,p))))[0]:h=D[0]:h=(await n.insert(s).output().values({hubId:f,userId:p,isStarred:S,isRead:!1,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)}))[0],y){let g=Pe(y);g&&(a.invalidatePrefix(Lt(g,p)),await r(`${Fe}${g}`))}return a.invalidatePrefix(zr(f,p)),await r(`${Qe}${f}`),await i(Tr.parse({type:"status-update",reportHubId:f,recipientRawUserId:p,statusType:"star",value:S,clientTempId:_}),"setStarStatus"),h},setReadStatus:async(m,p,f,y,S,_)=>{await d(m,f,p);let D=await n.select().top(1).from(s).where((0,xe.and)((0,xe.eq)(s.hubId,f),(0,xe.eq)(s.userId,p))),h;if(D.length>0?D[0].isRead!==S?h=(await n.update(s).set({isRead:S,updatedAt:new Date,updatedBy:String(p)}).output().where((0,xe.and)((0,xe.eq)(s.hubId,f),(0,xe.eq)(s.userId,p))))[0]:h=D[0]:h=(await n.insert(s).output().values({hubId:f,userId:p,isRead:S,isStarred:!1,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)}))[0],y){let g=Pe(y);g&&(a.invalidatePrefix(Lt(g,p)),await r(`${Fe}${g}`))}return a.invalidatePrefix(zr(f,p)),await r(`${Qe}${f}`),await i(Tr.parse({type:"status-update",reportHubId:f,recipientRawUserId:p,statusType:"read",value:S,clientTempId:_}),"setReadStatus"),h}}};var qp="v3",fo=e=>`${e}:${qp}`,jp=Object.freeze([]),ho=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},nn=(e,t)=>e.get(t)??jp,ol=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Vr),Wp=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw it(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw X(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw it(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw X(`${e}: options.signal`,r,n);return n};function on(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:s}=e,{hub:c,internal:d,comment:u,label:R,hubLabel:m}=r,p=rl(e),{externalSources:f,draftLabelNames:y,attachmentDelivery:S,titleMaxLength:_}=p,D=ge(e.logger,1,"Service"),h=re=>(0,Gt.runWithTransactionRetry)(ue=>t.transaction(Q=>ue(()=>re(Q))),e.transactionRetry),g=e.search===void 0?null:Ds(e.search,f.map(re=>re.sourceType)),P={hub:c,hubLabel:m,label:R},x=g===null?null:ks({tables:{...P,search:g.tables},draftLabelNames:y});g!==null&&ro();let M=null,j=async()=>{if(g===null)return null;if(M===null){let re=await ro(),ue=g.externalSourceTexts;M=Os({hub:c,tables:g.tables,loadSources:(Q,ne)=>Pl(Q,ne,ue),inTransaction:h,normalizerVersion:re})}return M},k=fo(p.streamKey),{incrementRedisEpoch:v,publishToSseStream:b,readSseStreamAnchor:N}=Js({redis:i,logger:D,epochs:s,streamKey:k,streamMaxLen:p.streamMaxLen}),$={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:D,settings:p,draftVisibilityTables:P,inTransaction:h,publishToSseStream:b,prepareSearchIndex:j},{visibleSourceTypeCondition:F,draftVisibleTo:H,draftLabelFlag:K,isDraftReport:ee,externalSelections:W,applyExternalJoins:ae,resolveHubDisplayFields:Te,readCanonicalDraftLabelId:ke,getDraftLabelId:Re,resolveCreationCategoryDraftLabelId:J,mapHubRecord:w}=Gs($),{getAttachmentsByHubIds:A,getAttachmentForUser:E,markAttachmentMissing:I,markAttachmentPresent:C}=Ks($,{draftVisibleTo:H,visibleSourceTypeCondition:F}),{getUserIdByExternalId:O,getDailyReportIdsByExternalId:q,getDailyReportIdsFirstPageByExternalId:B,getDailyReportsByBusinessDate:z,getDailyReportsByBusinessDateByExternalId:L,getDailyReportDetailById:G,getDailyReportDetailByIdByExternalId:te,getDailyReportDetailsByIdsByExternalId:Z,fetchVisibleHubDetails:ce,invalidateHubReadCaches:Ce,clearCache:At}=tl($,{draftVisibleTo:H,visibleSourceTypeCondition:F,draftLabelFlag:K,externalSelections:W,applyExternalJoins:ae,resolveHubDisplayFields:Te,resolveCreationCategoryDraftLabelId:J,mapHubRecord:w,getAttachmentsByHubIds:A,readSseStreamAnchor:N,incrementRedisEpoch:v}),{assertHubMutable:an,setStarStatus:Sr,setReadStatus:sn}=nl($,{draftVisibleTo:H,incrementRedisEpoch:v}),{addComment:qe,deleteComment:Al}=Qs($,{isDraftReport:ee,assertHubMutable:an,incrementRedisEpoch:v}),{createDailyReport:El,updateDailyReport:wl,publishDailyReport:Il,deleteDailyReport:_l}=Zs($,{readCanonicalDraftLabelId:ke,isDraftReport:ee,getDailyReportDetailById:G,incrementRedisEpoch:v}),xl=async(re,ue)=>{let Q=new Map,ne=r.attachment;if(!ne||S===null)return Q;let De=await re.select({hubId:ne.hubId,fileName:ne.fileName}).from(ne).where((0,fe.inArray)(ne.hubId,[...ue])).orderBy((0,fe.asc)(ne.hubId),(0,fe.asc)(ne.createdAt),(0,fe.asc)(ne.id));for(let oe of De)ho(Q,Number(oe.hubId),String(oe.fileName));return Q},Cl=async(re,ue,Q)=>{let ne=new Map;for(let[De,oe]of Q){let Xe=new Map;for(let{hub:Ne}of ue)Ne.sourceType===De&&Ne.sourceIdNum!==null&&Xe.set(Ne.sourceIdNum,Ne.id);if(Xe.size===0)continue;let Et=await oe(re,[...Xe.keys()]);for(let[Ne,ht]of Et){let Kt=Xe.get(Ne);if(Kt===void 0)throw X(`search.externalSourceTexts.${De} answer key`,"a source id that was asked for",Ne);if(!(Array.isArray(ht)&&ht.every(Ot=>typeof Ot=="string")))throw X(`search.externalSourceTexts.${De} answer for ${Ne}`,"an array of strings",ht);ne.set(Kt,ht)}}return ne},Ml=(re,ue)=>{let Q=Te(re),ne=[["subject",re.hub.title],["content",Q.content],["author",Q.author],["employeeName",Q.employeeName],["updatedBy",Q.updatedBy],["category",Q.category],["creationCategory",Q.creationCategory],["customerName",Q.customerName]];for(let oe of Q.interviewers)ne.push(["interviewerName",oe.name??null],["interviewerAffiliation",oe.affiliation??null]);for(let oe of ue.labelNames)ne.push(["label",oe]);for(let oe of ue.attachmentNames)ne.push(["attachment",oe]);for(let oe of ue.extraTexts)ne.push(["extra",oe]);let De=[];for(let oe of Q.externalComments)De.push({authorUserId:null,text:ol(oe.name,oe.text)});for(let oe of ue.postedComments)De.push({authorUserId:oe.userId,text:ol(oe.userName,oe.body)});return{hubId:re.hub.id,fields:ne,comments:De,filterValues:{authorName:Q.employeeName,customerName:Q.customerName}}},Pl=async(re,ue,Q)=>{let ne=[];for(let De of(0,Gt.chunk)(ue,Gt.MAX_IN_LIST)){let oe=await ae(re.select({hub:Je(c),internal:Je(d),creatorName:n.displayName,...W()}).from(c)).leftJoin(d,(0,fe.eq)(c.id,d.hubId)).leftJoin(n,(0,fe.eq)(c.userId,n.id)).where((0,fe.inArray)(c.id,[...De])).orderBy((0,fe.asc)(c.id)),Xe=new Map,Et=await re.select({hubId:m.hubId,name:R.name}).from(m).innerJoin(R,(0,fe.eq)(m.labelId,R.id)).where((0,fe.inArray)(m.hubId,[...De])).orderBy((0,fe.asc)(m.hubId),(0,fe.asc)(R.id));for(let Ee of Et)ho(Xe,Ee.hubId,Ee.name);let Ne=new Map,ht=await re.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,(0,fe.eq)(u.userId,n.id)).where((0,fe.inArray)(u.hubId,[...De])).orderBy((0,fe.asc)(u.hubId),(0,fe.asc)(u.createdAt),(0,fe.asc)(u.id));for(let Ee of ht)ho(Ne,Ee.hubId,Ee);let Kt=await xl(re,De),Ot=await Cl(re,oe,Q);for(let Ee of oe){let wt=Ee.hub.id;ne.push(Ml(Ee,{labelNames:nn(Xe,wt),postedComments:nn(Ne,wt),attachmentNames:nn(Kt,wt),extraTexts:nn(Ot,wt)}))}}return ne},Ll=(re,ue,Q)=>x===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):x.search(t,{criteria:Q,viewerUserId:ue,scope:re}),go=p.sourceTypes,kl=async(re,ue)=>{if(x===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let Q=go.filter(oe=>Ie(re.visible,oe)),ne=await x.facetValues(t,{column:"authorName",viewerUserId:ue,scope:re}),De=await x.facetValues(t,{column:"customerName",viewerUserId:ue,scope:re});return{sourceTypes:Q,authors:ne,customers:De}},Nl=async(re,ue,Q,ne,De)=>{let oe=Wp("markDailyReportSearchHits",De);if(x===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(ne.length>we.maxDetailIds)throw X("markDailyReportSearchHits: reportHubIds",`at most ${we.maxDetailIds} ids`,ne.length);let Xe=Er(ur(Q));if(ne.length===0||Le(re.visible))return{wordsDigest:Xe,reports:[],deferred:[]};oe.throwIfAborted();let Et=await ce(re,ue,(0,fe.inArray)(c.id,[...ne]));oe.throwIfAborted();let Ne=Q.combine==="union"&&Q.sets.length>=2&&Et.length>0?await x.matchedSets(t,{plan:Q,viewerUserId:ue,scope:re,ids:Et.map(Ee=>Ee.reportHubId)}):null,ht=Et.map(Ee=>{let wt=Ne===null?null:Ne.get(Ee.reportHubId),bo=wt===void 0?0:wt;return{reportHubId:Ee.reportHubId,matchedSets:bo,alternatives:js(Q,bo).flatMap(Ol=>Ol.alternatives),fields:Ws(Ee)}}),Ot=await zs(ht,yo,async()=>{await new Promise(Ee=>setImmediate(Ee)),oe.throwIfAborted()},$s(yo,se));return{wordsDigest:Xe,reports:Ot.reports,deferred:Ot.deferred}},vl=async re=>{let ue=await j();if(ue===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return ue.reconcile(t,re)};return{streamKey:k,attachmentDelivery:S,titleMaxLength:_,searchLimits:g===null?null:{concurrency:g.concurrency,rateLimitPerMinute:g.rateLimitPerMinute},searchFilterSourceTypes:go,clearCache:At,invalidateHubReadCaches:Ce,getUserIdByExternalId:O,getDailyReportIdsByExternalId:q,getDailyReportIdsFirstPageByExternalId:B,readSseStreamAnchor:N,getDailyReportsByBusinessDate:z,getDailyReportsByBusinessDateByExternalId:L,getDailyReportDetailById:G,getDailyReportDetailByIdByExternalId:te,getDailyReportDetailsByIdsByExternalId:Z,getDraftLabelId:Re,searchDailyReports:Ll,markDailyReportSearchHits:Nl,listDailyReportSearchFacets:kl,reconcileSearchIndex:vl,getAttachmentsByHubIds:A,getAttachmentForUser:E,markAttachmentMissing:I,markAttachmentPresent:C,setStarStatus:Sr,setReadStatus:sn,addComment:qe,deleteComment:Al,createDailyReport:El,updateDailyReport:wl,publishDailyReport:Il,deleteDailyReport:_l}}var al=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(ge(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return ge(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};var fr=require("drizzle-orm"),T=require("drizzle-orm/mssql-core");function il(e,t){let r=(0,T.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,T.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,T.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,T.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,T.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(fr.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,T.date)("business_date"),userId:(0,T.bigint)("user_id",{mode:"number"}),title:(0,T.nvarchar)("title",{length:200}),summary:(0,T.nvarchar)("summary",{length:"max"}),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,T.datetime2)("updated_at").notNull(),updatedBy:(0,T.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,T.datetime2)("deleted_at"),deletedBy:(0,T.nvarchar)("deleted_by",{length:50})},u=>[(0,T.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),(0,T.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,T.index)(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),(0,T.index)(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),(0,T.index)(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),(0,T.index)(`${e}_DailyReportHub_user_id_index`).on(u.userId),(0,T.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,fr.desc)(u.businessDate),(0,fr.desc)(u.id)),(0,T.index)(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,T.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,T.nvarchar)("body",{length:"max"}),metadata:(0,T.nvarchar)("metadata",{length:"max"}),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,T.datetime2)("updated_at").notNull(),updatedBy:(0,T.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,T.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),(0,T.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:(0,T.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,T.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,T.bigint)("user_id",{mode:"number"}).notNull(),body:(0,T.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,T.datetime2)("updated_at").notNull(),updatedBy:(0,T.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,T.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),(0,T.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,T.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,T.index)(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:(0,T.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,T.bigint)("user_id",{mode:"number"}),name:(0,T.nvarchar)("name",{length:50}).notNull(),color:(0,T.nvarchar)("color",{length:20}),sortOrder:(0,T.int)("sort_order"),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,T.datetime2)("updated_at").notNull(),updatedBy:(0,T.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,T.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),(0,T.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:(0,T.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,T.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull()},u=>[(0,T.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),(0,T.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,T.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:(0,T.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,T.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,T.bit)("is_read").default(!1).notNull(),isStarred:(0,T.bit)("is_starred").default(!1).notNull(),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,T.datetime2)("updated_at").notNull(),updatedBy:(0,T.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,T.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),(0,T.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,T.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:(0,T.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,T.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,T.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,T.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,T.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,T.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,T.nvarchar)("file_type",{length:100}),fileSize:(0,T.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,T.datetime2)("object_checked_at"),objectMissingAt:(0,T.datetime2)("object_missing_at"),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,T.datetime2)("updated_at").notNull(),updatedBy:(0,T.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,T.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),(0,T.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,T.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),(0,T.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),(0,T.index)(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:d,label:l,hubLabel:s,userStatus:c}}var me=require("drizzle-orm/mssql-core");function sl(e){let t=(0,me.mssqlSchema)(e),r=t.table("DailyReportSearchDocument",{hubId:(0,me.bigint)("hub_id",{mode:"number"}).notNull(),searchText:(0,me.nvarchar)("search_text",{length:"max"}).notNull(),sourceDigest:(0,me.binary)("source_digest",{length:32}).notNull(),normalizerVersion:(0,me.varchar)("normalizer_version",{length:64}).notNull(),indexedAt:(0,me.datetime2)("indexed_at").notNull(),rowVersion:(0,me.binary)("row_version",{length:8}).notNull(),authorName:(0,me.nvarchar)("author_name",{length:lt.maxValueLength}),customerName:(0,me.nvarchar)("customer_name",{length:lt.maxValueLength})},o=>[(0,me.primaryKey)({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:(0,me.bigint)("hub_id",{mode:"number"}).notNull(),ordinal:(0,me.int)("ordinal").notNull(),authorUserId:(0,me.bigint)("author_user_id",{mode:"number"}),commentText:(0,me.nvarchar)("comment_text",{length:"max"}).notNull()},o=>[(0,me.primaryKey)({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var zp=5e7,Ro=2e8,Gp=1,So=Object.freeze({fixedBytes:4*1024*1024,pipelineRows:2048,wholeImageBuffer:Object.freeze({"jpeg-single-scan":Object.freeze({kind:"none"}),"jpeg-multi-scan":Object.freeze({kind:"jpeg-coefficients"}),png:Object.freeze({kind:"none"}),"png-interlaced":Object.freeze({kind:"decoded-raster"}),gif:Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-lossy":Object.freeze({kind:"none"}),"webp-lossy-alpha":Object.freeze({kind:"canvas",bytesPerPixel:5}),"webp-lossless":Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-animated":Object.freeze({kind:"canvas",bytesPerPixel:9})})}),ll=125,cl=4,ul=16,dl=50,pl=2,Rr=Object.freeze({renderMs:Be.renderMs,nanosecondsPerBlockVisit:ll,margin:cl,maxBlockVisits:Math.floor(Be.renderMs*1e6/(ll*cl)),walkBudgetMs:ul,nanosecondsPerWalkStep:dl,walkMargin:pl,maxWalkSteps:Math.floor(ul*1e6/(dl*pl))}),Kp=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),ml=75,yl=4,hl="#ffffff",Jp=1,Qp={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Xp=[/out of memory/i,/insufficient memory/i,/memory allocation|allocation failed/i,/(?:cannot|could not|unable to|failed to) allocate/i,/picture memory error/i,/unable to create thread|error creating thread|resource temporarily unavailable/i,/too many open files|no space left on device/i,/\b(?:ENOMEM|EAGAIN|EMFILE|ENFILE|ENOSPC)\b/],fl=Object.freeze({ok:!1,reason:"failed"}),Rl=Object.freeze({ok:!1,reason:"unsupported"}),Sl=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:za(e)}),gl=(e,t)=>{switch(t){case"jpeg":{let r=Wn(e);return r===null?null:Sl(r)}case"png":{let r=Ja(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Qa(e,Rr.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},bl=(e,t)=>{let r=Kp.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=So,a=o.wholeImageBuffer[e.layout];return(a.kind==="none"?0:a.kind==="decoded-raster"?t.width*t.height*n:a.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*a.bytesPerPixel)+o.pipelineRows*t.width*n+o.fixedBytes},Dl=(e,t,r)=>{let n=gl(e,t);return n===null?null:bl(n,r)},Zp=e=>e!==null&&e<=Ro,em=(e,t)=>{if(t!=="jpeg")return gl(e,t);let r=Ga(e,Rr);return r===null||r.blockVisits>Rr.maxBlockVisits?null:Sl(r.header)},tm=e=>{let t=e instanceof Error?e.message:"";return Xp.some(r=>r.test(t))?"failed":"unsupported"},Tl=e=>{e.cache(!1),e.concurrency(Gp),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Qp)});let t=async(n,o,a,i,l)=>{let s=em(n,o);if(s===null)return Rl;try{let c=e(n,{limitInputPixels:zp,animated:!1});if(!Zp(bl(s,await c.metadata())))return Rl;if(l.aborted)return fl;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:hl}).webp({quality:ml,effort:yl}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:tm(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?fl:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${ml}-e${yl}/flatten-${hl}/v${Jp}`,render:r}};function rm(e){e.redis||ge(e.logger,2,"Server").warn("redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=gr(e.redis),r=new Ft({defaultTtlMs:e.cacheDefaultTtlMs,maxBuckets:e.cacheMaxBuckets,maxBytes:e.cacheMaxBytes},t),n=on({...e,cache:r,epochs:t}),o=new Wt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Jr({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:n.searchFilterSourceTypes,...a}}0&&(module.exports={DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,DAILY_REPORT_SSE_CATCH_UP_BATCH,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,buildDailyReportSseStreamKey,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createEpochStore,createSharpThumbnailRenderer,defineDailyReportSchema,defineDailyReportSearchSchema,encodeIdsStreamRows,isStreamIdLte,parseClientTempId,predictSharpThumbnailWorkingSetBytes,readDailyReportSseStreamEntry,transformJsonArray});
|
|
11
|
+
INSERT INTO ${o} (${q(o.hubId)}, ${q(o.ordinal)}, ${q(o.authorUserId)}, ${q(o.commentText)}) SELECT ${q(o.hubId)}, ${q(o.ordinal)}, ${q(o.authorUserId)}, ${q(o.commentText)} FROM OPENJSON(${i}) WITH (${q(o.hubId)} bigint, ${q(o.ordinal)} int, ${q(o.authorUserId)} bigint, ${q(o.commentText)} nvarchar(max));`},Vs=(e,t)=>B.sql`SELECT ${q(e.hubId)} AS ${B.sql.identifier(Ce.hubId)}, LOWER(CONVERT(char(64), ${q(e.sourceDigest)}, 2)) AS ${B.sql.identifier(Ce.sourceDigest)}, ${q(e.normalizerVersion)} AS ${B.sql.identifier(Ce.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${hr(t)})`,qs=(e,t,r)=>B.sql`SELECT TOP (${r}) ${q(e.id)} AS ${B.sql.identifier(Ce.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var Ys=e=>({search:async(t,r)=>ke(r.scope.visible)?[]:gt(await t.execute(Fs(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=kt(o[Ke.sourceType],Ke.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${Ke.sourceType} is null`);return{reportHubId:Lt(o[Ke.reportHubId],Ke.reportHubId),businessDate:kt(o[Ke.businessDate],Ke.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(ke(r.scope.visible))return new Map;let n=gt(await t.execute(Us(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames,r.ids))),o=2**r.plan.sets.length-1,a=new Map;for(let i of n){let l=i[Nt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${Nt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(Lt(i[Nt.reportHubId],Nt.reportHubId),l)}return a},facetValues:async(t,r)=>ke(r.scope.visible)?[]:gt(await t.execute($s(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=kt(o[fr.value],fr.value);if(a===null)throw new Error(`[daily-report] search: column ${fr.value} is null`);return a})});var nt=require("@aiquants/mssql"),ho=require("drizzle-orm");var Ws=require("crypto");var Fp=Object.freeze({authorName:"author",customerName:"customer"}),mo=e=>e===null?null:Ln(e),js=(e,t,r)=>{let n=mo(r);if(n!==null&&n.length>st.maxValueLength){let o=st.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${Fp[t]} display value has ${n.length} UTF-16 units after trimming; the host must keep the author and customer display values at most ${o} UTF-16 units`)}return n},Rr=e=>e===null?"n;":`s${e.length}:${e}`,Sr="utf16le",Up=e=>{let t=(0,Ws.createHash)("sha256");t.update(`F${e.fields.length};`,Sr);for(let[r,n]of e.fields)t.update(Rr(r)+Rr(n),Sr);return t.update(`C${e.comments.length};`,Sr),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${Rr(r.text)}`,Sr)}),t.update(`P;${Rr(mo(e.filterValues.authorName))}${Rr(mo(e.filterValues.customerName))}`,Sr),t.digest("hex")},yo=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=jr(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=jr(o.text);t+=a.forcedCuts,a.text.length!==0&&n.push({ordinal:n.length,authorUserId:o.authorUserId,commentText:a.text})}return{hubId:e.hubId,searchText:Ki(r),comments:n,sourceDigest:Up(e),forcedCuts:t,authorName:js(e.hubId,"authorName",e.filterValues.authorName),customerName:js(e.hubId,"customerName",e.filterValues.customerName)}};var zs=e=>{let t=async(s,c)=>{let d=[];for(let u of(0,nt.chunk)(c,nt.MAX_IN_LIST))for(let R of gt(await s.execute(Os(e.hub,u))))d.push(Lt(R[Ce.hubId],Ce.hubId));return d},r=async(s,c)=>{for(let d of(0,nt.chunk)(c,nt.MAX_IN_LIST))await s.execute(Bs(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of(0,nt.chunk)(c,nt.MAX_IN_LIST))for(let R of gt(await s.execute(Vs(e.tables.document,u))))d.set(Lt(R[Ce.hubId],Ce.hubId),{sourceDigest:kt(R[Ce.sourceDigest],Ce.sourceDigest),normalizerVersion:kt(R[Ce.normalizerVersion],Ce.normalizerVersion)});return d},o=async(s,c,d)=>gt(await s.execute(qs(e.hub,c,d))).map(u=>Lt(u[Ce.hubId],Ce.hubId)),a=async(s,c)=>{let d=await t(s,[...new Set(c)].sort((R,p)=>R-p));if(d.length===0)return;let u=(await e.loadSources(s,d)).map(yo);u.length>0&&await r(s,u)},i=s=>e.inTransaction(async c=>{await c.execute(ho.sql`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),R=(await e.loadSources(c,d)).map(yo),p=R.filter(m=>{let S=u.get(m.hubId);return S===void 0||S.sourceDigest!==m.sourceDigest||S.normalizerVersion!==e.normalizerVersion});return p.length>0&&await r(c,p),await c.execute(ho.sql`SET DEADLOCK_PRIORITY NORMAL`),{scanned:R.length,written:p.length,forcedCuts:R.reduce((m,S)=>m+S.forcedCuts,0)}});return{writeHubs:a,reconcile:async(s,c)=>{let{batchSize:d,hubIds:u,signal:R,onProgress:p}=c;ae("reconcileSearchIndex: batchSize",d,1,nt.MAX_IN_LIST);let m=ie(),S=u===void 0?null:(0,nt.chunk)([...new Set(u)].sort((h,T)=>h-T),d),y={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let h=0;;h++){R?.throwIfAborted();let T=S===null?await o(s,y.lastHubId===null?0:y.lastHubId,d):S[h];if(T===void 0||T.length===0)break;let D=await i(T);y={scanned:y.scanned+D.scanned,written:y.written+D.written,skipped:y.skipped+D.scanned-D.written,forcedCuts:y.forcedCuts+D.forcedCuts,lastHubId:T[T.length-1]},p?.(y)}return{...y,elapsedMs:ie()-m}}}};var Js=require("@aiquants/fuzzy-search/normalize");var fo=255,Xr=Object.values(Ct).sort((e,t)=>e-t),$p=new Intl.Segmenter("und",{granularity:"grapheme"}),Se=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),ot=5e5,Zr=Math.floor(ot/Se.linear),Bp=Math.floor(ot/Se.segment),Gs=Math.floor(ot/Se.sweep),Qs=Math.floor(ot/Se.scan),go=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),Xs=(e,t)=>{let r=0,n=t(),o=ot,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+ot,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=ot,a=!1}}},GR=Object.freeze({fits:()=>!0,charge:()=>{}}),Zs=e=>{let t=null;return{step:()=>{if(t!==null)return!0;let r=e.next();return r.done!==!0?!1:(t={result:r.value},!0)},result:()=>{if(t===null)throw new Error("[daily-report] search marks: the walk is not done (step until it returns true)");return t.result}}};var Vp=(e,t)=>{if(e.text!==t)throw new Error(`[daily-report] search marks: the position-mapped line (${e.text.length} units) differs from the index line (${t.length} units)`);return e},qp=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length;function*Yp(e,t,r,n){let o=!1;for(let c=t;c<r&&!o;c+=Zr){let d=Math.min(r,c+Zr),u=(d-c)*Se.linear;n.fits(u)||(yield),o=(0,Js.holdsMultiUnitCluster)(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=$p.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(Bp,s.value.segment.length);n.fits(c*Se.segment)||(yield);let d=0;for(;!s.done&&d+s.value.segment.length<=c;){let{index:u,segment:R}=s.value;a.fill(t+u,u,u+R.length),i.fill(t+u+R.length,u,u+R.length),d+=R.length,s=l.next()}n.charge(d*Se.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var jp=256,Wp=e=>{let t=new Int32Array(e.length),r=0;for(let n=1;n<e.length;n++){for(;r>0&&e.charCodeAt(n)!==e.charCodeAt(r);)r=t[r-1];e.charCodeAt(n)===e.charCodeAt(r)&&r++,t[n]=r}return e.length-t[e.length-1]},zp=e=>{let t=new Map;for(let r of e){if(r.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let n=t.get(r.text);(n===void 0||r.tier<n)&&t.set(r.text,r.tier)}return[...t].map(([r,n])=>{let o=Wp(r),a=Math.max(Qs-r.length+1,r.length);if(o===r.length)return{text:r,tier:n,periodic:null,windowStarts:a};let i=r.length%o,l=r.slice(i,o)+r.slice(0,i);return{text:r,tier:n,periodic:{period:o,continuation:l.repeat(Math.ceil(jp/o))},windowStarts:a}})},en=(e,t)=>{let{pieces:r}=e,n=r[e.lastPiece];if(n.plainStart<=t&&t<n.plainStart+n.text.length)return e.lastPiece;let o=0,a=r.length-1;for(;o<a;){let i=o+a+1>>1;r[i].plainStart<=t?o=i:a=i-1}return t>=r[o].plainStart+r[o].text.length?-1:(e.lastPiece=o,o)},Ks=(e,t,r)=>{let n=en(e,t);return e.pieces[n>=0?n:en(e,r==="start"?t-1:t+1)]},el=(e,t)=>{let r=en(e,t);if(r<0)return tl(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},tl=(e,t)=>{let r=en(e,t);if(r<0)return el(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},Gp=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),Kp=Object.freeze({kind:"done"}),Ro=Object.freeze({kind:"slice"}),Jp=Object.freeze({kind:"clusters"}),Qp=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:s,periodic:c}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(Se.run))return Ro;let p=Ks(e,n.closedStart,"start"),m=Ks(e,n.closedEnd-1,"end");if(p.mapped===null)return{kind:"map",piece:p};if(m.mapped===null)return{kind:"map",piece:m};if(e.isCut&&e.clusters===void 0)return Jp;let S=t(e.offset+el(e,n.closedStart)),y=t(e.offset+tl(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let h=e.clusters;h==null?a(S,y,s):a(h.clusterStarts[S-h.start],h.clusterEnds[y-1-h.start],s),o.charge(Se.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(ot))return Ro;let{period:p,continuation:m}=c,S=n.periodicEnd,y=Math.min(i.length,S+Math.max(Qs,m.length)),h=S;for(;h+m.length<=y&&i.startsWith(m,h);)h+=m.length;let T=h+m.length>y&&y<i.length;if(!T)for(;h<i.length&&i.charCodeAt(h)===i.charCodeAt(h-p);)h++;if(o.charge((h-S)*Se.scan),T){n.periodicEnd=h;continue}n.periodicEnd=-1,n.last+=Math.floor((h-n.last-l.length)/p)*p,n.from=n.last+l.length-p+1;continue}if(n.from<0){if(n.runStart<0)return Kp;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(ot))return Ro;n.from>=n.windowEnd&&(n.windowStart=n.from,n.windowEnd=n.from+r.windowStarts,n.window=i.slice(n.from,n.windowEnd+l.length-1));let d=n.from-n.windowStart,u=n.window.indexOf(l,d);if(u<0){o.charge((n.window.length-d)*Se.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*Se.scan);let R=n.windowStart+u;(n.runStart<0||R>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=R),n.last=R,c===null?n.from=R+1:n.periodicEnd=R+l.length}};function*So(e,t,r){let n=Math.floor(ot/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*Xp(e,t,r,n,o){if(t.length===0)return;let a=yield*So(Ji(e),Se.strip,n),i=[],l=[];yield*So(Qi(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),Se.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(Se.line)||(yield),n.charge(Se.line);let d=i[c],u=a.text.slice(d,l[c]),R=yield*So(Xi(u,r),Se.plan,n),p=[],m="";for(let y of R.chunks){let h="",T=[];for(let D of y){let f=(D.end-D.start)*Se.normalize;n.fits(f)||(yield);let b=no(D.start===0&&D.end===u.length?u:u.slice(D.start,D.end),r).text;n.charge(f),b.length>0&&T.push({start:D.start,end:D.end,text:b,chunkStart:h.length}),h+=b}if(h.length!==0){m.length>0&&(m+=" ");for(let D of T)p.push({start:D.start,end:D.end,text:D.text,plainStart:m.length+D.chunkStart,mapped:null});m+=h}}if(m.length===0)continue;let S={offset:d,plain:m,pieces:p,isCut:!qp(R,u),lastPiece:0,clusters:void 0};for(let y of t){let h=Gp();for(;;){let T=Qp(S,s,y,h,n,o);if(T.kind==="done")break;if(T.kind==="slice"){yield;continue}if(T.kind==="clusters"){S.clusters=yield*Yp(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:D}=T,f=(D.end-D.start)*Se.map;n.fits(f)||(yield);let b=u.slice(D.start,D.end);D.mapped=Vp(Gi(b,ro(b,r)),D.text),n.charge(f)}}}}function*Zp(e,t,r,n){let o=new Int32Array(Xr.length),a=0,i=fo;for(let l=0;l<=e;l+=Gs){let s=Math.min(e+1,l+Gs),c=(s-l)*Se.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=fo;for(let R=Xr.length-1;R>=0;R--){let p=Xr[R];o[p]+=t[p][d],o[p]>0&&(u=p)}if(u!==i){if(i!==fo&&!n(a,d,i))return!1;a=d,i=u}}r.charge(c)}return!0}function*em(e,t,r,n,o){let a=null;return yield*Xp(e,t,r,n,(l,s,c)=>{a===null&&(a=Xr.map(()=>new Int32Array(e.length+1))),a[c][l]++,a[c][s]--}),a===null?!0:yield*Zp(e.length,a,n,o)}var tm=(e,t,r,n)=>{let o=zp(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return Zs(function*(){return(yield*em(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var rl=(e,t)=>{if(e.combine==="intersection"||e.sets.length===1)return e.sets.flatMap(r=>r.words);if(t===null)throw new Error(`[daily-report] search marks: a union of ${e.sets.length} keywords needs the report's mask of matched keywords`);return e.sets.flatMap((r,n)=>(t&1<<n)===0?[]:r.words)},nl=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of oa)r(it.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(it.interviewer(o,"name"),n.name),r(it.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(it.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(it.comment(wn(o),"author"),n.name),r(it.comment(wn(o),"content"),n.text)});for(let n of e.postedComments)r(it.comment(n.id,"author"),n.userName),r(it.comment(n.id,"content"),n.content);return t};function*rm(e,t){let r=xn;for(let n=0;n<e.length;n+=Zr){let o=Math.min(e.length,n+Zr),a=(o-n)*Se.linear;t.fits(a)||(yield),r=Cn(r,e,n,o),t.charge(a)}return r}var ol=async(e,t,r,n)=>{let o=0,a=0,i=async c=>{for(;!c.step();)await r(),n.startSlice();return c.result()},l=async(c,d)=>{if(!d&&a>t.maxRanges)return null;let u={};for(let{key:R,value:p}of c.fields){if(!d&&o+p.length>t.maxUnits)return null;let m=await i(Zs(rm(p,n))),S=await i(tm(p,c.alternatives,{maxLength:Zn,maxRanges:t.maxFieldRanges},n));if(o+=p.length,S.dense){u[R]={fingerprint:m,dense:!0};continue}if(u[R]={fingerprint:m,ranges:S.ranges},a+=S.ranges.length/3,!d&&a>t.maxRanges)return null}return u},s=[];for(let c=0;c<e.length;c++){let d=e[c],u=await l(d,s.length===0);if(u===null)return{reports:s,deferred:e.slice(c).map(R=>R.reportHubId)};s.push({reportHubId:d.reportHubId,matchedSets:d.matchedSets,fields:u})}return{reports:s,deferred:[]}};var ve=require("drizzle-orm");var Ne=require("drizzle-orm");var yt=e=>(0,Ne.getColumns)(e),Te=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},al=e=>{let{db:t,tables:r,encodeUserId:n,settings:o,draftVisibilityTables:a}=e,{hub:i,label:l}=r,{externalSources:s,draftLabelNames:c,canonicalDraftLabelName:d}=o,u=N=>dr(i.sourceType,N),R=(N,H)=>Qr(a,N,c,H),p=Ne.sql`CASE WHEN ${Jr(a,c)} THEN 1 ELSE 0 END`,m=async N=>{let[H]=await t.select({id:i.id}).top(1).from(i).where((0,Ne.and)((0,Ne.eq)(i.id,N),Jr(a,c)));return H!==void 0},S=N=>N==null||N===""?null:/^\d+$/.test(N)?n(Number(N)):N,y=()=>{let N={};for(let H of s)N[`ext_${H.sourceType}`]=yt(H.table);return N},h=N=>{let H=N;for(let k of s)H=H.leftJoin(k.table,(0,Ne.and)((0,Ne.eq)(i.sourceType,k.sourceType),(0,Ne.eq)(i.sourceIdNum,k.idColumn)));return H},T=N=>{let{hub:H,internal:k}=N,K=H.summary,G=[],O=null,E=null,F=null,te=null,J=null,ue=null,he=[],le=s.find(P=>P.sourceType===H.sourceType),fe=le?N[`ext_${le.sourceType}`]:void 0;if(le&&fe){let P=le.mapRow(fe);P.content!==void 0&&(K=P.content),P.employeeName!==void 0&&(ue=P.employeeName),P.category!==void 0&&(O=P.category),P.creationCategory!==void 0&&(E=P.creationCategory),P.visitTimeFrom!==void 0&&(F=P.visitTimeFrom),P.visitTimeTo!==void 0&&(te=P.visitTimeTo),P.customerName!==void 0&&(J=P.customerName),P.interviewers!==void 0&&(G=P.interviewers),P.externalComments!==void 0&&(he=P.externalComments)}else H.sourceType===Ve&&k&&(K=k.body);return{content:K,author:N.creatorName??S(H.createdBy)??"",employeeName:ue??N.creatorName??S(H.createdBy),updatedBy:S(H.updatedBy),category:O,creationCategory:E,visitTimeFrom:F,visitTimeTo:te,customerName:J,interviewers:G,externalComments:he}},D=N=>{if(N===1)return!0;if(N===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${Et(N)}`)},f=N=>N.creationCategory!==null&&c.includes(N.creationCategory),b=(N,H)=>D(N.hasDraftLabel)?!0:f(H),M=async N=>{let[H]=await N.select({id:l.id}).top(1).from(l).where((0,Ne.eq)(l.name,d)).orderBy((0,Ne.asc)(l.id));return H===void 0?null:H.id},C=()=>M(t);return{visibleSourceTypeCondition:u,draftVisibleTo:R,draftLabelFlag:p,isDraftReport:m,externalSelections:y,applyExternalJoins:h,resolveHubDisplayFields:T,readCanonicalDraftLabelId:M,getDraftLabelId:C,resolveCreationCategoryDraftLabelId:N=>N.some(f)?C():Promise.resolve(null),mapHubRecord:(N,H,k,K,G)=>{let{hub:O}=H,E=H.labels.map(J=>({id:J.id,name:J.name,color:J.color})),F=H.postedCommentRows,te=Ie(N.commentable,O.sourceType);return K!==null&&f(k)&&!E.some(J=>J.id===K)&&E.push({id:K,name:d,color:null}),{reportHubId:O.id,date:Te(O.businessDate,"YYYY-MM-DD"),author:k.author,userId:O.userId?n(O.userId):"",sourceType:O.sourceType,createdAt:Te(O.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:Te(O.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:k.updatedBy,employeeName:k.employeeName,category:k.category,creationCategory:k.creationCategory,visitTimeFrom:k.visitTimeFrom,visitTimeTo:k.visitTimeTo,customerName:k.customerName,interviewers:k.interviewers,subject:O.title,content:k.content,externalComments:te?k.externalComments:[],isRead:H.isRead??!1,isStarred:H.isStarred??!1,isDraft:b(H,k),labels:E,postedComments:F.filter(J=>Fi({authorUserId:J.userId},O.sourceType,G,N)).map(J=>({...J,userId:n(J.userId),isMine:G?J.userId===G:!1})),attachments:H.attachments}}}};var il=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r})=>{let{db:n,tables:o,logger:a,settings:i}=e,{hub:l}=o,{attachmentDelivery:s}=i,c=(m,S)=>S!=null?"absent":m!=null?"present":"unknown";return{getAttachmentsByHubIds:async m=>{let S=new Map,y=o.attachment;if(m.length===0||!y||s===null)return S;let h=s.idCodec,T=s.thumbnails!==null,D=await n.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where((0,ve.inArray)(y.hubId,m)).orderBy((0,ve.asc)(y.createdAt),(0,ve.asc)(y.id));for(let f of D){let b=f.fileType?String(f.fileType):null,M=f.fileSize!=null?Number(f.fileSize):null,C=c(f.objectCheckedAt,f.objectMissingAt),_={id:h.encode(Number(f.id)),fileName:String(f.fileName),fileType:b,fileSize:M,createdAt:Te(f.createdAt,"YYYY-MM-DD HH:mm:ss"),state:C,hasThumbnail:T&&C!=="absent"&&vr({fileType:b,fileSize:M},s.maxBytes)},$=S.get(Number(f.hubId));$?$.push(_):S.set(Number(f.hubId),[_])}return S},getAttachmentForUser:async(m,S,y)=>{let h=o.attachment;return!h||ke(m.visible)?null:(await n.select({fileName:h.fileName,filePath:h.filePath,fileType:h.fileType,fileSize:h.fileSize}).top(1).from(h).innerJoin(l,(0,ve.eq)(l.id,h.hubId)).where((0,ve.and)((0,ve.eq)(h.id,S),(0,ve.isNull)(l.deletedAt),t(y,"author"),r(m.visible))))[0]??null},markAttachmentMissing:async m=>{let S=o.attachment;if(!S)return;let y=new Date;try{await n.update(S).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where((0,ve.eq)(S.id,m))}catch(h){a.error("markAttachmentMissing failed",h)}},markAttachmentPresent:async m=>{let S=o.attachment;if(!S)return;let y=new Date;try{await n.update(S).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where((0,ve.eq)(S.id,m))}catch(h){a.error("markAttachmentPresent failed",h)}}}};var tn=require("drizzle-orm");var vt=require("drizzle-orm"),Gt=async(e,t,r,n)=>{if((await e.update(t).set({deletedAt:null}).output().where((0,vt.and)((0,vt.eq)(t.id,r),(0,vt.isNull)(t.deletedAt),n===null?void 0:(0,vt.eq)(t.userId,n)))).length===0)throw new Error("Not Found")};var bt="daily-report:ids:epoch",Ue="daily-report:date-epoch:",at="daily-report:detail-epoch:",sl=({redis:e,logger:t,epochs:r,streamKey:n,streamMaxLen:o})=>({incrementRedisEpoch:s=>r.incrementEpoch(s),publishToSseStream:async(s,c)=>{let d=await e?.getClient();if(!d){t.warn(`[SSE] Redis client unavailable (${c})`);return}let u=JSON.stringify(s),R=Buffer.byteLength(u);if(R>6356992){t.warn(`[SSE] Event too large (${c}): ${R} bytes > ${6356992}; not published`);return}let p=ie();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let m=ie()-p;m>1e3&&t.warn(`[SSE] Slow publish (${c}): ${m}ms`)}catch(m){t.error(`[SSE] Redis publish failed (${c}):`,m)}},readSseStreamAnchor:async()=>{try{let s=await e?.getClient();if(s===void 0)return null;let[c]=await s.xRevRange(n,"+","-",{COUNT:1});return c===void 0?null:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});var ll=(e,{isDraftReport:t,assertHubMutable:r,incrementRedisEpoch:n})=>{let{db:o,tables:a,users:i,encodeUserId:l,cache:s,inTransaction:c,prepareSearchIndex:d,publishToSseStream:u}=e,{hub:R,comment:p}=a,m=async(T,D)=>{if(D!==null)return await t(T)?D:void 0},S=async(T,D,f,b,M,C)=>{let _=await r(T,f,D);if(!Ie(T.commentable,_.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(_.sourceType.toLowerCase()!==Ve.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let $=await m(f,_.userId),N=await d(),H=await c(async O=>{await Gt(O,R,f,null);let[E]=await O.insert(p).output().values({hubId:f,userId:D,body:b,createdAt:new Date,createdBy:String(D),updatedAt:new Date,updatedBy:String(D)});return N!==null&&await N.writeHubs(O,[f]),E}),[k]=await o.select({displayName:i.displayName}).top(1).from(i).where((0,tn.eq)(i.id,D)),K=k?.displayName??"";if(M){let O=He(M);O&&(s.invalidatePrefix(jt(O)),await n(`${Ue}${O}`))}s.invalidatePrefix(Ye(f)),await n(`${at}${f}`);let G={id:H.id,userId:l(H.userId),userName:K,content:H.body,createdAt:Te(H.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(Sn.parse({type:"comment-add",reportHubId:f,comment:G,clientTempId:C,recipientRawUserId:$,sourceType:_.sourceType}),"addComment"),G},y=async(T,D)=>await T.select().top(1).from(p).where((0,tn.eq)(p.id,D));return{addComment:S,deleteComment:async(T,D,f,b,M,C)=>{let _=await y(o,b);if(_.length===0)throw new Error("Not Found");if(_[0].hubId!==f)throw new Error("Not Found");let $=await r(T,_[0].hubId,D);if(_[0].userId!==D)throw new Error("Unauthorized");let N=await m(f,$.userId),H=await d();if(await c(async k=>{await Gt(k,R,f,null),await k.delete(p).where((0,tn.eq)(p.id,b)),H!==null&&await H.writeHubs(k,[f])}),M){let k=He(M);k&&(s.invalidatePrefix(jt(k)),await n(`${Ue}${k}`))}s.invalidatePrefix(Ye(f)),await n(`${at}${f}`),await u(gn.parse({type:"comment-delete",reportHubId:f,commentId:b,clientTempId:C,recipientRawUserId:N,sourceType:$.sourceType}),"deleteComment")}}};var Oe=require("drizzle-orm");var cl=e=>e===""?null:e,ul=(e,{readCanonicalDraftLabelId:t,isDraftReport:r,getDailyReportDetailById:n,assertHubMutable:o,incrementRedisEpoch:a})=>{let{db:i,tables:l,users:s,encodeUserId:c,cache:d,logger:u,inTransaction:R,prepareSearchIndex:p,publishToSseStream:m,settings:S,draftVisibilityTables:y}=e,{hub:h,internal:T,hubLabel:D,userStatus:f}=l,{canonicalDraftLabelName:b,draftLabelNames:M}=S,C=async(O,E,F,te)=>{if(!Ar(F))throw Q("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",F);if(!Ie(O.visible,Ve))throw new Error("Forbidden");u.info("createDailyReport called",{userId:E,businessDate:F});let[J]=await i.select({displayName:s.displayName}).from(s).where((0,Oe.eq)(s.id,E)),ue=J?.displayName??c(E),he=await p();try{let le=await R(async g=>{u.info("Starting transaction");let I=await t(g);if(I===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(b)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let w=`internal-temp-${Date.now()}-${Math.random()}`,[x]=await g.insert(h).output().values({sourceType:Ve,sourceId:w,businessDate:new Date(`${F}T00:00:00Z`),userId:E,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(E),updatedAt:new Date,updatedBy:String(E)});await g.update(h).set({sourceId:String(x.id)}).where((0,Oe.eq)(h.id,x.id)),u.info("Hub created",x),await g.insert(T).values({hubId:x.id,body:"",createdAt:new Date,createdBy:String(E),updatedAt:new Date,updatedBy:String(E)}),u.info("Internal created"),await g.insert(D).values({hubId:x.id,labelId:I,createdAt:new Date,createdBy:String(E)});let v=[{id:I,name:b,color:null}];return u.info("Label assigned"),await g.insert(f).values({hubId:x.id,userId:E,isRead:!0,isStarred:!1,createdAt:new Date,createdBy:String(E),updatedAt:new Date,updatedBy:String(E)}),he!==null&&await he.writeHubs(g,[x.id]),{reportHubId:x.id,date:F,createdAt:Te(x.createdAt,"YYYY-MM-DD HH:mm:ss"),author:ue,userId:c(E),sourceType:Ve,employeeName:ue,updatedBy:c(E),updatedAt:Te(x.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:x.title,content:"",externalComments:[],isRead:!0,isStarred:!1,isDraft:!0,labels:v,postedComments:[],attachments:[]}});d.invalidatePrefix(Wt(F,E)),d.invalidatePrefix(so(E)),await a(bt),await a(`${Ue}${F}`);let fe=await n(qe.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),le.reportHubId,E,{forceRefresh:!0});if(fe){let g=await r(fe.reportHubId);await m(bn.parse({type:"report-create",reportHubId:fe.reportHubId,report:fe,clientTempId:te,recipientRawUserId:g?E:void 0}),"createDailyReport")}return(fe===null?null:await n(O,le.reportHubId,E,{forceRefresh:!0}))??le}catch(le){throw u.error("Error in createDailyReport",le),le}},_=async(O,E)=>await O.select().top(1).from(h).where((0,Oe.eq)(h.id,E)),$=async(O,E,F)=>{await o(O,E,F);let[te]=await _(i,E);if(te===void 0||te.deletedAt)throw new Error("Not Found");if(te.userId!==F)throw new Error("Unauthorized");return te},N=async(O,E,F)=>{await O.update(h).set(F).where((0,Oe.eq)(h.id,E))},H=async(O,E,F)=>{await O.update(T).set(F).where((0,Oe.eq)(T.hubId,E))};return{createDailyReport:C,updateDailyReport:async(O,E,F,te,J)=>{let ue=await $(O,E,F),he=await p();await R(async P=>{await Gt(P,h,E,F),te.title!==void 0&&await N(P,E,{title:cl(te.title),updatedAt:new Date,updatedBy:String(F)}),te.content!==void 0&&await H(P,E,{body:cl(te.content),updatedAt:new Date,updatedBy:String(F)}),he!==null&&await he.writeHubs(P,[E])}),d.invalidatePrefix(Ye(E)),await a(`${at}${E}`);let le=He(Te(ue.businessDate,"YYYY-MM-DD"));le&&(d.invalidatePrefix(jt(le)),await a(`${Ue}${le}`));let fe=await n(qe.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),E,F,{forceRefresh:!0});if(fe){let P=await r(E);await m(Dn.parse({type:"report-update",reportHubId:fe.reportHubId,report:fe,clientTempId:J,recipientRawUserId:P?F:void 0}),"updateDailyReport")}},publishDailyReport:async(O,E,F,te)=>{let J=await $(O,E,F),ue=await p();if(await R(async P=>{await Gt(P,h,E,F),await P.delete(D).where((0,Oe.and)((0,Oe.eq)(D.hubId,E),Ns(y,M))),ue!==null&&await ue.writeHubs(P,[E])}),d.invalidatePrefix(Ye(E)),d.invalidatePrefix(Rt),await a(bt),J.businessDate){let P=He(Te(J.businessDate,"YYYY-MM-DD"));P&&await a(`${Ue}${P}`)}let he=He(Te(J.businessDate,"YYYY-MM-DD"));he&&d.invalidatePrefix(Wt(he,F));let le=await n(qe.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),E,F,{forceRefresh:!0});if(le===null)return null;let fe=await r(E);return await m(An.parse({type:"report-publish",reportHubId:le.reportHubId,report:le,clientTempId:te,recipientRawUserId:fe?F:void 0}),"publishDailyReport"),await n(O,E,F,{forceRefresh:!0})},deleteDailyReport:async(O,E,F,te)=>{let J=await $(O,E,F);if(await R(async ue=>{if((await ue.update(h).set({deletedAt:new Date,deletedBy:String(F),updatedAt:new Date,updatedBy:String(F)}).output().where((0,Oe.and)((0,Oe.eq)(h.id,E),(0,Oe.eq)(h.userId,F),(0,Oe.isNull)(h.deletedAt)))).length===0)throw new Error("Not Found")}),d.invalidatePrefix(Ye(E)),d.invalidatePrefix(Rt),await a(bt),J.businessDate){let ue=He(Te(J.businessDate,"YYYY-MM-DD"));ue&&await a(`${Ue}${ue}`)}await m(Tn.parse({type:"report-delete",reportHubId:E,clientTempId:te,sourceType:J.sourceType}),"deleteDailyReport")}}};var W=require("drizzle-orm");var dl=Er([]),pl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r,draftLabelFlag:n,externalSelections:o,applyExternalJoins:a,resolveHubDisplayFields:i,resolveCreationCategoryDraftLabelId:l,mapHubRecord:s,getAttachmentsByHubIds:c,readSseStreamAnchor:d,incrementRedisEpoch:u})=>{let{db:R,tables:p,users:m,resolveUserId:S,cache:y,epochs:h,logger:T,settings:D}=e,{hub:f,internal:b,comment:M,label:C,hubLabel:_,userStatus:$}=p,N=D.idsTtlMs,H=D.businessDateTtlMs,k=async(P,g)=>(await R.select({reportHubId:f.id,businessDate:f.businessDate,sourceType:f.sourceType}).from(f).where((0,W.and)((0,W.isNull)(f.deletedAt),t(g,"author-or-authorless"),r(P.visible))).orderBy((0,W.desc)(f.businessDate),(0,W.desc)(f.id))).map(w=>({...w,businessDate:Te(w.businessDate,"YYYY-MM-DD")})),K=async(P,g,I)=>{let w=await O(g);return w?ke(P.visible)?[]:(await R.select({reportHubId:f.id,businessDate:f.businessDate,sourceType:f.sourceType}).top(I).from(f).where((0,W.and)((0,W.isNull)(f.deletedAt),t(w,"author-or-authorless"),r(P.visible))).orderBy((0,W.desc)(f.businessDate),(0,W.desc)(f.id))).map(v=>({...v,businessDate:Te(v.businessDate,"YYYY-MM-DD")})):[]},G=new Map,O=async P=>{if(!D.disableUserIdCache&&G.has(P))return G.get(P)??null;let g=await S(P);return g!==null&&!D.disableUserIdCache&&G.set(P,g),g},E=async(P,g,{forceRefresh:I=!1,snapshot:w=!1,ttlMsOverride:x,onFetchStart:v,admission:V}={})=>{let j=await O(g);if(!j)return{items:[],streamAnchor:null,snapshot:dl};if(ke(P.visible))return{items:[],streamAnchor:await d(),snapshot:dl};let U=ss(j,Br(P)),[z]=await y.getOrFetch({cacheKey:U,fetcher:async()=>{let L=await d(),X=await k(P,j);if(!ea(X)){T.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let Y=[...X].sort(En);return[{items:Y,streamAnchor:L,snapshot:Er(Y)}]}return[{items:X,streamAnchor:L,snapshot:Er(X)}]},onFetchStart:v,forceRefresh:I,snapshot:w,admission:V,ttlMsOverride:x??N,epochKey:bt,refreshAheadRatio:.5});if(z===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return z},F=async(P,g,I)=>{let w=await a(R.select({hub:yt(f),internal:yt(b),isRead:$.isRead,isStarred:$.isStarred,creatorName:m.displayName,hasDraftLabel:n,...o()}).from(f)).leftJoin(b,(0,W.eq)(f.id,b.hubId)).leftJoin($,(0,W.and)((0,W.eq)(f.id,$.hubId),(0,W.eq)($.userId,g))).leftJoin(m,(0,W.eq)(f.userId,m.id)).where((0,W.and)(I,(0,W.isNull)(f.deletedAt),t(g,"author"),r(P.visible))).orderBy((0,W.desc)(f.id));if(w.length===0)return[];let x=w.map(Y=>Y.hub.id),v=await R.select({hubId:_.hubId,id:C.id,name:C.name,color:C.color}).from(_).innerJoin(C,(0,W.eq)(_.labelId,C.id)).where((0,W.inArray)(_.hubId,x)),V=await R.select({hubId:M.hubId,id:M.id,body:M.body,createdAt:M.createdAt,userId:M.userId,userName:m.displayName}).from(M).leftJoin(m,(0,W.eq)(M.userId,m.id)).where((0,W.inArray)(M.hubId,x)).orderBy((0,W.asc)(M.createdAt)),j=await c(x),U=new Map,z=new Map;for(let Y of v){let Z=U.get(Y.hubId);Z||(Z=[],U.set(Y.hubId,Z)),Z.push({id:Y.id,name:Y.name,color:Y.color})}for(let Y of V){let Z=z.get(Y.hubId);Z||(Z=[],z.set(Y.hubId,Z)),Z.push({id:Y.id,content:Y.body,createdAt:Te(Y.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Y.userId,userName:Y.userName||""})}let L=w.map(i),X=await l(L);return w.map((Y,Z)=>{let Dt=Y.hub.id;return s(P,{...Y,attachments:j.get(Dt)??[],labels:U.get(Dt)||[],postedCommentRows:z.get(Dt)||[]},L[Z],X,g)})},te=async(P,g,I,{forceRefresh:w=!1,snapshot:x=!1,ttlMsOverride:v,admission:V}={})=>{let j=await O(I);if(!j)return[];let U=He(g);if(!U)return[];if(ke(P.visible))return[];let z=ls(U,j,Br(P));return y.getOrFetch({cacheKey:z,fetcher:()=>F(P,j,(0,W.eq)(f.businessDate,W.sql`${U}`)),forceRefresh:w,snapshot:x,admission:V,ttlMsOverride:v??H,epochKey:`${Ue}${U}`})},J=async(P,g,I,{forceRefresh:w=!1,snapshot:x=!1,ttlMsOverride:v,admission:V}={})=>{if(ke(P.visible))return null;let j=cs(g,I,Br(P));return(await y.getOrFetch({cacheKey:j,fetcher:async()=>{let z=await a(R.select({hub:yt(f),internal:yt(b),isRead:$.isRead,isStarred:$.isStarred,creatorName:m.displayName,hasDraftLabel:n,...o()}).from(f)).leftJoin(b,(0,W.eq)(f.id,b.hubId)).leftJoin($,(0,W.and)((0,W.eq)(f.id,$.hubId),(0,W.eq)($.userId,I))).leftJoin(m,(0,W.eq)(f.userId,m.id)).where((0,W.and)((0,W.eq)(f.id,g),(0,W.isNull)(f.deletedAt),t(I,"author"),r(P.visible)));if(z.length===0)return[];let L=z[0].hub.id,X=await R.select({id:C.id,name:C.name,color:C.color}).from(_).innerJoin(C,(0,W.eq)(_.labelId,C.id)).where((0,W.eq)(_.hubId,L)),Y=await R.select({id:M.id,body:M.body,createdAt:M.createdAt,userId:M.userId,userName:m.displayName}).from(M).leftJoin(m,(0,W.eq)(M.userId,m.id)).where((0,W.eq)(M.hubId,L)).orderBy((0,W.asc)(M.createdAt)),Z=await c([L]),Dt=X.map(je=>({id:je.id,name:je.name,color:je.color})),sn=Y.map(je=>({id:je.id,content:je.body,createdAt:Te(je.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:je.userId,userName:je.userName||""})),Jt=i(z[0]),ln=await l([Jt]);return[s(P,{...z[0],attachments:Z.get(L)??[],labels:Dt,postedCommentRows:sn},Jt,ln,I)]},forceRefresh:w,snapshot:x,admission:V,ttlMsOverride:v??H,epochKey:`${at}${g}`}))[0]??null};return{getUserIdByExternalId:O,getDailyReportIdsByExternalId:E,getDailyReportIdsFirstPageByExternalId:K,getDailyReportsByBusinessDateByExternalId:te,getDailyReportDetailById:J,getDailyReportDetailByIdByExternalId:async(P,g,I,w={})=>{let x=await O(I);return x?J(P,g,x,w):null},getDailyReportDetailsByIdsByExternalId:async(P,g,I)=>{if(g.length>xe.maxDetailIds)throw Q("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${xe.maxDetailIds} ids`,g.length);let w=await O(I);return!w||g.length===0?[]:ke(P.visible)?[]:F(P,w,(0,W.inArray)(f.id,[...g]))},fetchVisibleHubDetails:F,invalidateHubReadCaches:async(P,g)=>{y.invalidatePrefix(Rt),await u(bt);for(let I of new Set(P))y.invalidatePrefix(Ye(I)),await u(`${at}${I}`);for(let I of new Set(g)){let w=He(I);w&&await u(`${Ue}${w}`)}},clearCache:async()=>{y.clearAll(),G.clear(),h&&await u(bt),T.info("Server-side DB/SQL caches cleared successfully.")}}};var rn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,streamKey:"daily-report:sse-stream",streamMaxLen:1e4}),om=e=>{let{length:t}=e;if(t===void 0)throw Q("tables.hub.title","a character column with a declared length",t);return ae("tables.hub.title.length",t,1)},am=e=>{if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0)||new Set(e).size!==e.length)throw Q("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},im=e=>{let t=new Map([[Ve.toLowerCase(),`the internal source type ${JSON.stringify(Ve)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw Q(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([Ve,...e.map(r=>r.sourceType)])},ml=e=>{let t=e.externalSources??[],r=am(e.draftLabelNames);Hr(e);let n=Si(e.attachments),o=om(e.tables.hub.title);Qn(e.tables.hub.sourceType);let a=Me("idsTtlMs",e.idsTtlMs,1,rn.idsTtlMs),i=Me("businessDateTtlMs",e.businessDateTtlMs,1,rn.businessDateTtlMs),l=Me("streamMaxLen",e.streamMaxLen,1,rn.streamMaxLen);return Object.freeze({externalSources:t,sourceTypes:im(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamKey:e.streamKey??rn.streamKey,streamMaxLen:l,disableUserIdCache:!!e.disableUserIdCache})};var pe=require("drizzle-orm");var nn=["hubId","userId","isRead","isStarred","createdAt","createdBy","updatedAt","updatedBy"],sm={isRead:{statusType:"read",callerName:"setReadStatus"},isStarred:{statusType:"star",callerName:"setStarStatus"}},$e=e=>pe.sql`${pe.sql.identifier(e.name)}`,lm=(e,t,{reportHubId:r,userId:n,value:o,at:a})=>{let i=String(n),l=$e(e[t]),s=(p,m)=>pe.sql`t.${$e(p)} = CASE WHEN t.${l} = ${o} THEN t.${$e(p)} ELSE ${m} END`,c={hubId:pe.sql`s.${$e(e.hubId)}`,userId:pe.sql`s.${$e(e.userId)}`,isRead:pe.sql`${t==="isRead"?o:!1}`,isStarred:pe.sql`${t==="isStarred"?o:!1}`,createdAt:pe.sql`${a}`,createdBy:pe.sql`${i}`,updatedAt:pe.sql`${a}`,updatedBy:pe.sql`${i}`},d=pe.sql.join(nn.map(p=>$e(e[p])),pe.sql`, `),u=pe.sql.join(nn.map(p=>c[p]),pe.sql`, `),R=pe.sql.join(nn.map(p=>pe.sql`inserted.${$e(e[p])} AS ${pe.sql.identifier(p)}`),pe.sql`, `);return pe.sql`MERGE ${e} WITH (HOLDLOCK) AS t USING (SELECT ${r} AS ${$e(e.hubId)}, ${n} AS ${$e(e.userId)}) AS s ON t.${$e(e.hubId)} = s.${$e(e.hubId)} AND t.${$e(e.userId)} = s.${$e(e.userId)}
|
|
12
|
+
WHEN MATCHED THEN UPDATE SET t.${l} = ${o}, ${s(e.updatedAt,a)}, ${s(e.updatedBy,i)}
|
|
13
|
+
WHEN NOT MATCHED THEN INSERT (${d}) VALUES (${u})
|
|
14
|
+
OUTPUT ${R};`},yl=(e,t)=>(typeof e=="number"||typeof e=="string")&&String(e)===String(t),hl=e=>e instanceof Date||typeof e=="string",cm=e=>{if(!Array.isArray(e))return`recordset ${Et(e)}`;if(e.length!==1)return`${e.length} rows`;let[t]=e;return typeof t!="object"||t===null?`a row of ${Et(t)}`:nn.map(r=>`${r}=${Et(t[r])}`).join(", ")},um=(e,{reportHubId:t,userId:r})=>{let n=typeof e=="object"&&e!==null?e.recordset:void 0,o=Array.isArray(n)&&n.length===1?n[0]:void 0,a=typeof o=="object"&&o!==null?o:void 0;if(a===void 0||!yl(a.hubId,t)||!yl(a.userId,r)||typeof a.isRead!="boolean"||typeof a.isStarred!="boolean"||!hl(a.createdAt)||!hl(a.updatedAt)||typeof a.createdBy!="string"||typeof a.updatedBy!="string")throw new Error(`[daily-report] user status: the upsert must output the one status row of report ${t} and user ${r}; got ${cm(n)}`);return{hubId:t,userId:r,isRead:a.isRead,isStarred:a.isStarred,createdAt:a.createdAt,createdBy:a.createdBy,updatedAt:a.updatedAt,updatedBy:a.updatedBy}},fl=(e,{draftVisibleTo:t,incrementRedisEpoch:r})=>{let{db:n,tables:o,cache:a,publishToSseStream:i}=e,{hub:l,userStatus:s}=o,c=async(m,S)=>{let[y]=await n.select({sourceType:l.sourceType,userId:l.userId,deletedAt:l.deletedAt}).top(1).from(l).where((0,pe.and)((0,pe.eq)(l.id,m),t(S,"author")));return y??null},d=async(m,S,y)=>{let h=await c(S,y);if(!h||h.deletedAt||!Ie(m.visible,h.sourceType))throw new Error("Not Found");return{sourceType:h.sourceType,userId:h.userId}},u=async(m,S,y,h,T,D,f)=>{await d(S,h,y);let b={reportHubId:h,userId:y,value:D,at:new Date},M=um(await n.execute(lm(s,m,b)),b);if(T){let $=He(T);$&&(a.invalidatePrefix(Wt($,y)),await r(`${Ue}${$}`))}a.invalidatePrefix(lo(h,y)),await r(`${at}${h}`);let{statusType:C,callerName:_}=sm[m];return await i(fn.parse({type:"status-update",reportHubId:h,recipientRawUserId:y,statusType:C,value:D,clientTempId:f}),_),M};return{assertHubMutable:d,setStarStatus:(m,S,y,h,T,D)=>u("isStarred",m,S,y,h,T,D),setReadStatus:(m,S,y,h,T,D)=>u("isRead",m,S,y,h,T,D)}};var dm="v3",Do=e=>`${e}:${dm}`,pm=Object.freeze([]),bo=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},on=(e,t)=>e.get(t)??pm,Rl=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(qr),mm=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw Qe(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw Q(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw Qe(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw Q(`${e}: options.signal`,r,n);return n};function an(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:s}=e,{hub:c,internal:d,comment:u,label:R,hubLabel:p}=r,m=ml(e),{externalSources:S,draftLabelNames:y,attachmentDelivery:h,titleMaxLength:T}=m,D=De(e.logger,1,"Service"),f=re=>(0,Kt.runWithTransactionRetry)(de=>t.transaction(ee=>de(()=>re(ee))),e.transactionRetry),b=e.search===void 0?null:Ls(e.search,S.map(re=>re.sourceType)),M={hub:c,hubLabel:p,label:R},C=b===null?null:Ys({tables:{...M,search:b.tables},draftLabelNames:y});b!==null&&ao();let _=null,$=async()=>{if(b===null)return null;if(_===null){let re=await ao(),de=b.externalSourceTexts;_=zs({hub:c,tables:b.tables,loadSources:(ee,ne)=>Wl(ee,ne,de),inTransaction:f,normalizerVersion:re})}return _},N=Do(m.streamKey),{incrementRedisEpoch:H,publishToSseStream:k,readSseStreamAnchor:K}=sl({redis:i,logger:D,epochs:s,streamKey:N,streamMaxLen:m.streamMaxLen}),G={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:D,settings:m,draftVisibilityTables:M,inTransaction:f,publishToSseStream:k,prepareSearchIndex:$},{visibleSourceTypeCondition:O,draftVisibleTo:E,draftLabelFlag:F,isDraftReport:te,externalSelections:J,applyExternalJoins:ue,resolveHubDisplayFields:he,readCanonicalDraftLabelId:le,getDraftLabelId:fe,resolveCreationCategoryDraftLabelId:P,mapHubRecord:g}=al(G),{getAttachmentsByHubIds:I,getAttachmentForUser:w,markAttachmentMissing:x,markAttachmentPresent:v}=il(G,{draftVisibleTo:E,visibleSourceTypeCondition:O}),{getUserIdByExternalId:V,getDailyReportIdsByExternalId:j,getDailyReportIdsFirstPageByExternalId:U,getDailyReportsByBusinessDateByExternalId:z,getDailyReportDetailById:L,getDailyReportDetailByIdByExternalId:X,getDailyReportDetailsByIdsByExternalId:Y,fetchVisibleHubDetails:Z,invalidateHubReadCaches:Dt,clearCache:sn}=pl(G,{draftVisibleTo:E,visibleSourceTypeCondition:O,draftLabelFlag:F,externalSelections:J,applyExternalJoins:ue,resolveHubDisplayFields:he,resolveCreationCategoryDraftLabelId:P,mapHubRecord:g,getAttachmentsByHubIds:I,readSseStreamAnchor:K,incrementRedisEpoch:H}),{assertHubMutable:Jt,setStarStatus:ln,setReadStatus:je}=fl(G,{draftVisibleTo:E,incrementRedisEpoch:H}),{addComment:Hl,deleteComment:Fl}=ll(G,{isDraftReport:te,assertHubMutable:Jt,incrementRedisEpoch:H}),{createDailyReport:Ul,updateDailyReport:$l,publishDailyReport:Bl,deleteDailyReport:Vl}=ul(G,{readCanonicalDraftLabelId:le,isDraftReport:te,getDailyReportDetailById:L,assertHubMutable:Jt,incrementRedisEpoch:H}),ql=async(re,de)=>{let ee=new Map,ne=r.attachment;if(!ne||h===null)return ee;let Ee=await re.select({hubId:ne.hubId,fileName:ne.fileName}).from(ne).where((0,ge.inArray)(ne.hubId,[...de])).orderBy((0,ge.asc)(ne.hubId),(0,ge.asc)(ne.createdAt),(0,ge.asc)(ne.id));for(let oe of Ee)bo(ee,Number(oe.hubId),String(oe.fileName));return ee},Yl=async(re,de,ee)=>{let ne=new Map;for(let[Ee,oe]of ee){let Je=new Map;for(let{hub:Pe}of de)Pe.sourceType===Ee&&Pe.sourceIdNum!==null&&Je.set(Pe.sourceIdNum,Pe.id);if(Je.size===0)continue;let At=await oe(re,[...Je.keys()]);for(let[Pe,ht]of At){let Qt=Je.get(Pe);if(Qt===void 0)throw Q(`search.externalSourceTexts.${Ee} answer key`,"a source id that was asked for",Pe);if(!(Array.isArray(ht)&&ht.every(Ot=>typeof Ot=="string")))throw Q(`search.externalSourceTexts.${Ee} answer for ${Pe}`,"an array of strings",ht);ne.set(Qt,ht)}}return ne},jl=(re,de)=>{let ee=he(re),ne=[["subject",re.hub.title],["content",ee.content],["author",ee.author],["employeeName",ee.employeeName],["updatedBy",ee.updatedBy],["category",ee.category],["creationCategory",ee.creationCategory],["customerName",ee.customerName]];for(let oe of ee.interviewers)ne.push(["interviewerName",oe.name??null],["interviewerAffiliation",oe.affiliation??null]);for(let oe of de.labelNames)ne.push(["label",oe]);for(let oe of de.attachmentNames)ne.push(["attachment",oe]);for(let oe of de.extraTexts)ne.push(["extra",oe]);let Ee=[];for(let oe of ee.externalComments)Ee.push({authorUserId:null,text:Rl(oe.name,oe.text)});for(let oe of de.postedComments)Ee.push({authorUserId:oe.userId,text:Rl(oe.userName,oe.body)});return{hubId:re.hub.id,fields:ne,comments:Ee,filterValues:{authorName:ee.employeeName,customerName:ee.customerName}}},Wl=async(re,de,ee)=>{let ne=[];for(let Ee of(0,Kt.chunk)(de,Kt.MAX_IN_LIST)){let oe=await ue(re.select({hub:yt(c),internal:yt(d),creatorName:n.displayName,...J()}).from(c)).leftJoin(d,(0,ge.eq)(c.id,d.hubId)).leftJoin(n,(0,ge.eq)(c.userId,n.id)).where((0,ge.inArray)(c.id,[...Ee])).orderBy((0,ge.asc)(c.id)),Je=new Map,At=await re.select({hubId:p.hubId,name:R.name}).from(p).innerJoin(R,(0,ge.eq)(p.labelId,R.id)).where((0,ge.inArray)(p.hubId,[...Ee])).orderBy((0,ge.asc)(p.hubId),(0,ge.asc)(R.id));for(let _e of At)bo(Je,_e.hubId,_e.name);let Pe=new Map,ht=await re.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,(0,ge.eq)(u.userId,n.id)).where((0,ge.inArray)(u.hubId,[...Ee])).orderBy((0,ge.asc)(u.hubId),(0,ge.asc)(u.createdAt),(0,ge.asc)(u.id));for(let _e of ht)bo(Pe,_e.hubId,_e);let Qt=await ql(re,Ee),Ot=await Yl(re,oe,ee);for(let _e of oe){let Tt=_e.hub.id;ne.push(jl(_e,{labelNames:on(Je,Tt),postedComments:on(Pe,Tt),attachmentNames:on(Qt,Tt),extraTexts:on(Ot,Tt)}))}}return ne},zl=(re,de,ee)=>C===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):C.search(t,{criteria:ee,viewerUserId:de,scope:re}),wo=m.sourceTypes,Gl=async(re,de)=>{if(C===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let ee=wo.filter(oe=>Ie(re.visible,oe)),ne=await C.facetValues(t,{column:"authorName",viewerUserId:de,scope:re}),Ee=await C.facetValues(t,{column:"customerName",viewerUserId:de,scope:re});return{sourceTypes:ee,authors:ne,customers:Ee}},Kl=async(re,de,ee,ne,Ee)=>{let oe=mm("markDailyReportSearchHits",Ee);if(C===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(ne.length>xe.maxDetailIds)throw Q("markDailyReportSearchHits: reportHubIds",`at most ${xe.maxDetailIds} ids`,ne.length);let Je=wr(pr(ee));if(ne.length===0||ke(re.visible))return{wordsDigest:Je,reports:[],deferred:[]};oe.throwIfAborted();let At=await Z(re,de,(0,ge.inArray)(c.id,[...ne]));oe.throwIfAborted();let Pe=ee.combine==="union"&&ee.sets.length>=2&&At.length>0?await C.matchedSets(t,{plan:ee,viewerUserId:de,scope:re,ids:At.map(_e=>_e.reportHubId)}):null,ht=At.map(_e=>{let Tt=Pe===null?null:Pe.get(_e.reportHubId),Io=Tt===void 0?0:Tt;return{reportHubId:_e.reportHubId,matchedSets:Io,alternatives:rl(ee,Io).flatMap(Ql=>Ql.alternatives),fields:nl(_e)}}),Ot=await ol(ht,go,async()=>{await new Promise(_e=>setImmediate(_e)),oe.throwIfAborted()},Xs(go,ie));return{wordsDigest:Je,reports:Ot.reports,deferred:Ot.deferred}},Jl=async re=>{let de=await $();if(de===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return de.reconcile(t,re)};return{streamKey:N,attachmentDelivery:h,titleMaxLength:T,searchLimits:b===null?null:{concurrency:b.concurrency,rateLimitPerMinute:b.rateLimitPerMinute},searchFilterSourceTypes:wo,clearCache:sn,invalidateHubReadCaches:Dt,getUserIdByExternalId:V,getDailyReportIdsByExternalId:j,getDailyReportIdsFirstPageByExternalId:U,readSseStreamAnchor:K,getDailyReportsByBusinessDateByExternalId:z,getDailyReportDetailById:L,getDailyReportDetailByIdByExternalId:X,getDailyReportDetailsByIdsByExternalId:Y,getDraftLabelId:fe,searchDailyReports:zl,markDailyReportSearchHits:Kl,listDailyReportSearchFacets:Gl,reconcileSearchIndex:Jl,getAttachmentsByHubIds:I,getAttachmentForUser:w,markAttachmentMissing:x,markAttachmentPresent:v,setStarStatus:ln,setReadStatus:je,addComment:Hl,deleteComment:Fl,createDailyReport:Ul,updateDailyReport:$l,publishDailyReport:Bl,deleteDailyReport:Vl}}var Sl=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(De(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return De(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};var gr=require("drizzle-orm"),A=require("drizzle-orm/mssql-core");function gl(e,t){let r=(0,A.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,A.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,A.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,A.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(gr.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,A.date)("business_date"),userId:(0,A.bigint)("user_id",{mode:"number"}),title:(0,A.nvarchar)("title",{length:200}),summary:(0,A.nvarchar)("summary",{length:"max"}),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,A.datetime2)("deleted_at"),deletedBy:(0,A.nvarchar)("deleted_by",{length:50})},u=>[(0,A.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,A.index)(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),(0,A.index)(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),(0,A.index)(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),(0,A.index)(`${e}_DailyReportHub_user_id_index`).on(u.userId),(0,A.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,gr.desc)(u.businessDate),(0,gr.desc)(u.id)),(0,A.index)(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,A.nvarchar)("body",{length:"max"}),metadata:(0,A.nvarchar)("metadata",{length:"max"}),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),(0,A.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}).notNull(),body:(0,A.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,A.index)(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}),name:(0,A.nvarchar)("name",{length:50}).notNull(),color:(0,A.nvarchar)("color",{length:20}),sortOrder:(0,A.int)("sort_order"),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,A.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,A.bit)("is_read").default(!1).notNull(),isStarred:(0,A.bit)("is_starred").default(!1).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),(0,A.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,A.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,A.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,A.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,A.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,A.nvarchar)("file_type",{length:100}),fileSize:(0,A.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,A.datetime2)("object_checked_at"),objectMissingAt:(0,A.datetime2)("object_missing_at"),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),(0,A.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),(0,A.index)(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:d,label:l,hubLabel:s,userStatus:c}}var ye=require("drizzle-orm/mssql-core");function bl(e){let t=(0,ye.mssqlSchema)(e),r=t.table("DailyReportSearchDocument",{hubId:(0,ye.bigint)("hub_id",{mode:"number"}).notNull(),searchText:(0,ye.nvarchar)("search_text",{length:"max"}).notNull(),sourceDigest:(0,ye.binary)("source_digest",{length:32}).notNull(),normalizerVersion:(0,ye.varchar)("normalizer_version",{length:64}).notNull(),indexedAt:(0,ye.datetime2)("indexed_at").notNull(),rowVersion:(0,ye.binary)("row_version",{length:8}).notNull(),authorName:(0,ye.nvarchar)("author_name",{length:st.maxValueLength}),customerName:(0,ye.nvarchar)("customer_name",{length:st.maxValueLength})},o=>[(0,ye.primaryKey)({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:(0,ye.bigint)("hub_id",{mode:"number"}).notNull(),ordinal:(0,ye.int)("ordinal").notNull(),authorUserId:(0,ye.bigint)("author_user_id",{mode:"number"}),commentText:(0,ye.nvarchar)("comment_text",{length:"max"}).notNull()},o=>[(0,ye.primaryKey)({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var ym=5e7,Ao=2e8,hm=1,To=Object.freeze({fixedBytes:4*1024*1024,pipelineRows:2048,wholeImageBuffer:Object.freeze({"jpeg-single-scan":Object.freeze({kind:"none"}),"jpeg-multi-scan":Object.freeze({kind:"jpeg-coefficients"}),png:Object.freeze({kind:"none"}),"png-interlaced":Object.freeze({kind:"decoded-raster"}),gif:Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-lossy":Object.freeze({kind:"none"}),"webp-lossy-alpha":Object.freeze({kind:"canvas",bytesPerPixel:5}),"webp-lossless":Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-animated":Object.freeze({kind:"canvas",bytesPerPixel:9})})}),Dl=125,Al=4,Tl=16,El=50,wl=2,br=Object.freeze({renderMs:Fe.renderMs,nanosecondsPerBlockVisit:Dl,margin:Al,maxBlockVisits:Math.floor(Fe.renderMs*1e6/(Dl*Al)),walkBudgetMs:Tl,nanosecondsPerWalkStep:El,walkMargin:wl,maxWalkSteps:Math.floor(Tl*1e6/(El*wl))}),fm=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Il=75,_l=4,xl="#ffffff",Rm=1,Sm={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},gm=[/out of memory/i,/insufficient memory/i,/memory allocation|allocation failed/i,/(?:cannot|could not|unable to|failed to) allocate/i,/picture memory error/i,/unable to create thread|error creating thread|resource temporarily unavailable/i,/too many open files|no space left on device/i,/\b(?:ENOMEM|EAGAIN|EMFILE|ENFILE|ENOSPC)\b/],Cl=Object.freeze({ok:!1,reason:"failed"}),Ml=Object.freeze({ok:!1,reason:"unsupported"}),Pl=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Za(e)}),Ll=(e,t)=>{switch(t){case"jpeg":{let r=zn(e);return r===null?null:Pl(r)}case"png":{let r=ri(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=ni(e,br.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},kl=(e,t)=>{let r=fm.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=To,a=o.wholeImageBuffer[e.layout];return(a.kind==="none"?0:a.kind==="decoded-raster"?t.width*t.height*n:a.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*a.bytesPerPixel)+o.pipelineRows*t.width*n+o.fixedBytes},Nl=(e,t,r)=>{let n=Ll(e,t);return n===null?null:kl(n,r)},bm=e=>e!==null&&e<=Ao,Dm=(e,t)=>{if(t!=="jpeg")return Ll(e,t);let r=ei(e,br);return r===null||r.blockVisits>br.maxBlockVisits?null:Pl(r.header)},Am=e=>{let t=e instanceof Error?e.message:"";return gm.some(r=>r.test(t))?"failed":"unsupported"},vl=e=>{e.cache(!1),e.concurrency(hm),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Sm)});let t=async(n,o,a,i,l)=>{let s=Dm(n,o);if(s===null)return Ml;try{let c=e(n,{limitInputPixels:ym,animated:!1});if(!bm(kl(s,await c.metadata())))return Ml;if(l.aborted)return Cl;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:xl}).webp({quality:Il,effort:_l}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:Am(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?Cl:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Il}-e${_l}/flatten-${xl}/v${Rm}`,render:r}};var Eo=6e4,Ol=e=>{let t=ae("ttlMs",e.ttlMs,1,Eo),r=Zt("readViewerKey",e.readViewerKey),n=Zt("resolve",e.resolve),o=new Map;return async(a,i)=>{let l=await r(a,i);if(l===null)throw new Error(`[daily-report] createDailyReportVisibilityCache: the request names no viewer for the ${JSON.stringify(i.reason)} resolution (readViewerKey answered null), so no source type may be shown`);let s=ie(),c=o.get(l);if(i.reason==="initial"&&c!==void 0&&s<c.expiresAt)return c.answer;let d=Promise.resolve().then(()=>n(a,i));for(let[R,p]of o)p.expiresAt<=s&&o.delete(R);o.set(l,{expiresAt:s+t,answer:d});let u=()=>{o.get(l)?.answer===d&&o.delete(l)};return d.catch(u),d}};function Tm(e){e.redis||De(e.logger,2,"Server").warn("redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=Dr(e.redis),r=new Ht({defaultTtlMs:e.cacheDefaultTtlMs,maxBuckets:e.cacheMaxBuckets,maxBytes:e.cacheMaxBytes},t),n=an({...e,cache:r,epochs:t}),o=new zt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Kr({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:n.searchFilterSourceTypes,...a}}0&&(module.exports={DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,DAILY_REPORT_SSE_CATCH_UP_BATCH,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,buildDailyReportSseStreamKey,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createDailyReportVisibilityCache,createEpochStore,createSharpThumbnailRenderer,defineDailyReportSchema,defineDailyReportSearchSchema,encodeIdsStreamRows,isStreamIdLte,parseClientTempId,predictSharpThumbnailWorkingSetBytes,readDailyReportSseStreamEntry,transformJsonArray});
|
|
12
15
|
/* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */
|