@probnaya/057-cli 1.2.3 → 1.3.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.
@@ -1,14 +1,18 @@
1
- import{existsSync as fe,createReadStream as dm,statSync as Qi,mkdirSync as Dc,chmodSync as ea,writeFileSync as El,renameSync as Il,rmSync as fm,readFileSync as Cl}from"node:fs";import{createInterface as Yv}from"node:readline";import{createServer as pm}from"node:http";import{join as se,isAbsolute as Pc,relative as cc,sep as Lc,dirname as ii,resolve as yo,normalize as Xv,extname as Jv}from"node:path";import{fileURLToPath as Zv}from"node:url";import{stat as zr,readdir as Ge,readFile as Nr}from"node:fs/promises";import{hostname as Qv,homedir as hn}from"node:os";import eb from"node:zlib";import{createHash as Qn,webcrypto as tb,randomBytes as Dn,X509Certificate as js,timingSafeEqual as rb,verify as nb,createPublicKey as sb}from"node:crypto";import{execFileSync as ob,execFile as ib}from"node:child_process";import{DatabaseSync as go}from"node:sqlite";import{isMainThread as hm,workerData as ai,parentPort as Bn,Worker as mm}from"node:worker_threads";import{promisify as ab}from"node:util";import{createServer as cb}from"node:https";const Yd=["machine","session","execution","process","artifact"];function ub(t){return`${t.ns}|${t.parts.join("|")}`}const z={interactions:"interactions",steps:"steps",errors:"errors",retries:"retries",cpuMs:"cpu.ms",tokensInput:"tokens.input",tokensOutput:"tokens.output",tokensCacheRead:"tokens.cacheRead",tokensReasoning:"tokens.reasoning"},lb=[{a:"execution",b:"process",kind:"ran-as"},{a:"session",b:"process",kind:"ran-as"},{a:"execution",b:"session",kind:"ran-as"},{a:"session",b:"session",kind:"same-as"},{a:"execution",b:"execution",kind:"same-as"},{a:"machine",b:"machine",kind:"same-as"},{a:"process",b:"process",kind:"same-as"}];function Xd(t,e){for(const r of lb){if(t.subjectType===r.a&&e.subjectType===r.b)return{kind:r.kind,from:t,to:e};if(e.subjectType===r.a&&t.subjectType===r.b)return{kind:r.kind,from:e,to:t}}return null}const db=(t,e)=>t.validFrom<=e.validTo&&e.validFrom<=t.validTo;function fb(t,e){const r=Math.max(t.validFrom,e.validFrom),n=Math.min(t.validTo,e.validTo);if(n<r)return 0;const s=Math.max(t.validTo,e.validTo)-Math.min(t.validFrom,e.validFrom);return s<=0?1:(n-r)/s}const pb=.5;function hb(t,e){return db(t,e)?fb(t,e)>=pb?2:1:0}const xt=t=>`${t.subjectType}:${t.subjectId}`,mb="inferred",yb="Two observers asserted the same identity claim over overlapping validity windows, and each was the other's only candidate at the strongest available evidence tier (two lifetimes that substantially coincide beat a bare overlap). The claims themselves are measured; the identification is inferred.";function gb(t){const e=new Map;for(const o of t){const i=e.get(o.key);i?i.push(o):e.set(o.key,[o])}const r=[],n=[];let s=0;for(const[o,i]of[...e.entries()].sort(([a],[c])=>a<c?-1:1)){const a=new Map;for(const p of i){const y=xt(p),v=a.get(y);if(!v){a.set(y,{...p});continue}v.validFrom=Math.min(v.validFrom,p.validFrom),v.validTo=Math.max(v.validTo,p.validTo)}const c=[...a.values()].sort((p,y)=>xt(p)<xt(y)?-1:1);if(c.length<2){s++;continue}const u=[];let l=!1;for(let p=0;p<c.length;p++)for(let y=p+1;y<c.length;y++){const v=c[p],g=c[y];if(v.sourceId===g.sourceId)continue;const C=hb(v,g);if(C!==0){if(!Xd(v,g)){l=!0;continue}u.push({x:v,y:g,tier:C})}}const d=new Map;for(const p of u)for(const y of[p.x,p.y]){const v=xt(y);d.set(v,Math.max(d.get(v)??0,p.tier))}const m=new Map;for(const p of u)for(const y of[p.x,p.y]){const v=xt(y);d.get(v)===p.tier&&m.set(v,(m.get(v)??0)+1)}if(u.length===0){n.push({key:o,reason:l?"no-pairing-defined":"no-window-overlap",subjects:[...a.keys()].sort()});continue}for(const{x:p,y,tier:v}of u){if(d.get(xt(p))!==v||d.get(xt(y))!==v)continue;if(m.get(xt(p))!==1||m.get(xt(y))!==1){n.push({key:o,reason:"multiple-candidates",subjects:[xt(p),xt(y)].sort()});continue}const g=Xd(p,y);r.push({from:{type:g.from.subjectType,id:g.from.subjectId},to:{type:g.to.subjectType,id:g.to.subjectId},kind:g.kind,basis:mb,assumption:yb,via:o})}}return{relationships:r,ambiguous:n,unmatched:s,considered:e.size}}async function vb(t,e,r,n,s){const o=[];let i=0,a=0;for(const c of e){const u=Date.now();try{const l=await c.collect(r,n),d=t.append(l);i+=d.inserted,a+=d.duplicate,o.push({id:c.id,ok:!0,collected:l.length,inserted:d.inserted,duplicate:d.duplicate,ms:Date.now()-u})}catch(l){o.push({id:c.id,ok:!1,collected:0,inserted:0,duplicate:0,error:l instanceof Error?l.message:String(l),ms:Date.now()-u})}s?.(o[o.length-1])}return{sources:o,inserted:i,duplicate:a}}const ym=1e3,Jd=60*ym;function We(t){if(!Number.isFinite(t)||t<=0)return"0m";if(t<Jd)return`${Math.max(1,Math.round(t/ym))}s`;const e=Math.round(t/Jd),r=Math.floor(e/60),n=e%60;return r===0?`${n}m`:n===0?`${r}h`:`${r}h ${n}m`}function Qe(t){if(!Number.isFinite(t))return"—";const e=Math.abs(t);return e>=1e9?`${(t/1e9).toFixed(e>=1e10?0:2)}B`:e>=1e6?`${(t/1e6).toFixed(e>=1e7?0:2)}M`:e>=1e3?`${(t/1e3).toFixed(e>=1e4?0:1)}k`:String(Math.round(t))}function bb(t,e="NOT OBSERVED"){return t===void 0?e:Qe(t)}function wb(t){return t===void 0||!Number.isFinite(t)?"—":t>=1e9?`${(t/1e9).toFixed(1)} GB`:t>=1e6?`${(t/1e6).toFixed(0)} MB`:t>=1e3?`${(t/1e3).toFixed(0)} KB`:`${t} B`}function Po(t){const e=new Date(t);return`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}function Ce(t){const e=t.split("/").filter(Boolean);return e[e.length-1]??t}const Ol="deepseek-harness",Ab={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"supported",waits:"supported",model:"supported",context:"supported",outcome:"supported"},Oe=t=>typeof t=="number"&&Number.isFinite(t)?t:0,ot=t=>typeof t=="string"?t:void 0;function Sb(t){const e=t.split("/").filter(Boolean);return(e[e.length-1]??t).toUpperCase()}function kb(t,e){const r=[],n=t[0];if(!n||n.type!=="session"||!n.id)return r;const s=n.id,o=n.cwd??"",i=Oe(n.createdAt),a=Oe(n.delegationDepth),c=Sb(o);let u="deepseek",l,d;for(const k of t)if(k.type==="request/context"&&k.data?(u=ot(k.data.provider)??u,l=ot(k.data.model)??l):k.type==="session/title"&&k.data&&(d=ot(k.data.title)??d),l&&d)break;const p={source:{id:Ol,instance:e.instance},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"};let y=i;for(const k of t){const T=Oe(k.time);T>y&&(y=T)}const v={ns:"fs.cwd",parts:[e.host,o],validFrom:i,validTo:Math.max(i,y)};r.push({...p,occurredAt:i,seq:"session",kind:"began",subject:{type:"session",id:s},claims:o?[v]:void 0,core:{machineId:e.machine.id,label:d,projectLabel:o?Ce(o):void 0,taskLabel:d,executor:u,model:l,depth:a},attrs:{context:o,"dsh.delegationDepth":a}});const g=k=>`${s}:turn:${k}`;let C=null;const A=new Map,I=new Map;let B=i;for(const k of t){const T=Oe(k.time)||B;if(T<i)continue;B=T;const S=k.data??{},E=k.seq??`t${T}`,R=j=>({type:"execution",id:g(j)});switch(k.type){case"turn/start":{const j=Oe(S.turn);C=j,r.push({...p,occurredAt:T,seq:E,kind:"began",subject:R(j),core:{machineId:e.machine.id,sessionId:s,label:d?`${c} · ${d}`:c,executor:u,model:l,depth:a},attrs:{"dsh.turn":j}});break}case"turn/end":{const j=Oe(S.turn),M=S.reason,J=M?.kind;if(J==="error"){const le=M?.error??{};r.push({...p,occurredAt:T,seq:E,kind:"ended",subject:R(j),core:{outcome:"error",failureCode:ot(le.code)??"ERROR",failureMessage:ot(le.message)??"Run failed"},attrs:{"dsh.endReason":J}})}else r.push({...p,occurredAt:T,seq:E,kind:"ended",subject:R(j),core:{outcome:J==="aborted"?"interrupted":"completed"},attrs:{"dsh.endReason":J??"completed"}});C===j&&(C=null);break}case"assistant/message":{const j=Oe(S.turn),M=S.usage;if(!M)break;const J={[z.tokensInput]:Oe(M.inputTokens),[z.tokensOutput]:Oe(M.outputTokens),[z.tokensCacheRead]:Oe(M.cacheReadTokens),[z.tokensReasoning]:Oe(M.reasoningTokens),[z.steps]:1};r.push({...p,occurredAt:T,seq:E,kind:"progressed",subject:R(j),core:{measures:J},attrs:{"dsh.inputTokens":Oe(M.inputTokens),"dsh.outputTokens":Oe(M.outputTokens),"dsh.cacheReadTokens":Oe(M.cacheReadTokens),"dsh.reasoningTokens":Oe(M.reasoningTokens)}});break}case"tool/call":{r.push({...p,occurredAt:T,seq:E,kind:"progressed",subject:R(Oe(S.turn)),core:{measures:{[z.interactions]:1}},attrs:{"dsh.tool":ot(S.name)}});break}case"tool/result":{const j=S.message;let M=!1;for(const J of j?.content??[])J.isError===!0&&(M=!0);M&&r.push({...p,occurredAt:T,seq:E,kind:"progressed",subject:R(Oe(S.turn)),core:{measures:{[z.errors]:1}}});break}case"llm/retry":{r.push({...p,occurredAt:T,seq:E,kind:"progressed",subject:R(Oe(S.turn)),core:{measures:{[z.retries]:1}}});break}case"approval/asked":{const j=ot(S.id);if(C===null)break;j&&A.set(j,C),r.push({...p,occurredAt:T,seq:E,kind:"blocked",subject:R(C),core:{blockedOn:"approval"},attrs:{"dsh.approvalId":j}});break}case"approval/decided":{const j=ot(S.id),M=j?A.get(j):C;if(M==null)break;A.delete(j??""),r.push({...p,occurredAt:T,seq:E,kind:"resumed",subject:R(M),attrs:{"dsh.approvalId":j}});break}case"tool-workflow/agent-start":{if(C===null)break;const j=ot(S.childId);if(!j)break;const M=`${s}:agent:${j}`;I.set(`${ot(S.runId)}:${Oe(S.seq)}`,M),r.push({...p,occurredAt:T,seq:E,kind:"began",subject:{type:"execution",id:M},core:{machineId:e.machine.id,sessionId:s,label:ot(S.label)??`${c} · SUB`,executor:u,model:l,parentId:g(C),depth:a+1},attrs:{"dsh.childId":j}});break}case"tool-workflow/agent-end":{const j=`${ot(S.runId)}:${Oe(S.seq)}`,M=I.get(j);if(!M)break;I.delete(j);const J=ot(S.outcome);r.push({...p,occurredAt:T,seq:E,kind:"ended",subject:{type:"execution",id:M},core:J==="completed"?{outcome:"completed"}:{outcome:"error",failureCode:"SUBAGENT",failureMessage:J??"Sub-agent did not complete"},attrs:{"dsh.subagentOutcome":J}});break}}}if(e.closeOpenTurns){const k="The session log has not been written to for longer than the live window, so the process that owned it is gone and any turn left open was cut off rather than still running.";C!==null&&r.push({...p,occurredAt:B,seq:"close:turn",kind:"ended",subject:{type:"execution",id:g(C)},core:{outcome:"interrupted"},basis:"inferred",assumption:k});for(const T of I.values())r.push({...p,occurredAt:B,seq:`close:${T}`,kind:"ended",subject:{type:"execution",id:T},core:{outcome:"interrupted"},basis:"inferred",assumption:k});r.push({...p,occurredAt:B,seq:"close:session",kind:"ended",subject:{type:"session",id:s},basis:"inferred",assumption:k})}return e.since!==void 0?r.filter(k=>k.occurredAt>=e.since):r}function xb(t){const e=[];let r=0;for(;r<t.length;){let n=t.indexOf(`
2
- `,r);n===-1&&(n=t.length);const s=t.slice(r,n);if(r=n+1,s.length!==0&&!(s.startsWith('{"type":"reasoning-chunks"')||s.startsWith('{"type":"text-chunks"')||s.startsWith('{"type":"tool-call-chunks"')||s.startsWith('{"type":"assistant/chunk"')))try{e.push(JSON.parse(s))}catch{}}return e}function Eb(t){const e=JSON.stringify([t.source.id,t.source.instance,t.occurredAt,t.clock,t.kind,t.subject.type,t.subject.id,t.basis,t.seq??null,ci(t.core),ci(t.attrs)]);return Qn("sha256").update(e).digest("hex").slice(0,32)}function ci(t){if(t==null)return null;if(Array.isArray(t))return t.map(ci);if(typeof t!="object")return t;const e={};for(const r of Object.keys(t).sort())e[r]=ci(t[r]);return e}function Wt(t){const{seq:e,...r}=t;return{id:Eb(t),...r}}let Zd;function Ib(){try{const t=ob("/usr/sbin/scutil",["--get","LocalHostName"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim();return/^[A-Za-z0-9-]{1,63}$/.test(t)?t:void 0}catch{return}}function gm(){return Zd??=Ib()??Qv().replace(/\.local$/i,""),Zd}const ui="host:";function Cb(t){return`${ui}${t}`}function Ob(t){return t.startsWith(ui)?t.slice(ui.length):void 0}function Qd(t){return t.startsWith(ui)}const Nb=4247762216,Tb=407710288,Bb=407710303;function $b(t){const e=[];for(let s=0;s+4<=t.length;s++){const o=t.readUInt32LE(s);(o===Nb||o>=Tb&&o<=Bb)&&e.push(s)}if(e.length===0)return Buffer.alloc(0);const r=[];let n=0;for(;n<e.length;){let s=n+1,o=null;for(;;){const i=s<e.length?e[s]:t.length;try{o=eb.zstdDecompressSync(t.subarray(e[n],i));break}catch{if(s>=e.length)break;s++}}o?(r.push(o),n=s):n++}return Buffer.concat(r)}function Nl(){return process.env.DSH_HOME||se(hn(),".dsh")}function Rr(){return gm()}function _r(){const t=Rr();return{id:Cb(t),name:t.toUpperCase(),kind:"laptop",firstSeenAt:0}}const ef=new Map;async function vm(){const t=se(Nl(),"sessions");if(!fe(t))return[];const e=[];for(const r of await Ge(t)){const n=se(t,r);let s;try{s=await Ge(n)}catch{continue}for(const o of s){const i=se(n,o,"session.jsonl.zstd");fe(i)&&e.push({path:i,workspace:r,sessionId:o})}}return e}const Tl=10*6e4;async function Rb(t,e){const r=await zr(t.path),n=ef.get(t.path);if(n&&n.mtimeMs===r.mtimeMs&&n.size===r.size)return n.envelopes;const s=await Nr(t.path),o=$b(s).toString("utf8"),i=xb(o),a=Date.now()-r.mtimeMs>Tl,u=kb(i,{machine:e,host:Rr(),instance:Nl(),observedAt:Date.now(),closeOpenTurns:a}).map(Wt);return ef.set(t.path,{mtimeMs:r.mtimeMs,size:r.size,envelopes:u}),u}async function _b(t,e){const r=_r(),n=await vm(),s=[];for(const o of n){let i;try{i=await zr(o.path)}catch{continue}if(!(i.mtimeMs<t))for(const a of await Rb(o,r))a.occurredAt>=t&&a.occurredAt<=e&&s.push(a)}return s}async function tf(){const t=await vm(),e=Nl();return{available:t.length>0,present:fe(e),home:e,sessions:t.length}}const li="0x2f",Mb={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"supported",model:"partial",context:"supported",outcome:"supported"},er=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0},bm=(t,e)=>`2f:${t}#${e}`,jb=(t,e,r)=>`${bm(t,e)}:run:${r}`;function rf(t){return t?.type==="permission"?"approval":"input"}function Db(t){const e=new Map;for(const r of t){const n=typeof r.run=="number"?r.run:1,s=e.get(n);s?s.push(r):e.set(n,[r])}return e}function Pb(t,e){const r=e.find(o=>o.type==="run.started");let n;for(let o=e.length-1;o>=0;o--){const i=e[o];if(i.type==="run.completed"||i.type==="run.failed"||i.type==="needs_user"&&i.blockedOn){n=i;break}}let s;return n?.type==="run.completed"?s="ready":n?.type==="run.failed"?s="failed":n?s="needs_you":t.status==="needs_you"||t.status==="ready"||t.status==="failed"?s=t.status:t.status==="working"?s="working":s=t.error?"failed":"ready",{run:1,provider:t.execution?.provider??null,node:t.execution?.node??null,model:t.execution?.model,externalSessionId:t.execution?.externalSessionId,attempts:t.execution?.attempts??1,startedAt:r?.at,completedAt:n?.at,outcome:s,error:t.error??(n?.type==="run.failed"?n.error:void 0),blockedOn:n?.type==="needs_user"?n.blockedOn:void 0,failure:t.failure}}function Lb(t,e){return Array.isArray(t.runs)&&t.runs.length?t.runs:[Pb(t,e)]}function Ub(t,e,r){if(typeof t.id!="number")return[];const n=bm(r.base,t.id),s=Lb(t,e),o=Ce(r.base).toUpperCase(),i=t.title,a=t.execution?.provider??s.at(-1)?.provider??li,c=er(t.createdAt)??s.map(g=>er(g.startedAt)).find(g=>g!==void 0);if(c===void 0)return[];const l={source:{id:li,instance:r.base},observedAt:r.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},d=[{...l,occurredAt:c,kind:"began",subject:{type:"session",id:n},core:{machineId:r.machine.id,label:i,projectLabel:Ce(r.base),taskLabel:i,executor:a,model:t.execution?.model},attrs:{context:r.base,"0x2f.taskId":t.id,"0x2f.status":t.status}}],m=Db(e),p=e.filter(g=>g.type==="task.answered"),y=e.find(g=>g.type==="task.closed"),v=s.at(-1);for(let g=0;g<s.length;g++){const C=s[g],A=er(C.startedAt);if(A===void 0)continue;const I=jb(r.base,t.id,C.run),B=C.provider??a,k=er(C.completedAt),T=k??r.now,S=[{ns:"fs.cwd",parts:[r.host,r.base],validFrom:A,validTo:T}];typeof C.externalSessionId=="string"&&C.externalSessionId&&S.push({ns:"agent.session",parts:[B,C.externalSessionId],validFrom:A,validTo:T}),C===v&&typeof t.pid=="number"&&S.push({ns:"os.process",parts:[r.host,t.pid],validFrom:A,validTo:T}),d.push({...l,occurredAt:A,seq:`run:${C.run}`,kind:"began",subject:{type:"execution",id:I},claims:S,core:{machineId:r.machine.id,sessionId:n,label:i?`${o} · ${i} · RUN ${C.run}`:`${o} · RUN ${C.run}`,executor:B,model:C.model??t.execution?.model,depth:0},attrs:{"0x2f.run":C.run,"0x2f.provider":B,"0x2f.workspace":r.base,...C.requestedProvider?{"0x2f.requestedProvider":C.requestedProvider}:{},...t.pid!==void 0&&C===v?{"0x2f.workerPid":t.pid}:{}}});let E=!1,R=0;for(const M of m.get(C.run)??[]){R++;const J=er(M.at);if(J===void 0||J<A)continue;const le=`run:${C.run}:${R}`;if(M.type==="tool.started")d.push({...l,occurredAt:J,seq:le,kind:"progressed",subject:{type:"execution",id:I},core:{measures:{[z.interactions]:1}},attrs:{"0x2f.tool":M.name}});else if(M.type==="progress")d.push({...l,occurredAt:J,seq:le,kind:"progressed",subject:{type:"execution",id:I}});else if(M.type==="needs_user"&&M.blockedOn){if(E)continue;E=!0,d.push({...l,occurredAt:J,seq:le,kind:"blocked",subject:{type:"execution",id:I},core:{blockedOn:rf(M.blockedOn)},attrs:{"0x2f.blockedOn":M.blockedOn.type}})}else if(M.type==="permission.resolved"||M.type==="task.updated"&&typeof M.grant=="string"){if(!E)continue;E=!1,d.push({...l,occurredAt:J,seq:le,kind:"resumed",subject:{type:"execution",id:I},attrs:{"0x2f.grant":M.grant}})}}const j=(M,J,le)=>d.push({...l,occurredAt:M,seq:le,kind:"ended",subject:{type:"execution",id:I},core:J});if(C.outcome==="ready"&&k!==void 0)j(k,{outcome:"completed"},`run:${C.run}:end`);else if(C.outcome==="failed"&&k!==void 0)j(k,{outcome:"error",failureCode:(C.failure?.kind??t.failure?.kind??"unclassified").toUpperCase(),failureMessage:C.error??t.error??"Run failed"},`run:${C.run}:end`);else if(C.outcome==="needs_you"&&k!==void 0){E||(E=!0,d.push({...l,occurredAt:k,seq:`run:${C.run}:block`,kind:"blocked",subject:{type:"execution",id:I},core:{blockedOn:rf(C.blockedOn)}}));const M=Vb(k,p,s[g+1],y);M!==void 0&&j(M,{outcome:"interrupted"},`run:${C.run}:end`)}}if(y){const g=er(y.at);g!==void 0&&d.push({...l,occurredAt:g,seq:"task:closed",kind:"ended",subject:{type:"session",id:n}})}return d}function Vb(t,e,r,n){const s=[...e.map(i=>er(i.at)),er(r?.startedAt),er(n?.at)];let o;for(const i of s)i===void 0||i<t||(o===void 0||i<o)&&(o=i);return o}function Hb(t){const e=[];for(const r of t.split(`
3
- `))if(r.trim())try{const n=JSON.parse(r);n&&typeof n.type=="string"&&e.push(n)}catch{}return e}const wm=".work";function Am(){const t=process.env.WORK_ROOTS;return t?t.split(/[:,]/).map(e=>e.trim()).filter(Boolean):[hn()]}const nf=t=>fe(se(t,wm,"tasks")),Fb=new Set(["Desktop","Documents","Downloads"]);async function Sm(){const t=new Set,e=!process.env.WORK_ROOTS;for(const r of Am()){if(nf(r)){t.add(r);continue}let n;try{n=await Ge(r,{withFileTypes:!0})}catch{continue}for(const s of n){if(!s.isDirectory()||s.name.startsWith(".")||e&&Fb.has(s.name))continue;const o=se(r,s.name);nf(o)&&t.add(o)}}return[...t].sort()}async function Wb(){const t=[];for(const e of await Sm()){const r=se(e,wm,"tasks");let n;try{n=await Ge(r,{withFileTypes:!0})}catch{continue}for(const s of n){if(!s.isDirectory())continue;const o=se(r,s.name,"task.json");fe(o)&&t.push({base:e,slug:s.name,taskPath:o,eventsPath:se(r,s.name,"events.jsonl")})}}return t}const sf=new Map;async function Kb(t,e,r){let n;try{n=await zr(t.taskPath)}catch{return null}const s=await zr(t.eventsPath).catch(()=>null),o=Math.max(n.mtimeMs,s?.mtimeMs??0),i=`${n.mtimeMs}:${n.size}:${s?.mtimeMs??0}:${s?.size??0}`,a=sf.get(t.taskPath);if(a&&a.stamp===i)return{envelopes:a.envelopes,touchedAt:o};let c;try{c=JSON.parse(await Nr(t.taskPath,"utf8"))}catch{return null}let u=[];try{u=Hb(await Nr(t.eventsPath,"utf8"))}catch{}const l=Ub(c,u,{machine:e,base:t.base,host:Rr(),observedAt:Date.now(),now:r}).map(Wt);return sf.set(t.taskPath,{stamp:i,envelopes:l}),{envelopes:l,touchedAt:o}}async function Gb(t,e){const r=_r(),n=await Wb(),s=[];for(const o of n){const i=await Kb(o,r,e);if(i&&!(i.touchedAt<t))for(const a of i.envelopes)a.occurredAt>=t&&a.occurredAt<=e&&s.push(a)}return s}async function of(){const t=Am(),e=await Sm();return{available:e.length>0,present:t.some(r=>fe(r)),roots:t,workspaces:e}}const Kr="claude-code",qb={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"partial"},km="claude-code";class sr extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="ClaudeFormatError"}path;sourceVersion}const xm=t=>`claude:${t}`;function zb(t,e){const r=t,n=typeof r?.version=="string"?r.version:void 0;if(!r||typeof r!="object")throw new sr("registry entry is not an object",e,n);if(typeof r.sessionId!="string"||!r.sessionId)throw new sr("registry entry has no sessionId",e,n);if(typeof r.pid!="number"||!Number.isFinite(r.pid))throw new sr("registry entry has no numeric pid",e,n);if(typeof r.startedAt!="number"||!Number.isFinite(r.startedAt))throw new sr("registry entry has no numeric startedAt",e,n);return r}function Yb(t,e,r){const n=[{ns:"agent.session",parts:[km,t.sessionId],validFrom:t.startedAt,validTo:r.now},{ns:"os.process",parts:[r.host,t.pid],validFrom:t.startedAt,validTo:r.now}];return{source:{id:Kr,instance:r.host},occurredAt:t.startedAt,observedAt:r.observedAt,clock:"wall",stratum:"identity",kind:"began",subject:{type:"session",id:xm(t.sessionId)},claims:n,basis:"measured",core:{machineId:r.machine.id,label:t.name??Ce(t.cwd??"").toUpperCase(),projectLabel:t.cwd?Ce(t.cwd):void 0,taskLabel:t.name,executor:Kr},attrs:{context:t.cwd,"claude.sessionId":t.sessionId,"claude.pid":t.pid,"claude.procStart":t.procStart,"claude.version":t.version,"claude.kind":t.kind,"claude.entrypoint":t.entrypoint,"claude.status":t.status,"claude.waitingFor":t.waitingFor},provenance:{path:e,recordId:t.sessionId,sourceVersion:t.version},seq:"registry"}}const Xb=new Set(["stop_hook_summary","turn_duration"]),Jb="The transcript has not been written to for longer than the live window, so the process that owned it is gone and the turn ended at its last record.",tr=t=>typeof t=="number"&&Number.isFinite(t)?t:0,wn=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function Zb(t){const e=[];for(const r of t.split(`
4
- `))if(r.trim())try{const n=JSON.parse(r);n&&typeof n=="object"&&e.push(n)}catch{}return e}function Qb(t){if(!t)return{};const e=t.output_tokens_details;return{[z.tokensInput]:tr(t.input_tokens)+tr(t.cache_creation_input_tokens),[z.tokensOutput]:tr(t.output_tokens),[z.tokensCacheRead]:tr(t.cache_read_input_tokens),[z.tokensReasoning]:tr(e?.thinking_tokens),[z.steps]:1}}function e0(t,e){const r=t.filter(A=>wn(A.timestamp)!==void 0);if(r.length===0)throw new sr("transcript has no timestamped records",e.path);const n=t.find(A=>typeof A.sessionId=="string")?.sessionId;if(n&&n!==e.sessionId)throw new sr(`transcript names session ${n} but is filed under ${e.sessionId}`,e.path);const s=t.find(A=>typeof A.version=="string")?.version,o=t.find(A=>typeof A.cwd=="string")?.cwd??"",i=t.find(A=>typeof A.gitBranch=="string")?.gitBranch,a=t.find(A=>typeof A.entrypoint=="string")?.entrypoint,c=Ce(o).toUpperCase(),u=e.sessionId,l=xm(u),d=wn(r[0].timestamp),m=wn(r[r.length-1].timestamp),y={source:{id:Kr,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},v=(A,I)=>({path:e.path,...A?{recordId:A}:{},...I!==void 0?{index:I}:{},...s?{sourceVersion:s}:{}}),g=[{...y,occurredAt:d,kind:"began",subject:{type:"session",id:l},claims:[{ns:"agent.session",parts:[km,u],validFrom:d,validTo:m}],core:{machineId:e.machine.id,label:c,projectLabel:o?Ce(o):void 0,executor:Kr},attrs:{context:o,"claude.sessionId":u,"claude.gitBranch":i,"claude.entrypoint":a,"claude.version":s},provenance:v(u),seq:"session"}],C=[];for(let A=0;A<t.length;A++){const I=t[A];I.type==="user"&&typeof I.promptSource=="string"&&wn(I.timestamp)!==void 0&&C.push(A)}if(C.length===0)throw new sr(`transcript has ${t.length} records but no prompt-bearing user record (expected \`type:"user"\` with \`promptSource\`)`,e.path,s);for(let A=0;A<C.length;A++){const I=C[A],B=A+1<C.length?C[A+1]:t.length,k=A+1,T=`${l}:turn:${k}`,S=wn(t[I].timestamp),E=t.slice(I,B).some(F=>F.isSidechain===!0);let R,j=S,M,J=!1;const le=[];for(let F=I;F<B;F++){const W=t[F],ee=wn(W.timestamp);if(ee===void 0)continue;const he=W.type==="assistant"||W.type==="user"&&Array.isArray(W.message?.content);if(he&&ee>j&&(j=ee),he?(M=W,J=!1):W.type==="system"&&Xb.has(W.subtype??"")&&(J=!0),W.type==="assistant"&&W.message){R??=W.message.model;const Me=(Array.isArray(W.message.content)?W.message.content:[]).filter(pe=>!!pe&&typeof pe=="object"&&pe.type==="tool_use"),Qt={...Qb(W.message.usage)};Me.length&&(Qt[z.interactions]=Me.length),le.push({...y,occurredAt:ee,kind:"progressed",subject:{type:"execution",id:T},core:{measures:Qt},attrs:{...Me.length?{"claude.tools":Me.map(pe=>pe.name??"unknown")}:{},...W.message.model?{"claude.model":W.message.model}:{},...W.requestId?{"claude.requestId":W.requestId}:{},...W.message.stop_reason?{"claude.stopReason":W.message.stop_reason}:{},...W.message.usage?{"claude.usage.inputTokens":tr(W.message.usage.input_tokens),"claude.usage.outputTokens":tr(W.message.usage.output_tokens),"claude.usage.cacheReadTokens":tr(W.message.usage.cache_read_input_tokens),"claude.usage.cacheCreationTokens":tr(W.message.usage.cache_creation_input_tokens),"claude.usage.serviceTier":W.message.usage.service_tier}:{}},provenance:v(W.uuid,F),seq:W.uuid??`a${F}`})}else if(W.type==="user"&&W.message&&Array.isArray(W.message.content)){const $e=W.message.content.filter(Me=>!!Me&&typeof Me=="object"&&Me.is_error===!0).length;$e&&le.push({...y,occurredAt:ee,kind:"progressed",subject:{type:"execution",id:T},core:{measures:{[z.errors]:$e}},provenance:v(W.uuid,F),seq:W.uuid??`e${F}`})}}if(g.push({...y,occurredAt:S,kind:"began",subject:{type:"execution",id:T},core:{machineId:e.machine.id,sessionId:l,label:`${c} · TURN ${k}`,executor:Kr,model:R,depth:E?1:0},attrs:{"claude.turn":k,"claude.promptSource":t[I].promptSource,"claude.promptId":t[I].promptId,...E?{"claude.isSidechain":!0}:{}},provenance:v(t[I].uuid,I),seq:`turn:${k}`}),g.push(...le),A+1<C.length||J)g.push({...y,occurredAt:j,kind:"ended",subject:{type:"execution",id:T},core:{outcome:"completed"},provenance:v(t[I].uuid,I),seq:`turn:${k}:end`});else if(e.closeOpenTurns){const F=M?.type==="assistant"&&(M.message?.stop_reason==="end_turn"||M.message?.stop_reason==="stop_sequence");g.push({...y,occurredAt:j,kind:"ended",subject:{type:"execution",id:T},core:{outcome:F?"completed":"interrupted"},basis:"inferred",assumption:Jb,provenance:v(t[I].uuid,I),seq:`turn:${k}:end`})}}return g}function Bl(){return process.env.CLAUDE_HOME||se(hn(),".claude")}const Uc=()=>se(Bl(),"sessions"),t0=()=>se(Bl(),"projects"),af=new Map;async function r0(t,e,r){const n=Uc();if(!fe(n))return;r.identityAvailable=!0;let s;try{s=await Ge(n)}catch(o){r.problems.push({path:n,message:String(o)});return}for(const o of s){if(!o.endsWith(".json"))continue;const i=se(n,o);try{const a=zb(JSON.parse(await Nr(i,"utf8")),i);r.envelopes.push(Wt(Yb(a,i,{machine:t,host:Rr(),observedAt:e,now:e}))),r.registryEntries++}catch(a){r.problems.push({path:i,message:a instanceof Error?a.message:String(a),sourceVersion:a instanceof sr?a.sourceVersion:void 0})}}}async function Em(){const t=t0();if(!fe(t))return[];const e=[];let r;try{r=await Ge(t)}catch{return e}for(const n of r){let s;try{s=await Ge(se(t,n))}catch{continue}for(const o of s)o.endsWith(".jsonl")&&e.push({path:se(t,n,o),sessionId:o.slice(0,-6),project:n})}return e}async function n0(t,e,r,n){const s=await Em();if(s.length!==0){n.storedAvailable=!0;for(const o of s){let i;try{i=await zr(o.path)}catch{continue}if(i.mtimeMs<e)continue;const a=Date.now()-i.mtimeMs>Tl,c=`${i.mtimeMs}:${i.size}:${a}`,u=af.get(o.path);let l;if(u&&u.stamp===c)l=u.envelopes;else try{const d=Zb(await Nr(o.path,"utf8"));l=e0(d,{machine:t,host:Rr(),observedAt:Date.now(),path:o.path,sessionId:o.sessionId,closeOpenTurns:a}).map(Wt),af.set(o.path,{stamp:c,envelopes:l})}catch(d){n.transcriptsFailed++,n.problems.push({path:o.path,message:d instanceof Error?d.message:String(d),sourceVersion:d instanceof sr?d.sourceVersion:void 0});continue}n.transcriptsRead++;for(const d of l)d.occurredAt>=e&&d.occurredAt<=r&&n.envelopes.push(d)}}}async function Im(t,e){const r=_r(),n=Date.now(),s={envelopes:[],registryEntries:0,transcriptsRead:0,transcriptsFailed:0,problems:[],identityAvailable:!1,storedAvailable:!1};return await r0(r,n,s),await n0(r,t,e,s),s}async function s0(t,e){return(await Im(t,e)).envelopes}async function cf(){const t=Bl(),e=fe(Uc())?(await Ge(Uc()).catch(()=>[])).filter(n=>n.endsWith(".json")).length:0,r=(await Em()).length;return{available:e>0||r>0,present:fe(t),home:t,registry:e,transcripts:r}}const Ds="codex",o0={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"supported"},i0="codex",a0=10*6e4;class kn extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="CodexFormatError"}path;sourceVersion}const c0=t=>`codex:${t}`,Vt=t=>typeof t=="number"&&Number.isFinite(t)?t:0,ye=t=>typeof t=="string"&&t?t:void 0,uc=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function u0(t){const e=Vt(t.input_tokens),r=Vt(t.cached_input_tokens);return{[z.tokensInput]:Math.max(0,e-r),[z.tokensOutput]:Vt(t.output_tokens),[z.tokensCacheRead]:r,[z.tokensReasoning]:Vt(t.reasoning_output_tokens),[z.steps]:1}}function l0(t,e){const r=t.find(A=>A.type==="session_meta");if(!r||!r.payload)throw new kn("rollout has no session_meta record",e.path);const n=r.payload,s=ye(n.cli_version),o=ye(n.session_id)??ye(n.id);if(o&&o!==e.sessionId)throw new kn(`rollout names session ${o} but is filed under ${e.sessionId}`,e.path,s);const i=ye(n.cwd)??"",a=uc(n.timestamp)??uc(r.timestamp);if(a===void 0)throw new kn("session_meta has no parseable timestamp",e.path,s);const c=Ce(i).toUpperCase(),u=c0(e.sessionId),d={source:{id:Ds,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},m=(A,I)=>({path:e.path,...A?{recordId:A}:{},...I!==void 0?{index:I}:{},...s?{sourceVersion:s}:{}}),p=[];let y=null,v=a,g=0;for(let A=0;A<t.length;A++){const I=t[A],B=uc(I.timestamp);B!==void 0&&B>v&&(v=B);const k=I.payload;if(!k)continue;if(I.type==="turn_context"){y&&ye(k.turn_id)===y.turnId&&(y.model??=ye(k.model),y.effort??=ye(k.effort));continue}if(I.type!=="event_msg")continue;const T=ye(k.type);if(T==="task_started"){const E=ye(k.turn_id);if(!E||B===void 0)throw new kn(`task_started at ordinal ${I.ordinal} is missing turn_id or timestamp`,e.path,s);y={turnId:E,startedAt:B,interior:[],lastAt:B},p.push(y);continue}if(T==="task_complete"){const E=ye(k.turn_id),R=p.find(j=>j.turnId===E)??y;if(R&&B!==void 0){R.completedAt=B;const j=k.error;R.outcome=j?"error":"completed",R.failureMessage=j?ye(j.message):void 0,R.lastAt=Math.max(R.lastAt,B)}R===y&&(y=null);continue}if(T==="token_count"||T==="item_completed"){if(!y){g++;continue}if(B===void 0)continue}else continue;const S=`${u}:turn:${y.turnId}`;if(T==="token_count"){const R=k.info?.last_token_usage;if(!R)continue;y.lastAt=Math.max(y.lastAt,B),y.interior.push({...d,occurredAt:B,kind:"progressed",subject:{type:"execution",id:S},core:{measures:u0(R)},attrs:{"codex.usage.inputTokens":Vt(R.input_tokens),"codex.usage.cachedInputTokens":Vt(R.cached_input_tokens),"codex.usage.cacheWriteInputTokens":Vt(R.cache_write_input_tokens),"codex.usage.outputTokens":Vt(R.output_tokens),"codex.usage.reasoningOutputTokens":Vt(R.reasoning_output_tokens)},provenance:m(void 0,I.ordinal),seq:`o${I.ordinal??A}`});continue}if(T==="item_completed"){const E=k.item,R=ye(E?.type);if(!E||!R)continue;y.lastAt=Math.max(y.lastAt,B);let j,M;if(R==="CommandExecution"){const J=Vt(E.exit_code);j={[z.interactions]:1,...J!==0?{[z.errors]:1}:{}},M={"codex.itemType":R,"codex.exitCode":J,...E.process_id!==void 0?{"codex.processId":E.process_id}:{},...ye(E.status)?{"codex.status":E.status}:{}}}else if(R==="McpToolCall"){const J=ye(E.status)==="failed"||ye(E.status)==="error";j={[z.interactions]:1,...J?{[z.errors]:1}:{}},M={"codex.itemType":R,"codex.tool":[ye(E.server),ye(E.tool)].filter(Boolean).join("."),...ye(E.status)?{"codex.status":E.status}:{}}}else if(R==="WebSearch")j={[z.interactions]:1},M={"codex.itemType":R};else if(R==="FileChange"){const J=E.changes;j={[z.interactions]:1},M={"codex.itemType":R,...J&&typeof J=="object"?{"codex.fileChanges":Object.entries(J).map(([le,re])=>({path:le,kind:ye(re?.type)}))}:{}}}else continue;y.interior.push({...d,occurredAt:B,kind:"progressed",subject:{type:"execution",id:S},core:{measures:j},attrs:M,provenance:m(ye(E.id),I.ordinal),seq:`o${I.ordinal??A}`})}}if(p.length===0&&g>0)throw new kn(`rollout has ${g} work records but no task_started marker`,e.path,s);const C=[{...d,occurredAt:a,kind:"began",subject:{type:"session",id:u},claims:[{ns:"agent.session",parts:[i0,e.sessionId],validFrom:a,validTo:v}],core:{machineId:e.machine.id,label:c,projectLabel:e.projectLabel??(i?Ce(i):void 0),taskLabel:e.taskLabel,executor:Ds},attrs:{context:i,"codex.sessionId":e.sessionId,"codex.cliVersion":s,"codex.originator":ye(n.originator),"codex.source":ye(n.source),"codex.modelProvider":ye(n.model_provider),...d0(n.git)},provenance:m(e.sessionId,r.ordinal),seq:"session"}];for(let A=0;A<p.length;A++){const I=p[A],B=`${u}:turn:${I.turnId}`;C.push({...d,occurredAt:I.startedAt,kind:"began",subject:{type:"execution",id:B},core:{machineId:e.machine.id,sessionId:u,label:`${c} · TURN ${A+1}`,executor:Ds,model:I.model,depth:0},attrs:{"codex.turnId":I.turnId,...I.effort?{"codex.effort":I.effort}:{}},provenance:m(I.turnId),seq:`turn:${I.turnId}`}),C.push(...I.interior),I.completedAt!==void 0?C.push({...d,occurredAt:I.completedAt,kind:"ended",subject:{type:"execution",id:B},core:{outcome:I.outcome??"completed",...I.outcome==="error"?{failureCode:"CODEX_TURN_ERROR",failureMessage:I.failureMessage??"turn failed"}:{}},provenance:m(I.turnId),seq:`turn:${I.turnId}:end`}):e.now-v>a0&&C.push({...d,basis:"inferred",assumption:"A rollout untouched for 10 minutes belongs to a dead process, so a turn left open in it was interrupted, not still running. Its end is the last instant the rollout moved.",occurredAt:I.lastAt,kind:"ended",subject:{type:"execution",id:B},core:{outcome:"interrupted"},provenance:m(I.turnId),seq:`turn:${I.turnId}:end`})}return C}function d0(t){if(!t||typeof t!="object")return{};const e=t;return{...ye(e.branch)?{"codex.gitBranch":e.branch}:{},...ye(e.commit_hash)?{"codex.gitCommit":e.commit_hash}:{},...ye(e.repository_url)?{"codex.gitOriginUrl":e.repository_url}:{}}}function $l(){return process.env.CODEX_HOME||se(hn(),".codex")}const Cm=()=>se($l(),"sessions"),f0=/^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/,lc=new Map,p0=new Set(["CommandExecution","McpToolCall","WebSearch","FileChange"]);function h0(t){const e={timestamp:t.timestamp,ordinal:t.ordinal,type:t.type},r=t.payload;if(!r)return t.type==="session_meta"?{...e}:void 0;if(t.type==="session_meta"){const a=r.git;return{...e,payload:{session_id:r.session_id,id:r.id,timestamp:r.timestamp,cwd:r.cwd,originator:r.originator,cli_version:r.cli_version,source:r.source,model_provider:r.model_provider,git:a?{branch:a.branch,commit_hash:a.commit_hash,repository_url:a.repository_url}:void 0}}}if(t.type==="turn_context")return{...e,payload:{turn_id:r.turn_id,model:r.model,effort:r.effort}};if(t.type!=="event_msg")return;const n=r.type;if(n==="task_started")return{...e,payload:{type:n,turn_id:r.turn_id}};if(n==="task_complete"){const a=r.error;return{...e,payload:{type:n,turn_id:r.turn_id,...a?{error:{message:a.message}}:{}}}}if(n==="token_count"){const c=r.info?.last_token_usage;return c?{...e,payload:{type:n,info:{last_token_usage:{input_tokens:c.input_tokens,cached_input_tokens:c.cached_input_tokens,cache_write_input_tokens:c.cache_write_input_tokens,output_tokens:c.output_tokens,reasoning_output_tokens:c.reasoning_output_tokens}}}}:{...e,payload:{type:n}}}if(n!=="item_completed")return;const s=r.item,o=typeof s?.type=="string"?s.type:void 0;if(!s||!o||!p0.has(o))return{...e,payload:{type:n,item:o?{type:o}:void 0}};const i={type:o,id:s.id};if(o==="CommandExecution")i.process_id=s.process_id,i.exit_code=s.exit_code,i.status=s.status;else if(o==="McpToolCall")i.server=s.server,i.tool=s.tool,i.status=s.status;else if(o==="FileChange"){const a=s.changes;i.changes=a?Object.fromEntries(Object.entries(a).map(([c,u])=>[c,{type:u?.type}])):void 0}return{...e,payload:{type:n,item:i}}}async function m0(t,e=0){const r=[];let n=[],s=0,o=0,i=e;const a=(c,u)=>{if(u===0)return;const l=Buffer.concat(c,Math.min(u,1024)).subarray(0,1024).toString("utf8"),d=/^\s*\{\s*"timestamp"\s*:\s*"(?:\\.|[^"])*"\s*,\s*"type"\s*:\s*"([^"]+)"/.exec(l)?.[1];if(d&&d!=="session_meta"&&d!=="turn_context"&&d!=="event_msg")return;const m=Buffer.concat(c,u).toString("utf8");if(m.trim())try{const p=JSON.parse(m);if(!p||typeof p!="object")return;const y=h0(p);y&&r.push(y)}catch{}};for await(const c of dm(t,{start:e})){const u=Buffer.isBuffer(c)?c:Buffer.from(c),l=o;o+=u.length;let d=0;for(;;){const m=u.indexOf(10,d);if(m<0)break;const p=u.subarray(d,m);a([...n,p],s+p.length),n=[],s=0,d=m+1,i=e+l+d}if(d<u.length){const m=u.subarray(d);n.push(m),s+=m.length}}return{records:r,offset:i,bytesRead:o}}function y0(t,e,r){return t.occurredAt>=e&&t.occurredAt<=r||t.subject.type==="session"&&t.kind==="began"&&(typeof t.core?.projectLabel=="string"||typeof t.core?.taskLabel=="string")}function g0(t,e=$l()){const r=se(e,"state_5.sqlite");if(!fe(r))return new Map;let n;try{n=new go(r,{readOnly:!0}),n.exec("PRAGMA query_only = ON");const s=n.prepare("SELECT name FROM threads WHERE id = ? LIMIT 1");let o;try{o=n.prepare(`SELECT projects.name AS projectName
1
+ import{existsSync as ge,createReadStream as jm,statSync as fa,mkdirSync as eu,chmodSync as pa,writeFileSync as Wl,renameSync as Kl,rmSync as Dm,readFileSync as Gl}from"node:fs";import{createInterface as Ib}from"node:readline";import{createServer as Lm}from"node:http";import{join as ue,isAbsolute as tu,relative as Sc,sep as ru,dirname as vi,resolve as $s,normalize as Ob,extname as Cb}from"node:path";import{fileURLToPath as Nb}from"node:url";import{stat as sn,readdir as Ze,readFile as _r}from"node:fs/promises";import{hostname as Tb,homedir as xn}from"node:os";import $b from"node:zlib";import{createHash as fo,webcrypto as Bb,randomBytes as Yn,X509Certificate as Jo,timingSafeEqual as Rb,verify as Mb,createPublicKey as _b}from"node:crypto";import{execFileSync as jb,execFile as Db}from"node:child_process";import{DatabaseSync as Bs}from"node:sqlite";import{isMainThread as Pm,workerData as bi,parentPort as Fn,Worker as Um}from"node:worker_threads";import{promisify as Lb}from"node:util";import{createServer as Pb}from"node:https";function Ub(t){const e=new AbortController,r={controller:e,consumers:0,settled:!1,promise:t(e.signal)};return r.promise.then(()=>{r.settled=!0},()=>{r.settled=!0}),r}function yf(t,e){return t.consumers++,new Promise((r,n)=>{let o=!1;const s=a=>{o||(o=!0,e?.removeEventListener("abort",i),t.consumers--,!t.settled&&t.consumers===0&&t.controller.abort(),a())},i=()=>s(()=>n(new Error("analytical read cancelled")));e?.addEventListener("abort",i,{once:!0}),t.promise.then(a=>s(()=>r(a)),a=>s(()=>n(a))),e?.aborted&&i()})}const gf=["machine","session","execution","process","artifact"];function Vb(t){return`${t.ns}|${t.parts.join("|")}`}const Z={interactions:"interactions",steps:"steps",errors:"errors",retries:"retries",cpuMs:"cpu.ms",tokensInput:"tokens.input",tokensOutput:"tokens.output",tokensCacheRead:"tokens.cacheRead",tokensReasoning:"tokens.reasoning"},Hb=[{a:"execution",b:"process",kind:"ran-as"},{a:"session",b:"process",kind:"ran-as"},{a:"execution",b:"session",kind:"ran-as"},{a:"session",b:"session",kind:"same-as"},{a:"execution",b:"execution",kind:"same-as"},{a:"machine",b:"machine",kind:"same-as"},{a:"process",b:"process",kind:"same-as"}];function vf(t,e){for(const r of Hb){if(t.subjectType===r.a&&e.subjectType===r.b)return{kind:r.kind,from:t,to:e};if(e.subjectType===r.a&&t.subjectType===r.b)return{kind:r.kind,from:e,to:t}}return null}const Fb=(t,e)=>t.validFrom<=e.validTo&&e.validFrom<=t.validTo;function Wb(t,e){const r=Math.max(t.validFrom,e.validFrom),n=Math.min(t.validTo,e.validTo);if(n<r)return 0;const o=Math.max(t.validTo,e.validTo)-Math.min(t.validFrom,e.validFrom);return o<=0?1:(n-r)/o}const Kb=.5;function Gb(t,e){return Fb(t,e)?Wb(t,e)>=Kb?2:1:0}const Bt=t=>`${t.subjectType}:${t.subjectId}`,qb="inferred",zb="Two observers asserted the same identity claim over overlapping validity windows, and each was the other's only candidate at the strongest available evidence tier (two lifetimes that substantially coincide beat a bare overlap). The claims themselves are measured; the identification is inferred.";function Yb(t){const e=new Map;for(const s of t){const i=e.get(s.key);i?i.push(s):e.set(s.key,[s])}const r=[],n=[];let o=0;for(const[s,i]of[...e.entries()].sort(([a],[c])=>a<c?-1:1)){const a=new Map;for(const p of i){const h=Bt(p),v=a.get(h);if(!v){a.set(h,{...p});continue}v.validFrom=Math.min(v.validFrom,p.validFrom),v.validTo=Math.max(v.validTo,p.validTo)}const c=[...a.values()].sort((p,h)=>Bt(p)<Bt(h)?-1:1);if(c.length<2){o++;continue}const u=[];let d=!1;for(let p=0;p<c.length;p++)for(let h=p+1;h<c.length;h++){const v=c[p],g=c[h];if(v.sourceId===g.sourceId)continue;const I=Gb(v,g);if(I!==0){if(!vf(v,g)){d=!0;continue}u.push({x:v,y:g,tier:I})}}const l=new Map;for(const p of u)for(const h of[p.x,p.y]){const v=Bt(h);l.set(v,Math.max(l.get(v)??0,p.tier))}const m=new Map;for(const p of u)for(const h of[p.x,p.y]){const v=Bt(h);l.get(v)===p.tier&&m.set(v,(m.get(v)??0)+1)}if(u.length===0){n.push({key:s,reason:d?"no-pairing-defined":"no-window-overlap",subjects:[...a.keys()].sort()});continue}for(const{x:p,y:h,tier:v}of u){if(l.get(Bt(p))!==v||l.get(Bt(h))!==v)continue;if(m.get(Bt(p))!==1||m.get(Bt(h))!==1){n.push({key:s,reason:"multiple-candidates",subjects:[Bt(p),Bt(h)].sort()});continue}const g=vf(p,h);r.push({from:{type:g.from.subjectType,id:g.from.subjectId},to:{type:g.to.subjectType,id:g.to.subjectId},kind:g.kind,basis:qb,assumption:zb,via:s})}}return{relationships:r,ambiguous:n,unmatched:o,considered:e.size}}async function Xb(t,e,r,n,o){const s=[];let i=0,a=0;for(const c of e){const u=Date.now();try{const d=await c.collect(r,n),l=t.append(d);i+=l.inserted,a+=l.duplicate,s.push({id:c.id,ok:!0,collected:d.length,inserted:l.inserted,duplicate:l.duplicate,ms:Date.now()-u})}catch(d){s.push({id:c.id,ok:!1,collected:0,inserted:0,duplicate:0,error:d instanceof Error?d.message:String(d),ms:Date.now()-u})}o?.(s[s.length-1])}return{sources:s,inserted:i,duplicate:a}}const Vm=1e3,bf=60*Vm;function fe(t){if(!Number.isFinite(t)||t<=0)return"0m";if(t<bf)return`${Math.max(1,Math.round(t/Vm))}s`;const e=Math.round(t/bf),r=Math.floor(e/60),n=e%60;return r===0?`${n}m`:n===0?`${r}h`:`${r}h ${n}m`}function ze(t){if(!Number.isFinite(t))return"—";const e=Math.abs(t);return e>=1e9?`${(t/1e9).toFixed(e>=1e10?0:2)}B`:e>=1e6?`${(t/1e6).toFixed(e>=1e7?0:2)}M`:e>=1e3?`${(t/1e3).toFixed(e>=1e4?0:1)}k`:String(Math.round(t))}function Jb(t,e="NOT OBSERVED"){return t===void 0?e:ze(t)}function wi(t,e){if(e<=0)return"—";const r=t/e*100;return r>0&&r<1?"<1%":`${Math.round(r)}%`}function Zb(t){return t===void 0||!Number.isFinite(t)?"—":t>=1e9?`${(t/1e9).toFixed(1)} GB`:t>=1e6?`${(t/1e6).toFixed(0)} MB`:t>=1e3?`${(t/1e3).toFixed(0)} KB`:`${t} B`}function wf(t){const e=new Date(t);return`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}function Ne(t){const e=t.split("/").filter(Boolean);return e[e.length-1]??t}const ql="deepseek-harness",Qb={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"supported",waits:"supported",model:"supported",context:"supported",outcome:"supported"},Me=t=>typeof t=="number"&&Number.isFinite(t)?t:0,dt=t=>typeof t=="string"?t:void 0;function ew(t){const e=t.split("/").filter(Boolean);return(e[e.length-1]??t).toUpperCase()}function tw(t,e){const r=[],n=t[0];if(!n||n.type!=="session"||!n.id)return r;const o=n.id,s=n.cwd??"",i=Me(n.createdAt),a=Me(n.delegationDepth),c=ew(s);let u="deepseek",d,l;for(const x of t)if(x.type==="request/context"&&x.data?(u=dt(x.data.provider)??u,d=dt(x.data.model)??d):x.type==="session/title"&&x.data&&(l=dt(x.data.title)??l),d&&l)break;const p={source:{id:ql,instance:e.instance},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"};let h=i;for(const x of t){const D=Me(x.time);D>h&&(h=D)}const v={ns:"fs.cwd",parts:[e.host,s],validFrom:i,validTo:Math.max(i,h)};r.push({...p,occurredAt:i,seq:"session",kind:"began",subject:{type:"session",id:o},claims:s?[v]:void 0,core:{machineId:e.machine.id,label:l,projectLabel:s?Ne(s):void 0,taskLabel:l,executor:u,model:d,depth:a},attrs:{context:s,"dsh.delegationDepth":a}});const g=x=>`${o}:turn:${x}`;let I=null;const N=new Map,S=new Map;let T=i;for(const x of t){const D=Me(x.time)||T;if(D<i)continue;T=D;const w=x.data??{},$=x.seq??`t${D}`,E=B=>({type:"execution",id:g(B)});switch(x.type){case"turn/start":{const B=Me(w.turn);I=B,r.push({...p,occurredAt:D,seq:$,kind:"began",subject:E(B),core:{machineId:e.machine.id,sessionId:o,label:l?`${c} · ${l}`:c,executor:u,model:d,depth:a},attrs:{"dsh.turn":B}});break}case"turn/end":{const B=Me(w.turn),C=w.reason,P=C?.kind;if(P==="error"){const L=C?.error??{};r.push({...p,occurredAt:D,seq:$,kind:"ended",subject:E(B),core:{outcome:"error",failureCode:dt(L.code)??"ERROR",failureMessage:dt(L.message)??"Run failed"},attrs:{"dsh.endReason":P}})}else r.push({...p,occurredAt:D,seq:$,kind:"ended",subject:E(B),core:{outcome:P==="aborted"?"interrupted":"completed"},attrs:{"dsh.endReason":P??"completed"}});I===B&&(I=null);break}case"assistant/message":{const B=Me(w.turn),C=w.usage;if(!C)break;const P={[Z.tokensInput]:Me(C.inputTokens),[Z.tokensOutput]:Me(C.outputTokens),[Z.tokensCacheRead]:Me(C.cacheReadTokens),[Z.tokensReasoning]:Me(C.reasoningTokens),[Z.steps]:1};r.push({...p,occurredAt:D,seq:$,kind:"progressed",subject:E(B),core:{measures:P},attrs:{"dsh.inputTokens":Me(C.inputTokens),"dsh.outputTokens":Me(C.outputTokens),"dsh.cacheReadTokens":Me(C.cacheReadTokens),"dsh.reasoningTokens":Me(C.reasoningTokens)}});break}case"tool/call":{r.push({...p,occurredAt:D,seq:$,kind:"progressed",subject:E(Me(w.turn)),core:{measures:{[Z.interactions]:1}},attrs:{"dsh.tool":dt(w.name)}});break}case"tool/result":{const B=w.message;let C=!1;for(const P of B?.content??[])P.isError===!0&&(C=!0);C&&r.push({...p,occurredAt:D,seq:$,kind:"progressed",subject:E(Me(w.turn)),core:{measures:{[Z.errors]:1}}});break}case"llm/retry":{r.push({...p,occurredAt:D,seq:$,kind:"progressed",subject:E(Me(w.turn)),core:{measures:{[Z.retries]:1}}});break}case"approval/asked":{const B=dt(w.id);if(I===null)break;B&&N.set(B,I),r.push({...p,occurredAt:D,seq:$,kind:"blocked",subject:E(I),core:{blockedOn:"approval"},attrs:{"dsh.approvalId":B}});break}case"approval/decided":{const B=dt(w.id),C=B?N.get(B):I;if(C==null)break;N.delete(B??""),r.push({...p,occurredAt:D,seq:$,kind:"resumed",subject:E(C),attrs:{"dsh.approvalId":B}});break}case"tool-workflow/agent-start":{if(I===null)break;const B=dt(w.childId);if(!B)break;const C=`${o}:agent:${B}`;S.set(`${dt(w.runId)}:${Me(w.seq)}`,C),r.push({...p,occurredAt:D,seq:$,kind:"began",subject:{type:"execution",id:C},core:{machineId:e.machine.id,sessionId:o,label:dt(w.label)??`${c} · SUB`,executor:u,model:d,parentId:g(I),depth:a+1},attrs:{"dsh.childId":B}});break}case"tool-workflow/agent-end":{const B=`${dt(w.runId)}:${Me(w.seq)}`,C=S.get(B);if(!C)break;S.delete(B);const P=dt(w.outcome);r.push({...p,occurredAt:D,seq:$,kind:"ended",subject:{type:"execution",id:C},core:P==="completed"?{outcome:"completed"}:{outcome:"error",failureCode:"SUBAGENT",failureMessage:P??"Sub-agent did not complete"},attrs:{"dsh.subagentOutcome":P}});break}}}if(e.closeOpenTurns){const x="The session log has not been written to for longer than the live window, so the process that owned it is gone and any turn left open was cut off rather than still running.";I!==null&&r.push({...p,occurredAt:T,seq:"close:turn",kind:"ended",subject:{type:"execution",id:g(I)},core:{outcome:"interrupted"},basis:"inferred",assumption:x});for(const D of S.values())r.push({...p,occurredAt:T,seq:`close:${D}`,kind:"ended",subject:{type:"execution",id:D},core:{outcome:"interrupted"},basis:"inferred",assumption:x});r.push({...p,occurredAt:T,seq:"close:session",kind:"ended",subject:{type:"session",id:o},basis:"inferred",assumption:x})}return e.since!==void 0?r.filter(x=>x.occurredAt>=e.since):r}function rw(t){const e=[];let r=0;for(;r<t.length;){let n=t.indexOf(`
2
+ `,r);n===-1&&(n=t.length);const o=t.slice(r,n);if(r=n+1,o.length!==0&&!(o.startsWith('{"type":"reasoning-chunks"')||o.startsWith('{"type":"text-chunks"')||o.startsWith('{"type":"tool-call-chunks"')||o.startsWith('{"type":"assistant/chunk"')))try{e.push(JSON.parse(o))}catch{}}return e}function nw(t){const e=JSON.stringify([t.source.id,t.source.instance,t.occurredAt,t.clock,t.kind,t.subject.type,t.subject.id,t.basis,t.seq??null,Ai(t.core),Ai(t.attrs)]);return fo("sha256").update(e).digest("hex").slice(0,32)}function Ai(t){if(t==null)return null;if(Array.isArray(t))return t.map(Ai);if(typeof t!="object")return t;const e={};for(const r of Object.keys(t).sort())e[r]=Ai(t[r]);return e}function Zt(t){const{seq:e,...r}=t;return{id:nw(t),...r}}let Af;function ow(){try{const t=jb("/usr/sbin/scutil",["--get","LocalHostName"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim();return/^[A-Za-z0-9-]{1,63}$/.test(t)?t:void 0}catch{return}}function Hm(){return Af??=ow()??Tb().replace(/\.local$/i,""),Af}const Si="host:";function sw(t){return`${Si}${t}`}function iw(t){return t.startsWith(Si)?t.slice(Si.length):void 0}function Sf(t){return t.startsWith(Si)}const aw=4247762216,cw=407710288,uw=407710303;function lw(t){const e=[];for(let o=0;o+4<=t.length;o++){const s=t.readUInt32LE(o);(s===aw||s>=cw&&s<=uw)&&e.push(o)}if(e.length===0)return Buffer.alloc(0);const r=[];let n=0;for(;n<e.length;){let o=n+1,s=null;for(;;){const i=o<e.length?e[o]:t.length;try{s=$b.zstdDecompressSync(t.subarray(e[n],i));break}catch{if(o>=e.length)break;o++}}s?(r.push(s),n=o):n++}return Buffer.concat(r)}function zl(){return process.env.DSH_HOME||ue(xn(),".dsh")}function Ur(){return Hm()}function Vr(){const t=Ur();return{id:sw(t),name:t.toUpperCase(),kind:"laptop",firstSeenAt:0}}const kf=new Map;async function Fm(){const t=ue(zl(),"sessions");if(!ge(t))return[];const e=[];for(const r of await Ze(t)){const n=ue(t,r);let o;try{o=await Ze(n)}catch{continue}for(const s of o){const i=ue(n,s,"session.jsonl.zstd");ge(i)&&e.push({path:i,workspace:r,sessionId:s})}}return e}const Yl=10*6e4;async function dw(t,e){const r=await sn(t.path),n=kf.get(t.path);if(n&&n.mtimeMs===r.mtimeMs&&n.size===r.size)return n.envelopes;const o=await _r(t.path),s=lw(o).toString("utf8"),i=rw(s),a=Date.now()-r.mtimeMs>Yl,u=tw(i,{machine:e,host:Ur(),instance:zl(),observedAt:Date.now(),closeOpenTurns:a}).map(Zt);return kf.set(t.path,{mtimeMs:r.mtimeMs,size:r.size,envelopes:u}),u}async function fw(t,e){const r=Vr(),n=await Fm(),o=[];for(const s of n){let i;try{i=await sn(s.path)}catch{continue}if(!(i.mtimeMs<t))for(const a of await dw(s,r))a.occurredAt>=t&&a.occurredAt<=e&&o.push(a)}return o}async function Ef(){const t=await Fm(),e=zl();return{available:t.length>0,present:ge(e),home:e,sessions:t.length}}const ki="0x2f",pw={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"supported",model:"partial",context:"supported",outcome:"supported"},ar=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0},Wm=(t,e)=>`2f:${t}#${e}`,hw=(t,e,r)=>`${Wm(t,e)}:run:${r}`;function xf(t){return t?.type==="permission"?"approval":"input"}function mw(t){const e=new Map;for(const r of t){const n=typeof r.run=="number"?r.run:1,o=e.get(n);o?o.push(r):e.set(n,[r])}return e}function yw(t,e){const r=e.find(s=>s.type==="run.started");let n;for(let s=e.length-1;s>=0;s--){const i=e[s];if(i.type==="run.completed"||i.type==="run.failed"||i.type==="needs_user"&&i.blockedOn){n=i;break}}let o;return n?.type==="run.completed"?o="ready":n?.type==="run.failed"?o="failed":n?o="needs_you":t.status==="needs_you"||t.status==="ready"||t.status==="failed"?o=t.status:t.status==="working"?o="working":o=t.error?"failed":"ready",{run:1,provider:t.execution?.provider??null,node:t.execution?.node??null,model:t.execution?.model,externalSessionId:t.execution?.externalSessionId,attempts:t.execution?.attempts??1,startedAt:r?.at,completedAt:n?.at,outcome:o,error:t.error??(n?.type==="run.failed"?n.error:void 0),blockedOn:n?.type==="needs_user"?n.blockedOn:void 0,failure:t.failure}}function gw(t,e){return Array.isArray(t.runs)&&t.runs.length?t.runs:[yw(t,e)]}function vw(t,e,r){if(typeof t.id!="number")return[];const n=Wm(r.base,t.id),o=gw(t,e),s=Ne(r.base).toUpperCase(),i=t.title,a=t.execution?.provider??o.at(-1)?.provider??ki,c=ar(t.createdAt)??o.map(g=>ar(g.startedAt)).find(g=>g!==void 0);if(c===void 0)return[];const d={source:{id:ki,instance:r.base},observedAt:r.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},l=[{...d,occurredAt:c,kind:"began",subject:{type:"session",id:n},core:{machineId:r.machine.id,label:i,projectLabel:Ne(r.base),taskLabel:i,executor:a,model:t.execution?.model},attrs:{context:r.base,"0x2f.taskId":t.id,"0x2f.status":t.status}}],m=mw(e),p=e.filter(g=>g.type==="task.answered"),h=e.find(g=>g.type==="task.closed"),v=o.at(-1);for(let g=0;g<o.length;g++){const I=o[g],N=ar(I.startedAt);if(N===void 0)continue;const S=hw(r.base,t.id,I.run),T=I.provider??a,x=ar(I.completedAt),D=x??r.now,w=[{ns:"fs.cwd",parts:[r.host,r.base],validFrom:N,validTo:D}];typeof I.externalSessionId=="string"&&I.externalSessionId&&w.push({ns:"agent.session",parts:[T,I.externalSessionId],validFrom:N,validTo:D}),I===v&&typeof t.pid=="number"&&w.push({ns:"os.process",parts:[r.host,t.pid],validFrom:N,validTo:D}),l.push({...d,occurredAt:N,seq:`run:${I.run}`,kind:"began",subject:{type:"execution",id:S},claims:w,core:{machineId:r.machine.id,sessionId:n,label:i?`${s} · ${i} · RUN ${I.run}`:`${s} · RUN ${I.run}`,executor:T,model:I.model??t.execution?.model,depth:0},attrs:{"0x2f.run":I.run,"0x2f.provider":T,"0x2f.workspace":r.base,...I.requestedProvider?{"0x2f.requestedProvider":I.requestedProvider}:{},...t.pid!==void 0&&I===v?{"0x2f.workerPid":t.pid}:{}}});let $=!1,E=0;for(const C of m.get(I.run)??[]){E++;const P=ar(C.at);if(P===void 0||P<N)continue;const L=`run:${I.run}:${E}`;if(C.type==="tool.started")l.push({...d,occurredAt:P,seq:L,kind:"progressed",subject:{type:"execution",id:S},core:{measures:{[Z.interactions]:1}},attrs:{"0x2f.tool":C.name}});else if(C.type==="progress")l.push({...d,occurredAt:P,seq:L,kind:"progressed",subject:{type:"execution",id:S}});else if(C.type==="needs_user"&&C.blockedOn){if($)continue;$=!0,l.push({...d,occurredAt:P,seq:L,kind:"blocked",subject:{type:"execution",id:S},core:{blockedOn:xf(C.blockedOn)},attrs:{"0x2f.blockedOn":C.blockedOn.type}})}else if(C.type==="permission.resolved"||C.type==="task.updated"&&typeof C.grant=="string"){if(!$)continue;$=!1,l.push({...d,occurredAt:P,seq:L,kind:"resumed",subject:{type:"execution",id:S},attrs:{"0x2f.grant":C.grant}})}}const B=(C,P,L)=>l.push({...d,occurredAt:C,seq:L,kind:"ended",subject:{type:"execution",id:S},core:P});if(I.outcome==="ready"&&x!==void 0)B(x,{outcome:"completed"},`run:${I.run}:end`);else if(I.outcome==="failed"&&x!==void 0)B(x,{outcome:"error",failureCode:(I.failure?.kind??t.failure?.kind??"unclassified").toUpperCase(),failureMessage:I.error??t.error??"Run failed"},`run:${I.run}:end`);else if(I.outcome==="needs_you"&&x!==void 0){$||($=!0,l.push({...d,occurredAt:x,seq:`run:${I.run}:block`,kind:"blocked",subject:{type:"execution",id:S},core:{blockedOn:xf(I.blockedOn)}}));const C=bw(x,p,o[g+1],h);C!==void 0&&B(C,{outcome:"interrupted"},`run:${I.run}:end`)}}if(h){const g=ar(h.at);g!==void 0&&l.push({...d,occurredAt:g,seq:"task:closed",kind:"ended",subject:{type:"session",id:n}})}return l}function bw(t,e,r,n){const o=[...e.map(i=>ar(i.at)),ar(r?.startedAt),ar(n?.at)];let s;for(const i of o)i===void 0||i<t||(s===void 0||i<s)&&(s=i);return s}function ww(t){const e=[];for(const r of t.split(`
3
+ `))if(r.trim())try{const n=JSON.parse(r);n&&typeof n.type=="string"&&e.push(n)}catch{}return e}const Km=".work";function Gm(){const t=process.env.WORK_ROOTS;return t?t.split(/[:,]/).map(e=>e.trim()).filter(Boolean):[xn()]}const If=t=>ge(ue(t,Km,"tasks")),Aw=new Set(["Desktop","Documents","Downloads"]);async function qm(){const t=new Set,e=!process.env.WORK_ROOTS;for(const r of Gm()){if(If(r)){t.add(r);continue}let n;try{n=await Ze(r,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory()||o.name.startsWith(".")||e&&Aw.has(o.name))continue;const s=ue(r,o.name);If(s)&&t.add(s)}}return[...t].sort()}async function Sw(){const t=[];for(const e of await qm()){const r=ue(e,Km,"tasks");let n;try{n=await Ze(r,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory())continue;const s=ue(r,o.name,"task.json");ge(s)&&t.push({base:e,slug:o.name,taskPath:s,eventsPath:ue(r,o.name,"events.jsonl")})}}return t}const Of=new Map;async function kw(t,e,r){let n;try{n=await sn(t.taskPath)}catch{return null}const o=await sn(t.eventsPath).catch(()=>null),s=Math.max(n.mtimeMs,o?.mtimeMs??0),i=`${n.mtimeMs}:${n.size}:${o?.mtimeMs??0}:${o?.size??0}`,a=Of.get(t.taskPath);if(a&&a.stamp===i)return{envelopes:a.envelopes,touchedAt:s};let c;try{c=JSON.parse(await _r(t.taskPath,"utf8"))}catch{return null}let u=[];try{u=ww(await _r(t.eventsPath,"utf8"))}catch{}const d=vw(c,u,{machine:e,base:t.base,host:Ur(),observedAt:Date.now(),now:r}).map(Zt);return Of.set(t.taskPath,{stamp:i,envelopes:d}),{envelopes:d,touchedAt:s}}async function Ew(t,e){const r=Vr(),n=await Sw(),o=[];for(const s of n){const i=await kw(s,r,e);if(i&&!(i.touchedAt<t))for(const a of i.envelopes)a.occurredAt>=t&&a.occurredAt<=e&&o.push(a)}return o}async function Cf(){const t=Gm(),e=await qm();return{available:e.length>0,present:t.some(r=>ge(r)),roots:t,workspaces:e}}const en="claude-code",xw={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"partial"},zm="claude-code";class lr extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="ClaudeFormatError"}path;sourceVersion}const Ym=t=>`claude:${t}`;function Iw(t,e){const r=t,n=typeof r?.version=="string"?r.version:void 0;if(!r||typeof r!="object")throw new lr("registry entry is not an object",e,n);if(typeof r.sessionId!="string"||!r.sessionId)throw new lr("registry entry has no sessionId",e,n);if(typeof r.pid!="number"||!Number.isFinite(r.pid))throw new lr("registry entry has no numeric pid",e,n);if(typeof r.startedAt!="number"||!Number.isFinite(r.startedAt))throw new lr("registry entry has no numeric startedAt",e,n);return r}function Ow(t,e,r){const n=[{ns:"agent.session",parts:[zm,t.sessionId],validFrom:t.startedAt,validTo:r.now},{ns:"os.process",parts:[r.host,t.pid],validFrom:t.startedAt,validTo:r.now}];return{source:{id:en,instance:r.host},occurredAt:t.startedAt,observedAt:r.observedAt,clock:"wall",stratum:"identity",kind:"began",subject:{type:"session",id:Ym(t.sessionId)},claims:n,basis:"measured",core:{machineId:r.machine.id,label:t.name??Ne(t.cwd??"").toUpperCase(),projectLabel:t.cwd?Ne(t.cwd):void 0,taskLabel:t.name,executor:en},attrs:{context:t.cwd,"claude.sessionId":t.sessionId,"claude.pid":t.pid,"claude.procStart":t.procStart,"claude.version":t.version,"claude.kind":t.kind,"claude.entrypoint":t.entrypoint,"claude.status":t.status,"claude.waitingFor":t.waitingFor},provenance:{path:e,recordId:t.sessionId,sourceVersion:t.version},seq:"registry"}}const Cw=new Set(["stop_hook_summary","turn_duration"]),Nw="The transcript has not been written to for longer than the live window, so the process that owned it is gone and the turn ended at its last record.",cr=t=>typeof t=="number"&&Number.isFinite(t)?t:0,Bn=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function Tw(t){const e=[];for(const r of t.split(`
4
+ `))if(r.trim())try{const n=JSON.parse(r);n&&typeof n=="object"&&e.push(n)}catch{}return e}function $w(t){if(!t)return{};const e=t.output_tokens_details;return{[Z.tokensInput]:cr(t.input_tokens)+cr(t.cache_creation_input_tokens),[Z.tokensOutput]:cr(t.output_tokens),[Z.tokensCacheRead]:cr(t.cache_read_input_tokens),[Z.tokensReasoning]:cr(e?.thinking_tokens),[Z.steps]:1}}function Bw(t,e){const r=t.filter(N=>Bn(N.timestamp)!==void 0);if(r.length===0)throw new lr("transcript has no timestamped records",e.path);const n=t.find(N=>typeof N.sessionId=="string")?.sessionId;if(n&&n!==e.sessionId)throw new lr(`transcript names session ${n} but is filed under ${e.sessionId}`,e.path);const o=t.find(N=>typeof N.version=="string")?.version,s=t.find(N=>typeof N.cwd=="string")?.cwd??"",i=t.find(N=>typeof N.gitBranch=="string")?.gitBranch,a=t.find(N=>typeof N.entrypoint=="string")?.entrypoint,c=Ne(s).toUpperCase(),u=e.sessionId,d=Ym(u),l=Bn(r[0].timestamp),m=Bn(r[r.length-1].timestamp),h={source:{id:en,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},v=(N,S)=>({path:e.path,...N?{recordId:N}:{},...S!==void 0?{index:S}:{},...o?{sourceVersion:o}:{}}),g=[{...h,occurredAt:l,kind:"began",subject:{type:"session",id:d},claims:[{ns:"agent.session",parts:[zm,u],validFrom:l,validTo:m}],core:{machineId:e.machine.id,label:c,projectLabel:s?Ne(s):void 0,executor:en},attrs:{context:s,"claude.sessionId":u,"claude.gitBranch":i,"claude.entrypoint":a,"claude.version":o},provenance:v(u),seq:"session"}],I=[];for(let N=0;N<t.length;N++){const S=t[N];S.type==="user"&&typeof S.promptSource=="string"&&Bn(S.timestamp)!==void 0&&I.push(N)}if(I.length===0)throw new lr(`transcript has ${t.length} records but no prompt-bearing user record (expected \`type:"user"\` with \`promptSource\`)`,e.path,o);for(let N=0;N<I.length;N++){const S=I[N],T=N+1<I.length?I[N+1]:t.length,x=N+1,D=`${d}:turn:${x}`,w=Bn(t[S].timestamp),$=t.slice(S,T).some(U=>U.isSidechain===!0);let E,B=w,C,P=!1;const L=[];for(let U=S;U<T;U++){const V=t[U],z=Bn(V.timestamp);if(z===void 0)continue;const se=V.type==="assistant"||V.type==="user"&&Array.isArray(V.message?.content);if(se&&z>B&&(B=z),se?(C=V,P=!1):V.type==="system"&&Cw.has(V.subtype??"")&&(P=!0),V.type==="assistant"&&V.message){E??=V.message.model;const Ae=(Array.isArray(V.message.content)?V.message.content:[]).filter(Ie=>!!Ie&&typeof Ie=="object"&&Ie.type==="tool_use"),_e={...$w(V.message.usage)};Ae.length&&(_e[Z.interactions]=Ae.length),L.push({...h,occurredAt:z,kind:"progressed",subject:{type:"execution",id:D},core:{measures:_e},attrs:{...Ae.length?{"claude.tools":Ae.map(Ie=>Ie.name??"unknown")}:{},...V.message.model?{"claude.model":V.message.model}:{},...V.requestId?{"claude.requestId":V.requestId}:{},...V.message.stop_reason?{"claude.stopReason":V.message.stop_reason}:{},...V.message.usage?{"claude.usage.inputTokens":cr(V.message.usage.input_tokens),"claude.usage.outputTokens":cr(V.message.usage.output_tokens),"claude.usage.cacheReadTokens":cr(V.message.usage.cache_read_input_tokens),"claude.usage.cacheCreationTokens":cr(V.message.usage.cache_creation_input_tokens),"claude.usage.serviceTier":V.message.usage.service_tier}:{}},provenance:v(V.uuid,U),seq:V.uuid??`a${U}`})}else if(V.type==="user"&&V.message&&Array.isArray(V.message.content)){const ve=V.message.content.filter(Ae=>!!Ae&&typeof Ae=="object"&&Ae.is_error===!0).length;ve&&L.push({...h,occurredAt:z,kind:"progressed",subject:{type:"execution",id:D},core:{measures:{[Z.errors]:ve}},provenance:v(V.uuid,U),seq:V.uuid??`e${U}`})}}if(g.push({...h,occurredAt:w,kind:"began",subject:{type:"execution",id:D},core:{machineId:e.machine.id,sessionId:d,label:`${c} · TURN ${x}`,executor:en,model:E,depth:$?1:0},attrs:{"claude.turn":x,"claude.promptSource":t[S].promptSource,"claude.promptId":t[S].promptId,...$?{"claude.isSidechain":!0}:{}},provenance:v(t[S].uuid,S),seq:`turn:${x}`}),g.push(...L),N+1<I.length||P)g.push({...h,occurredAt:B,kind:"ended",subject:{type:"execution",id:D},core:{outcome:"completed"},provenance:v(t[S].uuid,S),seq:`turn:${x}:end`});else if(e.closeOpenTurns){const U=C?.type==="assistant"&&(C.message?.stop_reason==="end_turn"||C.message?.stop_reason==="stop_sequence");g.push({...h,occurredAt:B,kind:"ended",subject:{type:"execution",id:D},core:{outcome:U?"completed":"interrupted"},basis:"inferred",assumption:Nw,provenance:v(t[S].uuid,S),seq:`turn:${x}:end`})}}return g}function Xl(){return process.env.CLAUDE_HOME||ue(xn(),".claude")}const nu=()=>ue(Xl(),"sessions"),Rw=()=>ue(Xl(),"projects"),Nf=new Map;async function Mw(t,e,r){const n=nu();if(!ge(n))return;r.identityAvailable=!0;let o;try{o=await Ze(n)}catch(s){r.problems.push({path:n,message:String(s)});return}for(const s of o){if(!s.endsWith(".json"))continue;const i=ue(n,s);try{const a=Iw(JSON.parse(await _r(i,"utf8")),i);r.envelopes.push(Zt(Ow(a,i,{machine:t,host:Ur(),observedAt:e,now:e}))),r.registryEntries++}catch(a){r.problems.push({path:i,message:a instanceof Error?a.message:String(a),sourceVersion:a instanceof lr?a.sourceVersion:void 0})}}}async function Xm(){const t=Rw();if(!ge(t))return[];const e=[];let r;try{r=await Ze(t)}catch{return e}for(const n of r){let o;try{o=await Ze(ue(t,n))}catch{continue}for(const s of o)s.endsWith(".jsonl")&&e.push({path:ue(t,n,s),sessionId:s.slice(0,-6),project:n})}return e}async function _w(t,e,r,n){const o=await Xm();if(o.length!==0){n.storedAvailable=!0;for(const s of o){let i;try{i=await sn(s.path)}catch{continue}if(i.mtimeMs<e)continue;const a=Date.now()-i.mtimeMs>Yl,c=`${i.mtimeMs}:${i.size}:${a}`,u=Nf.get(s.path);let d;if(u&&u.stamp===c)d=u.envelopes;else try{const l=Tw(await _r(s.path,"utf8"));d=Bw(l,{machine:t,host:Ur(),observedAt:Date.now(),path:s.path,sessionId:s.sessionId,closeOpenTurns:a}).map(Zt),Nf.set(s.path,{stamp:c,envelopes:d})}catch(l){n.transcriptsFailed++,n.problems.push({path:s.path,message:l instanceof Error?l.message:String(l),sourceVersion:l instanceof lr?l.sourceVersion:void 0});continue}n.transcriptsRead++;for(const l of d)l.occurredAt>=e&&l.occurredAt<=r&&n.envelopes.push(l)}}}async function Jm(t,e){const r=Vr(),n=Date.now(),o={envelopes:[],registryEntries:0,transcriptsRead:0,transcriptsFailed:0,problems:[],identityAvailable:!1,storedAvailable:!1};return await Mw(r,n,o),await _w(r,t,e,o),o}async function jw(t,e){return(await Jm(t,e)).envelopes}async function Tf(){const t=Xl(),e=ge(nu())?(await Ze(nu()).catch(()=>[])).filter(n=>n.endsWith(".json")).length:0,r=(await Xm()).length;return{available:e>0||r>0,present:ge(t),home:t,registry:e,transcripts:r}}const Zo="codex",Dw={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"supported"},Lw="codex",Pw=10*6e4;class Yr extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="CodexFormatError"}path;sourceVersion}const Uw=t=>`codex:${t}`,Yt=t=>typeof t=="number"&&Number.isFinite(t)?t:0,Se=t=>typeof t=="string"&&t?t:void 0,kc=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function Vw(t){const e=Yt(t.input_tokens),r=Yt(t.cached_input_tokens);return{[Z.tokensInput]:Math.max(0,e-r),[Z.tokensOutput]:Yt(t.output_tokens),[Z.tokensCacheRead]:r,[Z.tokensReasoning]:Yt(t.reasoning_output_tokens),[Z.steps]:1}}function Hw(t,e){const r=t.find(N=>N.type==="session_meta");if(!r||!r.payload)throw new Yr("rollout has no session_meta record",e.path);const n=r.payload,o=Se(n.cli_version),s=Se(n.session_id)??Se(n.id);if(s&&s!==e.sessionId)throw new Yr(`rollout names session ${s} but is filed under ${e.sessionId}`,e.path,o);const i=Se(n.cwd)??"",a=kc(n.timestamp)??kc(r.timestamp);if(a===void 0)throw new Yr("session_meta has no parseable timestamp",e.path,o);const c=Ne(i).toUpperCase(),u=Uw(e.sessionId),l={source:{id:Zo,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},m=(N,S)=>({path:e.path,...N?{recordId:N}:{},...S!==void 0?{index:S}:{},...o?{sourceVersion:o}:{}}),p=[];let h=null,v=a,g=0;for(let N=0;N<t.length;N++){const S=t[N],T=kc(S.timestamp);T!==void 0&&T>v&&(v=T);const x=S.payload;if(!x)continue;if(S.type==="turn_context"){h&&Se(x.turn_id)===h.turnId&&(h.model??=Se(x.model),h.effort??=Se(x.effort));continue}if(S.type!=="event_msg")continue;const D=Se(x.type);if(D==="task_started"){const $=Se(x.turn_id);if(!$||T===void 0)throw new Yr(`task_started at ordinal ${S.ordinal} is missing turn_id or timestamp`,e.path,o);h={turnId:$,startedAt:T,interior:[],lastAt:T},p.push(h);continue}if(D==="task_complete"){const $=Se(x.turn_id),E=p.find(B=>B.turnId===$)??h;if(E&&T!==void 0){E.completedAt=T;const B=x.error;E.outcome=B?"error":"completed",E.failureMessage=B?Se(B.message):void 0,E.lastAt=Math.max(E.lastAt,T)}E===h&&(h=null);continue}if(D==="turn_aborted"){const $=Se(x.turn_id);if(!$||T===void 0)throw new Yr(`turn_aborted at ordinal ${S.ordinal} is missing turn_id or timestamp`,e.path,o);const E=p.find(B=>B.turnId===$);E&&E.completedAt===void 0&&(E.completedAt=T,E.outcome="interrupted",E.lastAt=Math.max(E.lastAt,T)),E===h&&(h=null);continue}if(D==="token_count"||D==="item_completed"){if(!h){g++;continue}if(T===void 0)continue}else continue;const w=`${u}:turn:${h.turnId}`;if(D==="token_count"){const E=x.info?.last_token_usage;if(!E)continue;h.lastAt=Math.max(h.lastAt,T),h.interior.push({...l,occurredAt:T,kind:"progressed",subject:{type:"execution",id:w},core:{measures:Vw(E)},attrs:{"codex.usage.inputTokens":Yt(E.input_tokens),"codex.usage.cachedInputTokens":Yt(E.cached_input_tokens),"codex.usage.cacheWriteInputTokens":Yt(E.cache_write_input_tokens),"codex.usage.outputTokens":Yt(E.output_tokens),"codex.usage.reasoningOutputTokens":Yt(E.reasoning_output_tokens)},provenance:m(void 0,S.ordinal),seq:`o${S.ordinal??N}`});continue}if(D==="item_completed"){const $=x.item,E=Se($?.type);if(!$||!E)continue;h.lastAt=Math.max(h.lastAt,T);let B,C;if(E==="CommandExecution"){const P=Yt($.exit_code);B={[Z.interactions]:1,...P!==0?{[Z.errors]:1}:{}},C={"codex.itemType":E,"codex.exitCode":P,...$.process_id!==void 0?{"codex.processId":$.process_id}:{},...Se($.status)?{"codex.status":$.status}:{}}}else if(E==="McpToolCall"){const P=Se($.status)==="failed"||Se($.status)==="error";B={[Z.interactions]:1,...P?{[Z.errors]:1}:{}},C={"codex.itemType":E,"codex.tool":[Se($.server),Se($.tool)].filter(Boolean).join("."),...Se($.status)?{"codex.status":$.status}:{}}}else if(E==="WebSearch")B={[Z.interactions]:1},C={"codex.itemType":E};else if(E==="FileChange"){const P=$.changes;B={[Z.interactions]:1},C={"codex.itemType":E,...P&&typeof P=="object"?{"codex.fileChanges":Object.entries(P).map(([L,te])=>({path:L,kind:Se(te?.type)}))}:{}}}else continue;h.interior.push({...l,occurredAt:T,kind:"progressed",subject:{type:"execution",id:w},core:{measures:B},attrs:C,provenance:m(Se($.id),S.ordinal),seq:`o${S.ordinal??N}`})}}if(p.length===0&&g>0)throw new Yr(`rollout has ${g} work records but no task_started marker`,e.path,o);const I=[{...l,occurredAt:a,kind:"began",subject:{type:"session",id:u},claims:[{ns:"agent.session",parts:[Lw,e.sessionId],validFrom:a,validTo:v}],core:{machineId:e.machine.id,label:c,projectLabel:e.projectLabel??(i?Ne(i):void 0),taskLabel:e.taskLabel,executor:Zo},attrs:{context:i,"codex.sessionId":e.sessionId,"codex.cliVersion":o,"codex.originator":Se(n.originator),"codex.source":Se(n.source),"codex.modelProvider":Se(n.model_provider),...Fw(n.git)},provenance:m(e.sessionId,r.ordinal),seq:"session"}];for(let N=0;N<p.length;N++){const S=p[N],T=`${u}:turn:${S.turnId}`;I.push({...l,occurredAt:S.startedAt,kind:"began",subject:{type:"execution",id:T},core:{machineId:e.machine.id,sessionId:u,label:`${c} · TURN ${N+1}`,executor:Zo,model:S.model,depth:0},attrs:{"codex.turnId":S.turnId,...S.effort?{"codex.effort":S.effort}:{}},provenance:m(S.turnId),seq:`turn:${S.turnId}`}),I.push(...S.interior),S.completedAt!==void 0?I.push({...l,occurredAt:S.completedAt,kind:"ended",subject:{type:"execution",id:T},core:{outcome:S.outcome??"completed",...S.outcome==="error"?{failureCode:"CODEX_TURN_ERROR",failureMessage:S.failureMessage??"turn failed"}:{}},provenance:m(S.turnId),seq:`turn:${S.turnId}:end`}):e.now-v>Pw&&I.push({...l,basis:"inferred",assumption:"A rollout untouched for 10 minutes belongs to a dead process, so a turn left open in it was interrupted, not still running. Its end is the last instant the rollout moved.",occurredAt:S.lastAt,kind:"ended",subject:{type:"execution",id:T},core:{outcome:"interrupted"},provenance:m(S.turnId),seq:`turn:${S.turnId}:end`})}return I}function Fw(t){if(!t||typeof t!="object")return{};const e=t;return{...Se(e.branch)?{"codex.gitBranch":e.branch}:{},...Se(e.commit_hash)?{"codex.gitCommit":e.commit_hash}:{},...Se(e.repository_url)?{"codex.gitOriginUrl":e.repository_url}:{}}}function Jl(){return process.env.CODEX_HOME||ue(xn(),".codex")}const Zm=()=>ue(Jl(),"sessions"),Ww=/^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/,Ec=new Map,Kw=new Set(["CommandExecution","McpToolCall","WebSearch","FileChange"]);function Gw(t){const e={timestamp:t.timestamp,ordinal:t.ordinal,type:t.type},r=t.payload;if(!r)return t.type==="session_meta"?{...e}:void 0;if(t.type==="session_meta"){const a=r.git;return{...e,payload:{session_id:r.session_id,id:r.id,timestamp:r.timestamp,cwd:r.cwd,originator:r.originator,cli_version:r.cli_version,source:r.source,model_provider:r.model_provider,git:a?{branch:a.branch,commit_hash:a.commit_hash,repository_url:a.repository_url}:void 0}}}if(t.type==="turn_context")return{...e,payload:{turn_id:r.turn_id,model:r.model,effort:r.effort}};if(t.type!=="event_msg")return;const n=r.type;if(n==="task_started"||n==="turn_aborted")return{...e,payload:{type:n,turn_id:r.turn_id}};if(n==="task_complete"){const a=r.error;return{...e,payload:{type:n,turn_id:r.turn_id,...a?{error:{message:a.message}}:{}}}}if(n==="token_count"){const c=r.info?.last_token_usage;return c?{...e,payload:{type:n,info:{last_token_usage:{input_tokens:c.input_tokens,cached_input_tokens:c.cached_input_tokens,cache_write_input_tokens:c.cache_write_input_tokens,output_tokens:c.output_tokens,reasoning_output_tokens:c.reasoning_output_tokens}}}}:{...e,payload:{type:n}}}if(n!=="item_completed")return;const o=r.item,s=typeof o?.type=="string"?o.type:void 0;if(!o||!s||!Kw.has(s))return{...e,payload:{type:n,item:s?{type:s}:void 0}};const i={type:s,id:o.id};if(s==="CommandExecution")i.process_id=o.process_id,i.exit_code=o.exit_code,i.status=o.status;else if(s==="McpToolCall")i.server=o.server,i.tool=o.tool,i.status=o.status;else if(s==="FileChange"){const a=o.changes;i.changes=a?Object.fromEntries(Object.entries(a).map(([c,u])=>[c,{type:u?.type}])):void 0}return{...e,payload:{type:n,item:i}}}async function qw(t,e=0){const r=[];let n=[],o=0,s=0,i=e;const a=(c,u)=>{if(u===0)return;const d=Buffer.concat(c,Math.min(u,1024)).subarray(0,1024).toString("utf8"),l=/^\s*\{\s*"timestamp"\s*:\s*"(?:\\.|[^"])*"\s*,\s*"type"\s*:\s*"([^"]+)"/.exec(d)?.[1];if(l&&l!=="session_meta"&&l!=="turn_context"&&l!=="event_msg")return;const m=Buffer.concat(c,u).toString("utf8");if(m.trim())try{const p=JSON.parse(m);if(!p||typeof p!="object")return;const h=Gw(p);h&&r.push(h)}catch{}};for await(const c of jm(t,{start:e})){const u=Buffer.isBuffer(c)?c:Buffer.from(c),d=s;s+=u.length;let l=0;for(;;){const m=u.indexOf(10,l);if(m<0)break;const p=u.subarray(l,m);a([...n,p],o+p.length),n=[],o=0,l=m+1,i=e+d+l}if(l<u.length){const m=u.subarray(l);n.push(m),o+=m.length}}return{records:r,offset:i,bytesRead:s}}function zw(t,e,r){return t.occurredAt>=e&&t.occurredAt<=r||t.subject.type==="session"&&t.kind==="began"&&(typeof t.core?.projectLabel=="string"||typeof t.core?.taskLabel=="string")}function Yw(t,e=Jl()){const r=ue(e,"state_5.sqlite");if(!ge(r))return new Map;let n;try{n=new Bs(r,{readOnly:!0}),n.exec("PRAGMA query_only = ON");const o=n.prepare("SELECT name FROM threads WHERE id = ? LIMIT 1");let s;try{s=n.prepare(`SELECT projects.name AS projectName
5
5
  FROM threads JOIN projects ON projects.id = threads.project_id
6
- WHERE threads.id = ? LIMIT 1`)}catch{}const i=new Map;for(const a of t){const c=s.get(a.sessionId),u=o?.get(a.sessionId),l=typeof c?.name=="string"?c.name.trim():"",d=typeof u?.projectName=="string"?u.projectName.trim():"";(l||d)&&i.set(a.sessionId,{...l?{taskLabel:l}:{},...d?{projectLabel:d}:{}})}return i}catch{return new Map}finally{n?.close()}}function v0(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function b0(t,e){if(e?.trim())return e.trim();const r=t.find(o=>o.type==="session_meta"),n=v0(r?.payload?.cwd);if(!n)return;if(fe(se(n,".git")))return Ce(n);const s=new Map;for(const o of t){if(o.type!=="event_msg"||o.payload?.type!=="item_completed")continue;const i=o.payload.item;if(i?.type!=="FileChange")continue;const a=i.changes;for(const c of Object.keys(a??{})){if(!Pc(c))continue;const u=cc(n,c);if(!u||u===".."||u.startsWith(`..${Lc}`)||Pc(u))continue;const l=u.split(Lc).filter(Boolean)[0];if(!l||l.startsWith("."))continue;const d=se(n,l);let m;if(fe(se(d,".git")))m=d;else{let y=ii(c);for(;y!==n&&cc(n,y)&&!cc(n,y).startsWith("..");){fe(se(y,".git"))&&(m=y);const v=ii(y);if(v===y)break;y=v}}const p=m?Ce(m):l;s.set(p,(s.get(p)??0)+1)}}return[...s.entries()].sort(([o,i],[a,c])=>c-i||o.localeCompare(a))[0]?.[0]??Ce(n)}async function Om(){const t=Cm();if(!fe(t))return[];const e=[];let r;try{r=await Ge(t)}catch{return e}for(const n of r){let s;try{s=await Ge(se(t,n))}catch{continue}for(const o of s){let i;try{i=await Ge(se(t,n,o))}catch{continue}for(const a of i){let c;try{c=await Ge(se(t,n,o,a))}catch{continue}for(const u of c){const l=f0.exec(u);l&&e.push({path:se(t,n,o,a,u),sessionId:l[1]})}}}}return e}async function Nm(t,e){const r=_r(),n=Date.now(),s={envelopes:[],rolloutsRead:0,rolloutsFailed:0,problems:[],storedAvailable:!1},o=await Om();if(o.length===0)return s.storedAvailable=fe(Cm()),s;s.storedAvailable=!0;const i=g0(o);for(const a of o){let c;try{c=await zr(a.path)}catch{continue}if(c.mtimeMs<t)continue;const u=i.get(a.sessionId),l=`${u?.projectLabel??""}:${u?.taskLabel??""}`;let d=lc.get(a.path);d&&c.size<d.offset&&(lc.delete(a.path),d=void 0);let m;const p=await m0(a.path,d?.offset??0),y=d?p.records.length>0?[...d.records,...p.records]:d.records:p.records,v=!d||p.offset!==d.offset;if(d&&!v&&d.annotationStamp===l)m=d.envelopes;else try{const g=b0(y,u?.projectLabel);m=l0(y,{machine:r,host:Rr(),observedAt:n,path:a.path,sessionId:a.sessionId,now:n,projectLabel:g,taskLabel:u?.taskLabel}).map(Wt),lc.set(a.path,{offset:p.offset,records:y,annotationStamp:l,envelopes:m})}catch(g){s.rolloutsFailed++,s.problems.push({path:a.path,message:g instanceof Error?g.message:String(g),sourceVersion:g instanceof kn?g.sourceVersion:void 0});continue}s.rolloutsRead++;for(const g of m)y0(g,t,e)&&s.envelopes.push(g)}return s}async function w0(t,e){return(await Nm(t,e)).envelopes}async function uf(){const t=$l(),e=(await Om()).length;return{available:e>0,present:fe(t),home:t,rollouts:e}}const Pn="cursor",A0={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"unsupported",context:"partial",outcome:"partial"},S0="cursor";class Jo extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="CursorFormatError"}path;sourceVersion}const Vc=t=>`cursor:${t}`,Vr=t=>typeof t=="string"&&t?t:void 0,Lo=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,lf=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function Tm(t,e){if(typeof t.composerId!="string"||!t.composerId)throw new Jo("composer header has no composerId",e);if(typeof t.createdAt!="number"||!Number.isFinite(t.createdAt))throw new Jo("composer header has no numeric createdAt",e);if(typeof t.lastUpdatedAt!="number"||!Number.isFinite(t.lastUpdatedAt))throw new Jo("composer header has no numeric lastUpdatedAt",e)}function k0(t,e){Tm(t,e.path);const r=t.value??{},n=r.subagentInfo,s=n?Vr(n.parentComposerId):void 0,o=e.workspacePath??"",i=Vr(r.name)?.toUpperCase()??(o?Ce(o).toUpperCase():"CURSOR");return{source:{id:Pn,instance:e.host},occurredAt:t.createdAt,observedAt:e.observedAt,clock:"wall",stratum:"stored-semantics",kind:"began",subject:{type:"session",id:Vc(t.composerId)},claims:[{ns:"agent.session",parts:[S0,t.composerId],validFrom:t.createdAt,validTo:t.lastUpdatedAt}],basis:"measured",core:{machineId:e.machine.id,label:i,projectLabel:o?Ce(o):void 0,taskLabel:Vr(r.name),executor:Pn,...s?{parentId:Vc(s)}:{}},attrs:{context:o,"cursor.composerId":t.composerId,"cursor.workspaceId":t.workspaceId,"cursor.isSubagent":t.isSubagent,...n?{"cursor.parentComposerId":Vr(n.parentComposerId),"cursor.subagentType":Vr(n.subagentTypeName)}:{},...Lo(r.totalLinesAdded)!==void 0?{"cursor.linesAdded":r.totalLinesAdded}:{},...Lo(r.totalLinesRemoved)!==void 0?{"cursor.linesRemoved":r.totalLinesRemoved}:{},...Lo(r.filesChangedCount)!==void 0?{"cursor.filesChanged":r.filesChangedCount}:{},...Vr(r.unifiedMode)?{"cursor.mode":r.unifiedMode}:{},...Lo(r._v)!==void 0?{"cursor.schemaVersion":r._v}:{}},provenance:{path:e.path,recordId:t.composerId},seq:"composer"}}const df="Cursor persists no turn timing: the bounds are the first and last timestamped records inside the turn, untimestamped activity may extend beyond them, and the turn is taken as completed because Cursor records no turn outcome.";function x0(t,e,r){Tm(t,r.path);const n=Vc(t.composerId),o={source:{id:Pn,instance:r.host},observedAt:r.observedAt,clock:"wall",stratum:"stored-semantics"},i=l=>({path:r.path,...l?{recordId:l}:{}}),a=[];for(let l=0;l<e.length;l++)e[l].type===1&&a.push(l);const c=[];let u=0;for(let l=0;l<a.length;l++){const d=a[l],m=l+1<a.length?a[l+1]:e.length,p=l+1,y=e.slice(d,m),v=y.map(k=>({bubble:k,at:lf(k.createdAt)})).filter(k=>k.at!==void 0);if(v.length<2){u++;continue}const g=Math.min(...v.map(k=>k.at)),C=Math.max(...v.map(k=>k.at)),A=`${n}:turn:${p}`,I=y.filter(k=>k.toolName&&lf(k.createdAt)===void 0),B=I.filter(k=>k.toolStatus==="error").length;c.push({...o,occurredAt:g,kind:"began",subject:{type:"execution",id:A},basis:"inferred",assumption:df,core:{machineId:r.machine.id,sessionId:n,label:`${Vr(t.value?.name)?.toUpperCase()??"CURSOR"} · TURN ${p}`,executor:Pn,depth:t.isSubagent?1:0,...I.length?{measures:{[z.interactions]:I.length,...B?{[z.errors]:B}:{}}}:{}},attrs:{"cursor.turn":p},provenance:i(e[d].bubbleId),seq:`turn:${p}`});for(const{bubble:k,at:T}of v){if(!k.toolName)continue;const S=k.toolStatus==="error",E={[z.interactions]:1,...S?{[z.errors]:1}:{}};c.push({...o,occurredAt:T,kind:"progressed",subject:{type:"execution",id:A},basis:"measured",core:{measures:E},attrs:{"cursor.tool":k.toolName,...k.toolStatus?{"cursor.toolStatus":k.toolStatus}:{}},provenance:i(k.bubbleId),seq:k.bubbleId})}c.push({...o,occurredAt:C,kind:"ended",subject:{type:"execution",id:A},basis:"inferred",assumption:df,core:{outcome:"completed"},provenance:i(e[d].bubbleId),seq:`turn:${p}:end`})}return{drafts:c,turns:a.length,untimedTurns:u}}function Ps(){return process.env.CURSOR_GLOBAL_STORAGE||se(hn(),"Library","Application Support","Cursor","User","globalStorage")}function E0(){return process.env.CURSOR_WORKSPACE_STORAGE||se(Ps(),"..","workspaceStorage")}const Bm=()=>se(Ps(),"state.vscdb"),ff=new Map;async function I0(){const t=new Map,e=E0();if(!fe(e))return t;let r;try{r=await Ge(e)}catch{return t}for(const n of r)try{const s=JSON.parse(await Nr(se(e,n,"workspace.json"),"utf8"));typeof s.folder=="string"&&s.folder.startsWith("file://")&&t.set(n,decodeURIComponent(s.folder.slice(7)))}catch{continue}return t}function C0(t,e){let r;if(t.value)try{r=JSON.parse(t.value)}catch{r=void 0}const n=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0,s=t.lastUpdatedAt??n(r?.lastUpdatedAt)??n(r?.conversationCheckpointLastUpdatedAt)??t.createdAt??NaN,o={composerId:t.composerId,workspaceId:t.workspaceId??void 0,createdAt:t.createdAt??NaN,lastUpdatedAt:s,isSubagent:t.isSubagent===1,value:r};if(!Number.isFinite(o.createdAt)||!Number.isFinite(o.lastUpdatedAt))throw new Jo(`composer ${t.composerId} has no numeric createdAt/lastUpdatedAt`,e);return o}function O0(t,e){const r=t.prepare("SELECT value FROM cursorDiskKV WHERE key = ?").get(`composerData:${e}`);if(!r?.value)return[];const n=typeof r.value=="string"?r.value:Buffer.from(r.value).toString("utf8"),o=JSON.parse(n).fullConversationHeadersOnly??[],i=t.prepare("SELECT key, value FROM cursorDiskKV WHERE key >= ? AND key < ?").all(`bubbleId:${e}:`,`bubbleId:${e};`),a=new Map;for(const c of i){const u=c.key.slice(`bubbleId:${e}:`.length);try{const l=typeof c.value=="string"?c.value:Buffer.from(c.value).toString("utf8"),d=JSON.parse(l);a.set(u,{bubbleId:u,type:d.type,createdAt:typeof d.createdAt=="string"&&d.createdAt?d.createdAt:void 0,toolName:d.toolFormerData?.name,toolStatus:d.toolFormerData?.status})}catch{continue}}return o.filter(c=>typeof c.bubbleId=="string").map(c=>a.get(c.bubbleId)??{bubbleId:c.bubbleId,type:c.type})}async function $m(t,e){const r=_r(),n=Date.now(),s=Bm(),o={envelopes:[],composersRead:0,composersFailed:0,problems:[],storedAvailable:!1};if(!fe(s))return o;o.storedAvailable=!0;const i=await I0();let a;try{a=new go(s,{readOnly:!0})}catch(c){return o.problems.push({path:s,message:`cannot open read-only: ${String(c)}`}),o}try{let c;try{c=a.prepare("SELECT composerId, workspaceId, createdAt, lastUpdatedAt, isSubagent, value FROM composerHeaders WHERE (lastUpdatedAt >= ? OR lastUpdatedAt IS NULL) AND createdAt <= ?").all(t,e)}catch(u){return o.problems.push({path:s,message:`composerHeaders unreadable: ${String(u)}`}),o}for(const u of c)try{const l=C0(u,s);if(l.lastUpdatedAt<t)continue;const d={machine:r,host:Rr(),observedAt:n,path:s,workspacePath:l.workspaceId?i.get(l.workspaceId):void 0};o.envelopes.push(Wt(k0(l,d)));const m=`${l.lastUpdatedAt}`,p=ff.get(l.composerId);let y;if(p&&p.stamp===m)y=p.envelopes;else{const v=O0(a,l.composerId),{drafts:g}=x0(l,v,d);y=g.map(Wt),ff.set(l.composerId,{stamp:m,envelopes:y})}for(const v of y)v.occurredAt>=t&&v.occurredAt<=e&&o.envelopes.push(v);o.composersRead++}catch(l){o.composersFailed++,o.problems.push({path:s,message:`${u.composerId}: ${l instanceof Error?l.message:String(l)}`})}}finally{a.close()}return o}async function N0(t,e){return(await $m(t,e)).envelopes}async function pf(){const t=Bm();if(!fe(t))return{available:!1,present:!1,globalStorage:Ps()};try{const e=new go(t,{readOnly:!0});try{const r=e.prepare("SELECT count(*) AS n FROM composerHeaders").get();return{available:r.n>0,present:!0,globalStorage:Ps(),composers:r.n}}finally{e.close()}}catch{return{available:!1,present:!0,globalStorage:Ps()}}}const Ls="gemini",T0={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"unsupported",model:"supported",context:"partial",outcome:"partial"},B0="gemini";class di extends Error{constructor(e,r){super(e),this.path=r,this.name="GeminiFormatError"}path}const $0="The session file has not been written to for longer than the live window, so the runtime that owned it is gone and the turn ended at its last message.";function R0(t){return(typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(r=>r?.text).filter(r=>typeof r=="string").join(`
6
+ WHERE threads.id = ? LIMIT 1`)}catch{}const i=new Map;for(const a of t){const c=o.get(a.sessionId),u=s?.get(a.sessionId),d=typeof c?.name=="string"?c.name.trim():"",l=typeof u?.projectName=="string"?u.projectName.trim():"";(d||l)&&i.set(a.sessionId,{...d?{taskLabel:d}:{},...l?{projectLabel:l}:{}})}return i}catch{return new Map}finally{n?.close()}}function Xw(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function Jw(t,e){if(e?.trim())return e.trim();const r=t.find(s=>s.type==="session_meta"),n=Xw(r?.payload?.cwd);if(!n)return;if(ge(ue(n,".git")))return Ne(n);const o=new Map;for(const s of t){if(s.type!=="event_msg"||s.payload?.type!=="item_completed")continue;const i=s.payload.item;if(i?.type!=="FileChange")continue;const a=i.changes;for(const c of Object.keys(a??{})){if(!tu(c))continue;const u=Sc(n,c);if(!u||u===".."||u.startsWith(`..${ru}`)||tu(u))continue;const d=u.split(ru).filter(Boolean)[0];if(!d||d.startsWith("."))continue;const l=ue(n,d);let m;if(ge(ue(l,".git")))m=l;else{let h=vi(c);for(;h!==n&&Sc(n,h)&&!Sc(n,h).startsWith("..");){ge(ue(h,".git"))&&(m=h);const v=vi(h);if(v===h)break;h=v}}const p=m?Ne(m):d;o.set(p,(o.get(p)??0)+1)}}return[...o.entries()].sort(([s,i],[a,c])=>c-i||s.localeCompare(a))[0]?.[0]??Ne(n)}async function Qm(){const t=Zm();if(!ge(t))return[];const e=[];let r;try{r=await Ze(t)}catch{return e}for(const n of r){let o;try{o=await Ze(ue(t,n))}catch{continue}for(const s of o){let i;try{i=await Ze(ue(t,n,s))}catch{continue}for(const a of i){let c;try{c=await Ze(ue(t,n,s,a))}catch{continue}for(const u of c){const d=Ww.exec(u);d&&e.push({path:ue(t,n,s,a,u),sessionId:d[1]})}}}}return e}async function ey(t,e){const r=Vr(),n=Date.now(),o={envelopes:[],rolloutsRead:0,rolloutsFailed:0,problems:[],storedAvailable:!1},s=await Qm();if(s.length===0)return o.storedAvailable=ge(Zm()),o;o.storedAvailable=!0;const i=Yw(s);for(const a of s){let c;try{c=await sn(a.path)}catch{continue}if(c.mtimeMs<t)continue;const u=i.get(a.sessionId),d=`${u?.projectLabel??""}:${u?.taskLabel??""}`;let l=Ec.get(a.path);l&&c.size<l.offset&&(Ec.delete(a.path),l=void 0);let m;const p=await qw(a.path,l?.offset??0),h=l?p.records.length>0?[...l.records,...p.records]:l.records:p.records,v=!l||p.offset!==l.offset;if(l&&!v&&l.annotationStamp===d)m=l.envelopes;else try{const g=Jw(h,u?.projectLabel);m=Hw(h,{machine:r,host:Ur(),observedAt:n,path:a.path,sessionId:a.sessionId,now:n,projectLabel:g,taskLabel:u?.taskLabel}).map(Zt),Ec.set(a.path,{offset:p.offset,records:h,annotationStamp:d,envelopes:m})}catch(g){o.rolloutsFailed++,o.problems.push({path:a.path,message:g instanceof Error?g.message:String(g),sourceVersion:g instanceof Yr?g.sourceVersion:void 0});continue}o.rolloutsRead++;for(const g of m)zw(g,t,e)&&o.envelopes.push(g)}return o}async function Zw(t,e){return(await ey(t,e)).envelopes}async function $f(){const t=Jl(),e=(await Qm()).length;return{available:e>0,present:ge(t),home:t,rollouts:e}}const Xn="cursor",Qw={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"unsupported",context:"partial",outcome:"partial"},e0="cursor";class ui extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="CursorFormatError"}path;sourceVersion}const ou=t=>`cursor:${t}`,Xr=t=>typeof t=="string"&&t?t:void 0,Js=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Bf=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function ty(t,e){if(typeof t.composerId!="string"||!t.composerId)throw new ui("composer header has no composerId",e);if(typeof t.createdAt!="number"||!Number.isFinite(t.createdAt))throw new ui("composer header has no numeric createdAt",e);if(typeof t.lastUpdatedAt!="number"||!Number.isFinite(t.lastUpdatedAt))throw new ui("composer header has no numeric lastUpdatedAt",e)}function t0(t,e){ty(t,e.path);const r=t.value??{},n=r.subagentInfo,o=n?Xr(n.parentComposerId):void 0,s=e.workspacePath??"",i=Xr(r.name)?.toUpperCase()??(s?Ne(s).toUpperCase():"CURSOR");return{source:{id:Xn,instance:e.host},occurredAt:t.createdAt,observedAt:e.observedAt,clock:"wall",stratum:"stored-semantics",kind:"began",subject:{type:"session",id:ou(t.composerId)},claims:[{ns:"agent.session",parts:[e0,t.composerId],validFrom:t.createdAt,validTo:t.lastUpdatedAt}],basis:"measured",core:{machineId:e.machine.id,label:i,projectLabel:s?Ne(s):void 0,taskLabel:Xr(r.name),executor:Xn,...o?{parentId:ou(o)}:{}},attrs:{context:s,"cursor.composerId":t.composerId,"cursor.workspaceId":t.workspaceId,"cursor.isSubagent":t.isSubagent,...n?{"cursor.parentComposerId":Xr(n.parentComposerId),"cursor.subagentType":Xr(n.subagentTypeName)}:{},...Js(r.totalLinesAdded)!==void 0?{"cursor.linesAdded":r.totalLinesAdded}:{},...Js(r.totalLinesRemoved)!==void 0?{"cursor.linesRemoved":r.totalLinesRemoved}:{},...Js(r.filesChangedCount)!==void 0?{"cursor.filesChanged":r.filesChangedCount}:{},...Xr(r.unifiedMode)?{"cursor.mode":r.unifiedMode}:{},...Js(r._v)!==void 0?{"cursor.schemaVersion":r._v}:{}},provenance:{path:e.path,recordId:t.composerId},seq:"composer"}}const Rf="Cursor persists no turn timing: the bounds are the first and last timestamped records inside the turn, untimestamped activity may extend beyond them, and the turn is taken as completed because Cursor records no turn outcome.";function r0(t,e,r){ty(t,r.path);const n=ou(t.composerId),s={source:{id:Xn,instance:r.host},observedAt:r.observedAt,clock:"wall",stratum:"stored-semantics"},i=d=>({path:r.path,...d?{recordId:d}:{}}),a=[];for(let d=0;d<e.length;d++)e[d].type===1&&a.push(d);const c=[];let u=0;for(let d=0;d<a.length;d++){const l=a[d],m=d+1<a.length?a[d+1]:e.length,p=d+1,h=e.slice(l,m),v=h.map(x=>({bubble:x,at:Bf(x.createdAt)})).filter(x=>x.at!==void 0);if(v.length<2){u++;continue}const g=Math.min(...v.map(x=>x.at)),I=Math.max(...v.map(x=>x.at)),N=`${n}:turn:${p}`,S=h.filter(x=>x.toolName&&Bf(x.createdAt)===void 0),T=S.filter(x=>x.toolStatus==="error").length;c.push({...s,occurredAt:g,kind:"began",subject:{type:"execution",id:N},basis:"inferred",assumption:Rf,core:{machineId:r.machine.id,sessionId:n,label:`${Xr(t.value?.name)?.toUpperCase()??"CURSOR"} · TURN ${p}`,executor:Xn,depth:t.isSubagent?1:0,...S.length?{measures:{[Z.interactions]:S.length,...T?{[Z.errors]:T}:{}}}:{}},attrs:{"cursor.turn":p},provenance:i(e[l].bubbleId),seq:`turn:${p}`});for(const{bubble:x,at:D}of v){if(!x.toolName)continue;const w=x.toolStatus==="error",$={[Z.interactions]:1,...w?{[Z.errors]:1}:{}};c.push({...s,occurredAt:D,kind:"progressed",subject:{type:"execution",id:N},basis:"measured",core:{measures:$},attrs:{"cursor.tool":x.toolName,...x.toolStatus?{"cursor.toolStatus":x.toolStatus}:{}},provenance:i(x.bubbleId),seq:x.bubbleId})}c.push({...s,occurredAt:I,kind:"ended",subject:{type:"execution",id:N},basis:"inferred",assumption:Rf,core:{outcome:"completed"},provenance:i(e[l].bubbleId),seq:`turn:${p}:end`})}return{drafts:c,turns:a.length,untimedTurns:u}}function Qo(){return process.env.CURSOR_GLOBAL_STORAGE||ue(xn(),"Library","Application Support","Cursor","User","globalStorage")}function n0(){return process.env.CURSOR_WORKSPACE_STORAGE||ue(Qo(),"..","workspaceStorage")}const ry=()=>ue(Qo(),"state.vscdb"),Mf=new Map;async function o0(){const t=new Map,e=n0();if(!ge(e))return t;let r;try{r=await Ze(e)}catch{return t}for(const n of r)try{const o=JSON.parse(await _r(ue(e,n,"workspace.json"),"utf8"));typeof o.folder=="string"&&o.folder.startsWith("file://")&&t.set(n,decodeURIComponent(o.folder.slice(7)))}catch{continue}return t}function s0(t,e){let r;if(t.value)try{r=JSON.parse(t.value)}catch{r=void 0}const n=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0,o=t.lastUpdatedAt??n(r?.lastUpdatedAt)??n(r?.conversationCheckpointLastUpdatedAt)??t.createdAt??NaN,s={composerId:t.composerId,workspaceId:t.workspaceId??void 0,createdAt:t.createdAt??NaN,lastUpdatedAt:o,isSubagent:t.isSubagent===1,value:r};if(!Number.isFinite(s.createdAt)||!Number.isFinite(s.lastUpdatedAt))throw new ui(`composer ${t.composerId} has no numeric createdAt/lastUpdatedAt`,e);return s}function i0(t,e){const r=t.prepare("SELECT value FROM cursorDiskKV WHERE key = ?").get(`composerData:${e}`);if(!r?.value)return[];const n=typeof r.value=="string"?r.value:Buffer.from(r.value).toString("utf8"),s=JSON.parse(n).fullConversationHeadersOnly??[],i=t.prepare("SELECT key, value FROM cursorDiskKV WHERE key >= ? AND key < ?").all(`bubbleId:${e}:`,`bubbleId:${e};`),a=new Map;for(const c of i){const u=c.key.slice(`bubbleId:${e}:`.length);try{const d=typeof c.value=="string"?c.value:Buffer.from(c.value).toString("utf8"),l=JSON.parse(d);a.set(u,{bubbleId:u,type:l.type,createdAt:typeof l.createdAt=="string"&&l.createdAt?l.createdAt:void 0,toolName:l.toolFormerData?.name,toolStatus:l.toolFormerData?.status})}catch{continue}}return s.filter(c=>typeof c.bubbleId=="string").map(c=>a.get(c.bubbleId)??{bubbleId:c.bubbleId,type:c.type})}async function ny(t,e){const r=Vr(),n=Date.now(),o=ry(),s={envelopes:[],composersRead:0,composersFailed:0,problems:[],storedAvailable:!1};if(!ge(o))return s;s.storedAvailable=!0;const i=await o0();let a;try{a=new Bs(o,{readOnly:!0})}catch(c){return s.problems.push({path:o,message:`cannot open read-only: ${String(c)}`}),s}try{let c;try{c=a.prepare("SELECT composerId, workspaceId, createdAt, lastUpdatedAt, isSubagent, value FROM composerHeaders WHERE (lastUpdatedAt >= ? OR lastUpdatedAt IS NULL) AND createdAt <= ?").all(t,e)}catch(u){return s.problems.push({path:o,message:`composerHeaders unreadable: ${String(u)}`}),s}for(const u of c)try{const d=s0(u,o);if(d.lastUpdatedAt<t)continue;const l={machine:r,host:Ur(),observedAt:n,path:o,workspacePath:d.workspaceId?i.get(d.workspaceId):void 0};s.envelopes.push(Zt(t0(d,l)));const m=`${d.lastUpdatedAt}`,p=Mf.get(d.composerId);let h;if(p&&p.stamp===m)h=p.envelopes;else{const v=i0(a,d.composerId),{drafts:g}=r0(d,v,l);h=g.map(Zt),Mf.set(d.composerId,{stamp:m,envelopes:h})}for(const v of h)v.occurredAt>=t&&v.occurredAt<=e&&s.envelopes.push(v);s.composersRead++}catch(d){s.composersFailed++,s.problems.push({path:o,message:`${u.composerId}: ${d instanceof Error?d.message:String(d)}`})}}finally{a.close()}return s}async function a0(t,e){return(await ny(t,e)).envelopes}async function _f(){const t=ry();if(!ge(t))return{available:!1,present:!1,globalStorage:Qo()};try{const e=new Bs(t,{readOnly:!0});try{const r=e.prepare("SELECT count(*) AS n FROM composerHeaders").get();return{available:r.n>0,present:!0,globalStorage:Qo(),composers:r.n}}finally{e.close()}}catch{return{available:!1,present:!0,globalStorage:Qo()}}}const es="gemini",c0={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"unsupported",model:"supported",context:"partial",outcome:"partial"},u0="gemini";class Ei extends Error{constructor(e,r){super(e),this.path=r,this.name="GeminiFormatError"}path}const l0="The session file has not been written to for longer than the live window, so the runtime that owned it is gone and the turn ended at its last message.";function d0(t){return(typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(r=>r?.text).filter(r=>typeof r=="string").join(`
7
7
  `):"").split(`
8
- `)[0].trim().slice(0,200)||"Gemini reported an error"}const _0=t=>`gemini:${t}`,Ht=t=>typeof t=="number"&&Number.isFinite(t)?t:0,Uo=t=>typeof t=="string"&&t?t:void 0,An=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function M0(t,e){const r=t.split(`
9
- `).filter(a=>a.trim());if(r.length===0)throw new di("session file is empty",e);let n=null;const s=[],o=new Map,i=a=>{const c=a;!c||typeof c!="object"||typeof c.id!="string"||(o.has(c.id)||s.push(c.id),o.set(c.id,c))};for(const a of r){let c;try{c=JSON.parse(a)}catch{continue}if(!c||typeof c!="object")continue;const u=c;if(!n&&typeof u.sessionId=="string"){n=u;continue}const l=u.$set;if(l){const d=l.messages;if(Array.isArray(d))for(const m of d)i(m);continue}typeof u.id=="string"&&i(u)}if(!n||!n.sessionId)throw new di("session file has no header with a sessionId",e);return{header:n,messages:s.map(a=>o.get(a))}}const Rm=t=>Array.isArray(t.content)&&t.content.some(e=>!!e&&typeof e=="object"&&"functionResponse"in e);function j0(t){if(t.type!=="user"||Rm(t))return!1;const e=Array.isArray(t.content)?t.content.map(n=>n?.text).filter(n=>typeof n=="string"):[];if(e.length===0)return!1;const r=e[0];return!r.startsWith("<session_context>")&&!r.startsWith("[System:")}function D0(t){const e=Ht(t.input),r=Ht(t.cached);return{[z.tokensInput]:Math.max(0,e-r),[z.tokensOutput]:Ht(t.output)+Ht(t.thoughts),[z.tokensCacheRead]:r,[z.tokensReasoning]:Ht(t.thoughts),[z.steps]:1}}function P0(t,e){const{header:r,messages:n}=t,s=r.sessionId,o=An(r.startTime);if(o===void 0)throw new di("session header has no parseable startTime",e.path);const i=n.filter(g=>An(g.timestamp)!==void 0),a=i.length?Math.max(...i.map(g=>An(g.timestamp))):o,c=e.workspacePath??"",u=c?Ce(c).toUpperCase():"GEMINI",l=_0(s),m={source:{id:Ls,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},p=g=>({path:e.path,...g?{recordId:g}:{}}),y=[{...m,occurredAt:o,kind:"began",subject:{type:"session",id:l},claims:[{ns:"agent.session",parts:[B0,s],validFrom:o,validTo:a}],core:{machineId:e.machine.id,label:u,projectLabel:c?Ce(c):void 0,executor:Ls},attrs:{context:c,"gemini.sessionId":s,"gemini.projectHash":r.projectHash,...Uo(r.kind)?{"gemini.kind":r.kind}:{}},provenance:p(s),seq:"session"}],v=[];for(let g=0;g<n.length;g++)j0(n[g])&&An(n[g].timestamp)!==void 0&&v.push(g);if(v.length===0){if(n.some(g=>g.type==="gemini"))throw new di(`session has ${n.length} messages including model output but no recognisable user prompt`,e.path);return y}for(let g=0;g<v.length;g++){const C=v[g],A=g+1<v.length?v[g+1]:n.length,I=g+1,B=`${l}:turn:${I}`,k=An(n[C].timestamp);let T=k,S,E;const R=[];for(let re=C;re<A;re++){const F=n[re],W=An(F.timestamp);if(W===void 0||F.type!=="gemini"&&F.type!=="error"&&!(F.type==="user"&&Rm(F))||(W>T&&(T=W),E=F,F.type!=="gemini"))continue;S??=Uo(F.model);const ee=Array.isArray(F.toolCalls)?F.toolCalls:[],he=F.tokens?D0(F.tokens):{};ee.length&&(he[z.interactions]=ee.length),Object.keys(he).length!==0&&R.push({...m,occurredAt:W,kind:"progressed",subject:{type:"execution",id:B},core:{measures:he},attrs:{...ee.length?{"gemini.tools":ee.map($e=>Uo($e.name)??"unknown")}:{},...Uo(F.model)?{"gemini.model":F.model}:{},...F.tokens?{"gemini.usage.input":Ht(F.tokens.input),"gemini.usage.output":Ht(F.tokens.output),"gemini.usage.cached":Ht(F.tokens.cached),"gemini.usage.thoughts":Ht(F.tokens.thoughts),"gemini.usage.tool":Ht(F.tokens.tool)}:{}},provenance:p(F.id),seq:F.id})}y.push({...m,occurredAt:k,kind:"began",subject:{type:"execution",id:B},core:{machineId:e.machine.id,sessionId:l,label:`${u} · TURN ${I}`,executor:Ls,model:S,depth:0},attrs:{"gemini.turn":I},provenance:p(n[C].id),seq:`turn:${I}`}),y.push(...R);const j=E?.type==="error",M=E?.type==="gemini"&&!(Array.isArray(E.toolCalls)&&E.toolCalls.length),J=g+1<v.length,le=(re,F)=>({...m,occurredAt:T,kind:"ended",subject:{type:"execution",id:B},core:re,...F?{basis:"inferred",assumption:$0}:{},provenance:p(n[C].id),seq:`turn:${I}:end`});j?y.push(le({outcome:"error",failureMessage:R0(E)},!1)):J||M&&e.settled?y.push(le({outcome:"completed"},!1)):e.closeOpenTurns&&y.push(le({outcome:M?"completed":"interrupted"},!0))}return y}const L0=3e3;function Rl(){return process.env.GEMINI_HOME||se(hn(),".gemini")}const _m=()=>se(Rl(),"tmp"),hf=new Map;async function U0(){const t=new Map;try{const e=JSON.parse(await Nr(se(Rl(),"projects.json"),"utf8"));for(const[r,n]of Object.entries(e.projects??{}))typeof n=="string"&&t.set(n,r)}catch{}return t}async function Mm(){const t=_m();if(!fe(t))return[];const e=[];let r;try{r=await Ge(t)}catch{return e}for(const n of r){let s;try{s=await Ge(se(t,n,"chats"))}catch{continue}for(const o of s)o.startsWith("session-")&&o.endsWith(".jsonl")&&e.push({path:se(t,n,"chats",o),slug:n})}return e}async function jm(t,e){const r=_r(),n=Date.now(),s={envelopes:[],sessionsRead:0,sessionsFailed:0,problems:[],storedAvailable:!1},o=await Mm();if(o.length===0)return s.storedAvailable=fe(_m()),s;s.storedAvailable=!0;const i=await U0();for(const a of o){let c;try{c=await zr(a.path)}catch{continue}if(c.mtimeMs<t)continue;const u=Date.now()-c.mtimeMs,l=u>L0,d=u>Tl,m=`${c.mtimeMs}:${c.size}:${l}:${d}`,p=hf.get(a.path);let y;if(p&&p.stamp===m)y=p.envelopes;else try{const v=M0(await Nr(a.path,"utf8"),a.path);y=P0(v,{machine:r,host:Rr(),observedAt:n,path:a.path,workspacePath:i.get(a.slug),settled:l,closeOpenTurns:d}).map(Wt),hf.set(a.path,{stamp:m,envelopes:y})}catch(v){s.sessionsFailed++,s.problems.push({path:a.path,message:v instanceof Error?v.message:String(v)});continue}s.sessionsRead++;for(const v of y)v.occurredAt>=t&&v.occurredAt<=e&&s.envelopes.push(v)}return s}async function V0(t,e){return(await jm(t,e)).envelopes}async function mf(){const t=Rl(),e=(await Mm()).length;return{available:e>0,present:fe(t),home:t,sessions:e}}const H0=new Set(["running","waiting"]);function Dm(t){return H0.has(t)}function Pm(t,e){return{now:t,dayStart:t,dayEnd:e,machines:new Map,sources:new Map,sessions:new Map,executions:new Map,processes:new Map,artifacts:new Map,transfers:new Map,relationships:[],active:new Set,seen:new Set}}const F0=5*6e4;function W0(t){const e=[];for(const r of t)r.parentId&&e.push({from:{type:"session",id:r.parentId},to:{type:"session",id:r.id},kind:"spawned",basis:"measured",via:"recorded by the child session's own runtime"});return e}function K0(t,e){const r=t.now-F0,n=new Set;for(const a of e)a.from.type==="process"&&n.add(a.from.id),a.to.type==="process"&&n.add(a.to.id);const s=[];let o=0,i=0;for(const a of t.processes.values())a.lastSeenAt>=r&&o++,a.endInferred&&i++,n.has(a.id)&&s.push(a);return{now:t.now,dayStart:t.dayStart,dayEnd:t.dayEnd,machines:[...t.machines.values()],sources:[...t.sources.values()],sessions:[...t.sessions.values()],executions:[...t.executions.values()],processes:s,processTotals:{observed:t.processes.size,recentlySeen:o,exitsInferred:i},relationships:[...e,...W0(t.sessions.values())]}}function yf(t){const e=Pm(t.dayStart,t.dayEnd);e.now=t.now;for(const r of t.machines)e.machines.set(r.id,r);for(const r of t.sources)e.sources.set(`${r.id}:${r.instance}`,r);for(const r of t.sessions)e.sessions.set(r.id,r);for(const r of t.executions)e.executions.set(r.id,r),Dm(r.status)&&e.active.add(r.id);for(const r of t.processes)e.processes.set(r.id,r);return e.processTotals=t.processTotals,e.relationships=t.relationships,e}function Ot(t,e){const r=t[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function fi(t,e){for(const[r,n]of Object.entries(e)){if(typeof n!="number"||!Number.isFinite(n))continue;const s=r;t[s]=(t[s]??0)+n}}const G0=[z.tokensInput,z.tokensOutput,z.tokensCacheRead];function ur(t){let e=0,r=!1;for(const n of G0){const s=Ot(t,n);s!==void 0&&(r=!0,e+=s)}return r?e:void 0}function Lm(t){return{input:Ot(t,z.tokensInput)??0,output:Ot(t,z.tokensOutput)??0,cacheRead:Ot(t,z.tokensCacheRead)??0,reasoning:Ot(t,z.tokensReasoning)??0}}function Um(t){const e=ur(t.measures);if(e!==void 0)return gf(e/1e3,200);const r=Ot(t.measures,z.cpuMs);if(r!==void 0)return gf(r/1e3,200)}function es(t){return Ot(t.measures,z.interactions)}function Vm(t){return Ot(t.measures,z.steps)??0}function Hc(t){return Ot(t.measures,z.errors)??0}function Fc(t){return Ot(t.measures,z.retries)??0}function gf(t,e){return Math.min(1,Math.log1p(Math.max(0,t))/Math.log1p(e))}function q0(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return e>>>0}function pi(t,e=0){return q0(t+"#"+e)%1e5/1e5}const dc=[{x:430,y:508,extentX:300,extentY:186},{x:838,y:322,extentX:186,extentY:116}];function z0(t){if(t<dc.length)return dc[t];const r=-.9+(t-dc.length)*1.15;return{x:620+Math.cos(r)*520,y:300+Math.sin(r)*250,extentX:150,extentY:94}}function Y0(t){const e=r=>r==="laptop"?0:r==="desktop"?1:2;return[...t].sort((r,n)=>e(r.kind)-e(n.kind)||r.firstSeenAt-n.firstSeenAt||(r.id<n.id?-1:r.id>n.id?1:0))}function vf(t,e){const r=pi(e,1),n=pi(e,2),s=r*Math.PI*2+n*2.399963,o=.34+.46*Math.sqrt(n);return{x:t.x+Math.cos(s)*t.extentX*o,y:t.y+Math.sin(s)*t.extentY*o}}const bf=30,X0=74;function J0(t){return bf+t*(X0-bf)}const wf=64,Z0=8,Q0=8,Af=16,Sf=.45;function ew(t,e){switch(t.status){case"running":{const r=e-t.lastActivityAt;return .55+.45*Math.exp(-r/45e3)}case"waiting":return .08;case"failed":return .9;case"completed":return 0;case"idle":return .03}}const kf=.32;function tw(t){const e=Um(t),r=t.depth>0?.62:1;return e===void 0?kf*r:Math.min(1,(kf+.68*e)*r)}function rw(t,e){const r=Math.max(1,(t.endedAt??e)-t.startedAt),n=(es(t)??0)/(r/6e4);return Math.min(1,.25+n/24)}function xf(t){return(t.status==="failed"?3:t.status==="waiting"?2:t.status==="running"?1:0)*1e15+t.lastActivityAt}function nw(t){const e=new Set,r=new Set,n=new Map,s=new Map,o=(i,a,c)=>{const u=i.get(a);u?u.push(c):i.set(a,[c])};for(const i of t.relationships){const{from:a,to:c,kind:u}=i;u==="ran-as"?(a.type==="execution"&&e.add(a.id),c.type==="execution"&&e.add(c.id),a.type==="session"&&c.type==="process"&&r.add(a.id),c.type==="session"&&a.type==="process"&&r.add(c.id),a.type==="execution"&&c.type==="session"?n.set(a.id,c.id):a.type==="session"&&c.type==="execution"&&n.set(c.id,a.id)):u==="same-as"&&a.type==="execution"&&c.type==="execution"&&(e.add(a.id),e.add(c.id),o(s,a.id,c.id),o(s,c.id,a.id))}return{resolvedExecutions:e,sessionsWithProcess:r,runObservesSession:n,sameExecution:s}}function sw(t,e){const n=t.startBasis===void 0?.5:t.startBasis==="measured"?1:0,s=t.endBasis===void 0?.5:t.endBasis==="measured"?1:0,o=t.endedAt===void 0?n:(n+s)/2,i=Um(t)===void 0?0:1,a=e.resolvedExecutions.has(t.id)||e.sessionsWithProcess.has(t.sessionId)?1:0;return(1+o+i+a)/4}function Ef(t){let e=1;for(const r of t)e*=1-Math.min(1,Math.max(0,r));return 1-e}function If(t,e,r,n){const s=Math.max(t,r),o=Math.min(e,n);if(o<s)return 0;const i=Math.max(e,n)-Math.min(t,r);return i<=0?1:(o-s)/i}function Cf(t){const e=t.now,r=Y0(t.machines.values()).slice(0,Z0),n=new Map,s=[];let o=1;const i=new Map;for(const S of t.executions.values()){const E=(i.get(S.machineId)??0)+1;i.set(S.machineId,E),E>o&&(o=E)}r.forEach((S,E)=>{const R=z0(E);n.set(S.id,R),s.push({id:S.id,name:S.name,kind:S.kind,x:R.x,y:R.y,extentX:R.extentX,extentY:R.extentY,prominence:(i.get(S.id)??0)/o,seed:pi(S.id,7)})});const a=45e3,c=[];for(const S of t.executions.values())(S.status==="completed"||S.status==="failed")&&e-(S.endedAt??e)>a||S.status==="idle"&&e-S.lastActivityAt>a*4||n.has(S.machineId)&&c.push(S);c.length>wf&&(c.sort((S,E)=>xf(E)-xf(S)),c.length=wf);const u=nw(t),l=S=>{const E=n.get(S.machineId),{x:R,y:j}=vf(E,S.id),M=t.sessions.get(S.sessionId);return{id:S.id,massId:S.machineId,sessionId:S.sessionId,x:R,y:j,extent:tw(S),energy:ew(S,e),rate:rw(S,e),phase:pi(S.id,3)*Math.PI*2,status:S.status,label:S.label,projectLabel:M?.projectLabel,taskLabel:M?.taskLabel,statusSince:S.waitingSince??S.endedAt??S.startedAt,articulation:sw(S,u),shoulder:0,observers:1}},d=new Set(c.map(S=>S.id)),m=new Set,p=[],y=S=>[S.startedAt,S.endedAt??e];for(const S of[...c].sort((E,R)=>E.id<R.id?-1:1)){if(m.has(S.id))continue;const E=[S];m.add(S.id);for(let re=0;re<E.length;re++)for(const F of u.sameExecution.get(E[re].id)??[])!d.has(F)||m.has(F)||(m.add(F),E.push(t.executions.get(F)));if(E.length===1){p.push(l(S));continue}const R=E.map(l),j=R.reduce((re,F)=>F.articulation>re.articulation||F.articulation===re.articulation&&F.id<re.id?F:re);let M=1;const[J,le]=y(t.executions.get(j.id));for(const re of E){const[F,W]=y(re);M=Math.min(M,If(J,le,F,W))}p.push({...j,extent:Math.max(...R.map(re=>re.extent)),energy:Math.max(...R.map(re=>re.energy)),articulation:Ef(R.map(re=>re.articulation)),shoulder:Math.min(Sf,1-M),observers:E.length})}const v=new Map;for(const S of p){if(u.runObservesSession.has(S.id))continue;const E=v.get(S.sessionId);E?E.push(S):v.set(S.sessionId,[S])}const g=new Map,C=[];for(const S of p){const E=u.runObservesSession.get(S.id),R=E?v.get(E):void 0;if(!E||!R||R.length===0){if(C.push(S),E){const W=v.get(S.sessionId);W?W.push(S):v.set(S.sessionId,[S])}continue}const j=t.executions.get(S.id);let M=1/0,J=-1/0;for(const W of R){const[ee,he]=y(t.executions.get(W.id));M=Math.min(M,ee),J=Math.max(J,he)}const[le,re]=y(j),F=g.get(E)??{articulations:[],coincidence:1};F.articulations.push(S.articulation),F.coincidence=Math.min(F.coincidence,If(le,re,M,J)),g.set(E,F)}const A=[];for(const S of[...v.keys()].sort()){const E=v.get(S),R=t.sessions.get(S);if(!R||E.length===0)continue;let j=0,M=0;for(const W of E)j+=W.x,M+=W.y;j/=E.length,M/=E.length;let J=0,le=0;for(const W of E){const ee=J0(W.extent);J=Math.max(J,Math.abs(W.x-j)+ee*1.5),le=Math.max(le,Math.abs(W.y-M)+ee)}const re=g.get(S),F=Math.max(...E.map(W=>W.articulation));A.push({id:S,massId:E[0].massId,x:j,y:M,extentX:Math.max(J,52),extentY:Math.max(le,36),presence:1,articulation:re?Ef([F,...re.articulations]):F,parentId:R.parentId,empty:!1,shoulder:re?Math.min(Sf,1-re.coincidence):0,observers:1+(re?.articulations.length??0),label:R.label??R.executor??S,projectLabel:R.projectLabel,taskLabel:R.taskLabel})}for(const S of[...t.sessions.values()].sort((E,R)=>E.id<R.id?-1:1)){if(S.executionIds.length>0||S.endedAt!==void 0&&e-S.endedAt>a)continue;const E=n.get(S.machineId);if(!E)continue;const{x:R,y:j}=vf(E,`session-presence:${S.id}`);A.push({id:S.id,massId:S.machineId,x:R,y:j,extentX:64,extentY:42,presence:1,articulation:u.sessionsWithProcess.has(S.id)?.5:.25,parentId:S.parentId,empty:!0,shoulder:0,observers:1,label:S.label??S.executor??S.id,projectLabel:S.projectLabel,taskLabel:S.taskLabel})}if(A.length>Af){const S=E=>E.empty?0:v.get(E.id)?.length??0;A.sort((E,R)=>S(R)-S(E)||(E.id<R.id?-1:1)),A.length=Af}const I=[];for(const S of t.transfers.values())if(S.endedAt===void 0&&!(!n.has(S.fromMachineId)||!n.has(S.toMachineId))){if(I.length>=Q0)break;I.push({id:S.id,fromMassId:S.fromMachineId,toMassId:S.toMachineId,energy:1,label:S.label})}const B=new Map;r.forEach((S,E)=>B.set(S.id,E));const k=Math.max(1,t.dayEnd-t.dayStart),T=[];for(const S of t.executions.values()){const E=B.get(S.machineId);if(E===void 0)continue;const R=(S.startedAt-t.dayStart)/k,j=((S.endedAt??e)-t.dayStart)/k;T.push({id:S.id,massId:S.machineId,lane:E,startFraction:Math.max(0,Math.min(1,R)),endFraction:Math.max(0,Math.min(1,j)),status:S.status,label:S.label})}return{time:e,masses:s,disturbances:C,plinths:A,couplings:I,strata:T}}const hi="057.landscape",qs=1;function ow(t){return{contract:hi,version:qs,landscape:t}}const _l="SHAPES FIELD",Ml="METADATA — DOES NOT SHAPE FIELD";function Hm(t){const e=new Date(t),r=n=>String(n).padStart(2,"0");return`${r(e.getHours())}:${r(e.getMinutes())}:${r(e.getSeconds())}`}function iw(t){return We(t).toUpperCase().replace(/(\d)([HMS])/g,"$1 $2").replace(/\bM\b/g,"MIN")}function aw(t,e,r,n,s=()=>{}){if(r==="mass")return lw(t,e,n);if(r==="coupling")return dw(t,n);const o=t.executions.get(n);return o?cw(t,e,o,r,s("execution",n)):null}function cw(t,e,r,n,s){const o=t.sessions.get(r.sessionId),i=t.machines.get(r.machineId),c=e.disturbances.find(g=>g.id===r.id)?.statusSince??r.endedAt??r.startedAt,u=r.startBasis==="inferred"||r.endBasis==="inferred",l=ur(r.measures),d=[{key:"MACHINE",value:(i?.name??r.machineId).toUpperCase()},{key:"STATE",value:r.status.toUpperCase(),tone:r.status},{key:"SINCE",value:Hm(c)},l===void 0?{key:"TOKENS",value:"NOT OBSERVED",tone:"absent",note:"This source does not persist token accounting."}:{key:"TOKENS",value:Qe(l)}];if(o){const g=o.executionIds.indexOf(r.id),C=e.plinths.some(I=>I.id===o.id),A=g>=0?`${g+1} OF ${o.executionIds.length}`:`OF ${o.executionIds.length}`;d.push({key:"SESSION",value:C?`${A} · PLINTH`:A})}const m=uw(t,r.id),p=[r.model??o?.model?{key:"MODEL",value:r.model??o?.model}:{key:"MODEL",value:"not observed",tone:"absent",note:"This source does not record the model."}];o?.context&&p.push({key:"PROJECT",value:Ce(o.context),note:o.context}),p.push({key:"SOURCE",value:[r.executor,m===void 0?void 0:`pid ${m}`].filter(Boolean).join(" · "),note:s}),p.push({key:"REQUESTS",value:String(Vm(r))});const y=es(r);if(p.push(y===void 0?{key:"TOOL CALLS",value:"not observed",tone:"absent",note:"This source does not count discrete operations."}:{key:"TOOL CALLS",value:bb(y)}),p.push({key:"ELAPSED",value:`${We((r.endedAt??t.now)-r.startedAt)}${u?" · inferred":""}`,note:u?r.boundsAssumption:void 0}),l!==void 0){const g=Lm(r.measures);p.push({key:"INPUT",value:Qe(g.input)},{key:"OUTPUT",value:Qe(g.output)}),p.push({key:"CACHE READ",value:Qe(g.cacheRead)},{key:"REASONING",value:Qe(g.reasoning)})}Hc(r)>0&&p.push({key:"TOOL ERRORS",value:String(Hc(r)),tone:"failed"}),Fc(r)>0&&p.push({key:"RETRIES",value:String(Fc(r)),tone:"waiting",note:"Provider retries."}),(r.waits.length>0||r.waitingMs>0)&&p.push({key:"BLOCKED",value:`${We(r.waitingMs)} on you · ${r.waits.length||1}×`,tone:"waiting"}),r.depth>0&&p.push({key:"SUB-AGENT",value:`depth ${r.depth}`});const v=r.status==="running"||r.status==="waiting";return{id:r.id,eyebrow:n==="stratum"||!v?"SELECTED · RUN":"SELECTED · PROCESS",title:r.label.toUpperCase(),state:{text:v?`${r.status.toUpperCase()} · ${iw(t.now-c)}`:r.status.toUpperCase(),status:r.status},groups:[{title:_l,metadata:!1,rows:d},{title:Ml,metadata:!0,rows:p}],failure:r.failure?`${r.failure.code}: ${r.failure.message}`:void 0,reveal:s}}function uw(t,e){for(const r of t.relationships){if(r.kind!=="ran-as")continue;const n=r.from.type==="execution"&&r.from.id===e&&r.to.type==="process"?r.to.id:r.to.type==="execution"&&r.to.id===e&&r.from.type==="process"?r.from.id:void 0;if(n)return t.processes.get(n)?.pid}}function lw(t,e,r){const n=t.machines.get(r);if(!n)return null;let s=0,o=0,i=0,a;for(const p of t.executions.values()){if(p.machineId!==n.id)continue;const y=ur(p.measures);y!==void 0&&(a=(a??0)+y),p.status==="running"?s++:p.status==="waiting"?o++:i++}const u=[{key:"KIND",value:(e.masses.find(p=>p.id===r)?.kind??n.kind).toUpperCase()},{key:"RUNNING",value:String(s),tone:s>0?"running":void 0}];o>0&&u.push({key:"WAITING",value:String(o),tone:"waiting"}),u.push({key:"RAN TODAY",value:String(i)});const l=[a===void 0?{key:"TOKENS",value:"not observed",tone:"absent",note:"No execution in this window reported token accounting."}:{key:"TOKENS",value:Qe(a)}],d=t.processTotals;if(d){const p=new Set;for(const y of t.relationships)y.kind==="ran-as"&&(y.from.type==="process"&&p.add(y.from.id),y.to.type==="process"&&p.add(y.to.id));l.push({key:"PROCESSES",value:`${d.observed} observed`}),l.push({key:"LAST 5 MIN",value:`${d.recentlySeen} seen`,note:"Processes with a liveness observation in the last five minutes. The sampler never witnesses an exit, so recency is the honest liveness signal."}),l.push({key:"ATTRIBUTED",value:`${p.size} of ${d.observed}`,note:"Processes tied to a session or execution by resolved identity. The rest are observed, not explained."})}const m=s+o;return{id:r,eyebrow:"SELECTED · MACHINE",title:n.name.toUpperCase(),state:m>0?{text:`${m} ACTIVE`,status:s>0?"running":"waiting"}:{text:"QUIET"},groups:[{title:_l,metadata:!1,rows:u},{title:Ml,metadata:!0,rows:l}]}}function dw(t,e){const r=t.transfers.get(e);if(!r)return null;const n=t.machines.get(r.fromMachineId)?.name??r.fromMachineId,s=t.machines.get(r.toMachineId)?.name??r.toMachineId;return{id:e,eyebrow:"SELECTED · TRANSFER",title:`${n} → ${s}`.toUpperCase(),state:{text:"TRANSFERRING",status:"running"},groups:[{title:_l,metadata:!1,rows:[{key:"FROM",value:n.toUpperCase()},{key:"TO",value:s.toUpperCase()},{key:"SINCE",value:Hm(r.startedAt)}]},{title:Ml,metadata:!0,rows:[{key:"WHAT",value:r.label},{key:"SIZE",value:wb(r.bytes)}]}]}}const it=t=>({value:t,basis:"measured"}),Vo=(t,e)=>({value:t,basis:"inferred",assumption:e});function jl(t){if(t.length===0)return[];t.sort((r,n)=>r.start-n.start);const e=[{start:t[0].start,end:t[0].end}];for(let r=1;r<t.length;r++){const n=t[r],s=e[e.length-1];n.start<=s.end?n.end>s.end&&(s.end=n.end):e.push({start:n.start,end:n.end})}return e}function Of(t){let e=0;for(const r of t)e+=r.end-r.start;return e}function fw(t,e){const r=[];let n=0,s=0;for(;n<t.length&&s<e.length;){const o=Math.max(t[n].start,e[s].start),i=Math.min(t[n].end,e[s].end);o<i&&r.push({start:o,end:i}),t[n].end<e[s].end?n++:s++}return r}function Fm(t){if(t.length===0)return{peak:0,at:0};const e=[];for(const o of t)e.push({t:o.start,d:1}),e.push({t:o.end,d:-1});e.sort((o,i)=>o.t-i.t||o.d-i.d);let r=0,n=0,s=e[0].t;for(const o of e)r+=o.d,r>n&&(n=r,s=o.t);return{peak:n,at:s}}function pw(t){if(t.length===0)return;const e=[...t].sort((n,s)=>n-s),r=e.length>>1;return e.length%2?e[r]:(e[r-1]+e[r])/2}const Wm=6e4;function ta(t,e){return t.endedAt!==void 0?{start:t.startedAt,end:t.endedAt}:{start:t.startedAt,end:t.status==="idle"?Math.max(t.startedAt,t.lastActivityAt):e}}function hw(t){const e=[];for(const r of t.executions.values()){r.depth===0&&e.push({start:r.startedAt-Wm,end:r.startedAt});for(const n of r.waits)e.push({start:n.start,end:n.end});r.waitingSince!==void 0&&e.push({start:r.waitingSince,end:t.now})}return jl(e)}function mw(t){const e=t.now,r=[...t.executions.values()];let n=0,s=0,o=0,i=0,a=0,c=0,u=0,l=0;const d=[],m=new Map;for(const T of r){n+=Vm(T),s+=ur(T.measures)??0,o+=es(T)??0,T.status==="completed"?i++:T.status==="failed"?a++:T.status==="waiting"?c++:T.status==="idle"&&u++;const S=ta(T,e);d.push(S),l+=T.waitingMs,T.waitingSince!==void 0&&(l+=Math.max(0,e-T.waitingSince));let E=m.get(T.machineId);E||(E={machineId:T.machineId,executions:0,tokens:0,computeTime:0},m.set(T.machineId,E)),E.executions++,E.tokens+=ur(T.measures)??0,E.computeTime+=S.end-S.start}const p=jl(d.map(T=>({...T}))),y=hw(t),v=Of(fw(p,y)),{peak:g,at:C}=Fm(d),A=yw(t),I=Math.max(0,A.length-1);let B=null;for(const T of A)(!B||T.end-T.start>B.end-B.start)&&(B=T);let k=0;for(const T of t.sessions.values())T.executionIds.some(S=>t.executions.has(S))&&k++;return{requests:it(n),sessions:it(k),executions:it(r.length),tokens:it(s),toolCalls:it(o),timeInFlight:Vo(Of(p),"Wall-clock time during which at least one run was in flight, merged so parallel runs are not double-counted. A run still open counts to now while it is running or waiting, and only to its last output once it has gone idle. In flight is not computing: it includes a run waiting on a tool, a model or a person."),humanAgentOverlap:Vo(v,`Time in flight intersecting a window when you were plausibly present: the ${Wm/1e3}s before you sent a message, and any approval from ask to answer.`),peakConcurrency:it(g),peakConcurrencyAt:it(C),contextSwitches:Vo(I,"Transitions between working directories, ordered by time. A directory is the closest thing the source has to a project."),longestFocus:Vo(B,"Longest unbroken stretch spent in one working directory."),waitingOnYou:it(l),completed:it(i),failed:it(a),waiting:it(c),idle:it(u),byMachine:m,contextSpans:A,transfers:it(t.transfers.size)}}function yw(t){const e=[];for(const n of t.executions.values()){const s=t.sessions.get(n.sessionId);s&&e.push({context:s.context,...ta(n,t.now)})}e.sort((n,s)=>n.start-s.start);const r=[];for(const n of e){const s=r[r.length-1];s&&s.context===n.context&&n.start<=s.end?n.end>s.end&&(s.end=n.end):s&&s.context===n.context?n.start-s.end<=gw?s.end=Math.max(s.end,n.end):r.push({context:n.context,start:n.start,end:n.end}):r.push({context:n.context,start:n.start,end:n.end})}return r}const gw=15*6e4;function vw(t){return{key:t,runs:0,tokens:0,tokenRuns:0,medianRuns:0,computeMs:0,failed:0,waitingMs:0,toolCalls:0}}function fc(t,e){const r=new Map,n=new Map;for(const s of t.executions.values()){const o=e(s,t.sessions.get(s.sessionId));if(o===void 0)continue;let i=r.get(o);i||(i=vw(o),r.set(o,i)),i.runs++;const a=ur(s.measures);if(a!==void 0&&(i.tokens+=a,i.tokenRuns++,s.endedAt!==void 0)){let u=n.get(o);u||(u=[],n.set(o,u)),u.push(a)}const c=ta(s,t.now);i.computeMs+=c.end-c.start,i.waitingMs+=s.waitingMs,i.toolCalls+=es(s)??0,s.status==="failed"&&i.failed++}for(const[s,o]of n){const i=r.get(s);i&&(i.medianTokens=pw(o),i.medianRuns=o.length)}return[...r.values()].sort((s,o)=>o.computeMs-s.computeMs)}function bw(t){const e={input:0,output:0,cacheRead:0,reasoning:0,total:0};for(const r of t.executions.values()){const n=Lm(r.measures);e.input+=n.input,e.output+=n.output,e.cacheRead+=n.cacheRead,e.reasoning+=n.reasoning}return e.total=e.input+e.output+e.cacheRead+e.reasoning,e}function ww(t){const e={count:0,totalMs:0,longestMs:0,openNow:0};for(const r of t.executions.values()){for(const n of r.waits){e.count++;const s=n.end-n.start;e.totalMs+=s,s>e.longestMs&&(e.longestMs=s)}if(r.waitingSince!==void 0){e.openNow++;const n=t.now-r.waitingSince;e.totalMs+=n,n>e.longestMs&&(e.longestMs=n)}}return e}function Aw(t){const e={toolCalls:0,toolErrors:0,retries:0,failed:0,interrupted:0,completed:0};for(const r of t.executions.values())e.toolCalls+=es(r)??0,e.toolErrors+=Hc(r),e.retries+=Fc(r),r.status==="failed"?e.failed++:r.outcome==="interrupted"?e.interrupted++:r.outcome==="completed"&&e.completed++;return e}function Sw(t){const e=[];for(const o of t.executions.values())e.push(ta(o,t.now));if(e.length===0)return[];const r=jl(e.map(o=>({...o}))),n=new Date(t.dayStart);n.setMinutes(0,0,0);const s=[];for(let o=n.getTime();o<t.now;o+=36e5){const i=o+36e5;let a=0;for(const l of r){const d=Math.max(l.start,o),m=Math.min(l.end,i);m>d&&(a+=m-d)}let c=0;const u=[];for(const l of e)l.start<i&&l.end>o&&(c++,u.push({start:Math.max(l.start,o),end:Math.min(l.end,i)}));s.push({hour:new Date(o).getHours(),runs:c,computeMs:a,peak:Fm(u).peak})}return s}const Zo=6e4,kw=60*Zo;function xw(t,e){const r=[],n=e.contextSpans,s=e.longestFocus.value,o=Math.max(1,t.now-t.dayStart),i=e.timeInFlight.value/o;let a;if(e.executions.value===0)return{headline:"QUIET",clauses:["No runs observed in this window."]};if(e.peakConcurrency.value>=3?a="PARALLEL":n.length>=6?a="FRAGMENTED":s&&s.end-s.start>2*kw?a="SUSTAINED":i<.15?a="SPARSE":a="SERIAL",e.peakConcurrency.value>=2?r.push(`Up to ${e.peakConcurrency.value} runs in flight at once; ${We(e.timeInFlight.value)} of wall-clock time had a run in flight.`):r.push(`Runs happened one at a time, across ${We(e.timeInFlight.value)} of wall-clock time.`),s&&r.push(`The longest unbroken stretch was ${We(s.end-s.start)} in ${Ce(s.context)}.`),n.length>1){const c=new Set(n.map(u=>u.context)).size;r.push(`Attention moved ${e.contextSwitches.value} ${e.contextSwitches.value===1?"time":"times"} across ${c} ${c===1?"context":"contexts"}.`)}if(e.waitingOnYou.value>Zo&&r.push(`${We(e.waitingOnYou.value)} was spent with a run waiting on your answer.`),e.humanAgentOverlap.value>Zo){const c=Math.round(e.humanAgentOverlap.value/Math.max(1,e.timeInFlight.value)*100);r.push(`About ${c}% of that time overlapped a window when you were present; no presence was observed in the rest.`)}else e.timeInFlight.value>5*Zo&&r.push("Runs were in flight almost entirely outside the moments you were observably present.");if(e.failed.value>0&&r.push(`${e.failed.value} of ${e.executions.value} runs ended in failure; ${e.completed.value} completed.`),e.byMachine.size>1){const c=[...e.byMachine.values()].sort((u,l)=>l.computeTime-u.computeTime).map(u=>`${t.machines.get(u.machineId)?.name??u.machineId} ${We(u.computeTime)}`);r.push(`Compute was split across ${c.join(", ")}.`)}return{headline:a,clauses:r}}const Nf="(no model)";function Ew(t){if(t.medianTokens===void 0)return{text:"no token accounting",title:"No run in this group reports token accounting, so there is no figure — not a figure of zero.",absent:!0};if(t.medianRuns===1)return{text:`single run ${Qe(t.medianTokens)}`,title:"One eligible run, so this is that run's figure, not a median. Same window as the rest of TODAY.",absent:!1};const e=t.medianRuns===t.runs?`${t.runs}`:`${t.medianRuns} of ${t.runs}`;return{text:`median ${Qe(t.medianTokens)} over ${e} runs`,title:`Median billed tokens per run, over the runs in this group that have ended and whose source reports token accounting — ${t.medianRuns} of ${t.runs} here. Runs still in flight are excluded: their totals are partial. Runs whose source persists no accounting are excluded: absence is not zero. Same window as the rest of TODAY.`,absent:!1}}function Iw(t,e,r){if(r&&r.runs>0&&r.reported===0)return at("WAITING ON YOU","—",void 0,{note:"not reported by today's sources"});const n=e.count>0?`${e.count} ${e.count===1?"block":"blocks"} · longest ${We(e.longestMs)}`:void 0,s=r&&r.reported<r.runs?`from the ${r.reported} of ${r.runs} runs whose sources report waits`:void 0;return at("WAITING ON YOU",We(t.value),t,{tone:t.value>0?"waiting":void 0,note:[n,s].filter(Boolean).join(" · ")||void 0})}function at(t,e,r,n={}){const s=r?.basis==="inferred";return{key:t,value:e,inferred:s,assumption:s?r?.assumption:void 0,...n}}function pc(t,e,r){const n=t[0]?.computeMs??0;return t.map(s=>({key:s.key,label:e(s.key),detail:`${s.runs} ${s.runs===1?"run":"runs"}${s.tokenRuns>0?` · ${Qe(s.tokens)} tok`:""} · ${We(s.computeMs)}`,failed:s.failed,fraction:n>0?s.computeMs/n:0,median:r?Ew(s):void 0}))}function Cw(t,e){const r=mw(t),n=xw(t,r),s=bw(t),o=ww(t),i=Aw(t),a=Sw(t),c=fc(t,(k,T)=>T?.context),u=fc(t,k=>k.model??Nf),l=fc(t,k=>k.machineId),d=[...t.executions.values()],m=d.filter(k=>ur(k.measures)===void 0).length,p=d.filter(k=>k.depth>0).length,y=r.longestFocus.value,v=Math.round(r.humanAgentOverlap.value/Math.max(1,r.timeInFlight.value)*100),g=[at("REQUESTS",Qe(r.requests.value),r.requests),at("RUNS",String(r.executions.value),r.executions,{note:p>0?`${p} of them sub-agents`:void 0}),at("SESSIONS",String(r.sessions.value),r.sessions),at("TOKENS",Qe(r.tokens.value),r.tokens,{note:`${Math.round(s.cacheRead/Math.max(1,s.total)*100)}% cache reads`+(m>0?` · ${m} ${m===1?"run reports":"runs report"} no accounting`:"")}),at("TOOL CALLS",Qe(i.toolCalls),r.toolCalls,{note:i.toolErrors>0?`${i.toolErrors} failed`:void 0}),at("TIME IN FLIGHT",We(r.timeInFlight.value),r.timeInFlight),at("HUMAN + AGENT OVERLAP",We(r.humanAgentOverlap.value),r.humanAgentOverlap,{note:`${v}% of time in flight`}),at("PEAK CONCURRENCY",r.peakConcurrency.value>0?`${r.peakConcurrency.value} · ${Po(r.peakConcurrencyAt.value)}`:"0",r.peakConcurrency),at("CONTEXT SWITCHES",String(r.contextSwitches.value),r.contextSwitches,{note:`across ${c.length} ${c.length===1?"context":"contexts"}`}),at("LONGEST FOCUS",y?We(y.end-y.start):"—",r.longestFocus,{note:y?`${Ce(y.context)} · ${Po(y.start)}–${Po(y.end)}`:void 0}),Iw(r.waitingOnYou,o,e),at("FAILED",String(i.failed),void 0,{tone:i.failed>0?"failed":void 0,note:i.interrupted>0||i.retries>0?`${i.interrupted} stopped · ${i.retries} retries`:void 0})],C=a.length>0?a.reduce((k,T)=>T.computeMs>k.computeMs?T:k,a[0]):void 0,A=k=>`${String(k).padStart(2,"0")}:00`,I=[{title:"WHERE THE TIME WENT",rows:pc(c,Ce,!1)}];l.length>0&&I.push({title:"BY MACHINE",rows:pc(l,k=>t.machines.get(k)?.name??k,!1)}),u.length>0&&I.push({title:"BY MODEL",rows:pc(u,k=>k===Nf?"model not observed":k,!0)});const B=k=>k/Math.max(1,s.total);return{headline:n.headline,clauses:[...n.clauses],measures:g,hours:a.map(k=>({hour:k.hour,computeMs:k.computeMs,runs:k.runs,peak:k.peak})),busiest:C?`busiest ${A(C.hour)} · ${We(C.computeMs)} of that hour`:void 0,groups:I,tokens:[["CACHE READS",s.cacheRead],["INPUT",s.input],["OUTPUT",s.output],["REASONING",s.reasoning]].map(([k,T])=>({key:k,value:Qe(T),percent:Math.round(B(T)*100),fraction:B(T)})),tokensNote:"Cache reads are context replayed into each request, not work generated. They dominate the total, which is why the headline token figure is much larger than it feels.",failures:d.filter(k=>k.status==="failed").sort((k,T)=>T.startedAt-k.startedAt).slice(0,12).map(k=>({id:k.id,at:Po(k.startedAt),label:k.label,reason:k.failure?`${k.failure.code}: ${k.failure.message}`:"failed"})),notAvailable:[{key:"COST",text:"Every source here reports tokens or CPU time; none reports money. Converting one to the other needs a price table 057 does not have, so no cost figure is shown anywhere."},{key:"TOKENS, FROM SOME SOURCES",text:"Cursor persists no usage and 0x2F records none; their runs read NOT OBSERVED rather than 0, and the token totals sum only the runs that report."},{key:"CLAUDE IN A BROWSER",text:"Claude on claude.ai — chat, Claude Design, cloud Claude Code sessions — runs on Anthropic's servers and writes nothing to this Mac. Only Claude Code sessions that run here (a terminal, an editor, the desktop app's Code tab) leave the files 057 reads; the browser is seen as a process, never as work."},{key:"MACHINE-TO-MACHINE TRANSFER",text:"Every observed source is single-host. Transfers are modelled and the field renders them, but no real adapter emits one; only the synthetic source does."},{key:"PROCESS EXITS",text:"The OS collector samples; an exit is inferred from disappearance between samples, never witnessed."},{key:"OUTCOME QUALITY",text:"The log records that a run completed, not whether the work was any good."}]}}function Ow(t,e){const r=new Set(e.disturbances.map(o=>o.id)),n=new Set(e.strata.map(o=>o.id)),s=[...t.executions.values()].sort((o,i)=>i.startedAt-o.startedAt).map(o=>{const i=t.sessions.get(o.sessionId);return{id:o.id,startedAt:o.startedAt,label:o.label,depth:o.depth,context:i?.context?Ce(i.context):null,model:o.model??null,status:o.status,stopped:o.outcome==="interrupted",durationMs:(o.endedAt??t.now)-o.startedAt,inferred:o.startBasis==="inferred"||o.endBasis==="inferred",tokens:ur(o.measures)??null,tools:es(o)??null,waitedMs:o.waitingMs,inField:r.has(o.id)?"disturbance":n.has(o.id)?"stratum":null}});return{now:t.now,rows:s}}const Dl={width:80,color:!1,ascii:!1},Nw={dim:"2",bold:"1",yellow:"33","bold-yellow":"1;33"};class Tw{segments=[];length=0;text(e,r){return e.length>0&&(this.segments.push({text:e,role:r}),this.length+=ke(e)),this}at(e,r,n){return this.padTo(e),this.text(r,n)}right(e,r,n){return this.at(e-ke(r)+1,r,n)}append(e){for(const r of e.segments)this.text(r.text,r.role);return this}padTo(e){const r=e-this.length;return r>0?this.text(" ".repeat(r)):this.length>0&&!this.endsWithSpace()&&this.text(" "),this}endsWithSpace(){const e=this.segments[this.segments.length-1];return e!==void 0&&e.text.endsWith(" ")}}function _(){return new Tw}function ra(t,e){return`${t.map(r=>Bw(r,e.color)).join(`
8
+ `)[0].trim().slice(0,200)||"Gemini reported an error"}const f0=t=>`gemini:${t}`,Xt=t=>typeof t=="number"&&Number.isFinite(t)?t:0,Zs=t=>typeof t=="string"&&t?t:void 0,Rn=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function p0(t,e){const r=t.split(`
9
+ `).filter(a=>a.trim());if(r.length===0)throw new Ei("session file is empty",e);let n=null;const o=[],s=new Map,i=a=>{const c=a;!c||typeof c!="object"||typeof c.id!="string"||(s.has(c.id)||o.push(c.id),s.set(c.id,c))};for(const a of r){let c;try{c=JSON.parse(a)}catch{continue}if(!c||typeof c!="object")continue;const u=c;if(!n&&typeof u.sessionId=="string"){n=u;continue}const d=u.$set;if(d){const l=d.messages;if(Array.isArray(l))for(const m of l)i(m);continue}typeof u.id=="string"&&i(u)}if(!n||!n.sessionId)throw new Ei("session file has no header with a sessionId",e);return{header:n,messages:o.map(a=>s.get(a))}}const oy=t=>Array.isArray(t.content)&&t.content.some(e=>!!e&&typeof e=="object"&&"functionResponse"in e);function h0(t){if(t.type!=="user"||oy(t))return!1;const e=Array.isArray(t.content)?t.content.map(n=>n?.text).filter(n=>typeof n=="string"):[];if(e.length===0)return!1;const r=e[0];return!r.startsWith("<session_context>")&&!r.startsWith("[System:")}function m0(t){const e=Xt(t.input),r=Xt(t.cached);return{[Z.tokensInput]:Math.max(0,e-r),[Z.tokensOutput]:Xt(t.output)+Xt(t.thoughts),[Z.tokensCacheRead]:r,[Z.tokensReasoning]:Xt(t.thoughts),[Z.steps]:1}}function y0(t,e){const{header:r,messages:n}=t,o=r.sessionId,s=Rn(r.startTime);if(s===void 0)throw new Ei("session header has no parseable startTime",e.path);const i=n.filter(g=>Rn(g.timestamp)!==void 0),a=i.length?Math.max(...i.map(g=>Rn(g.timestamp))):s,c=e.workspacePath??"",u=c?Ne(c).toUpperCase():"GEMINI",d=f0(o),m={source:{id:es,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},p=g=>({path:e.path,...g?{recordId:g}:{}}),h=[{...m,occurredAt:s,kind:"began",subject:{type:"session",id:d},claims:[{ns:"agent.session",parts:[u0,o],validFrom:s,validTo:a}],core:{machineId:e.machine.id,label:u,projectLabel:c?Ne(c):void 0,executor:es},attrs:{context:c,"gemini.sessionId":o,"gemini.projectHash":r.projectHash,...Zs(r.kind)?{"gemini.kind":r.kind}:{}},provenance:p(o),seq:"session"}],v=[];for(let g=0;g<n.length;g++)h0(n[g])&&Rn(n[g].timestamp)!==void 0&&v.push(g);if(v.length===0){if(n.some(g=>g.type==="gemini"))throw new Ei(`session has ${n.length} messages including model output but no recognisable user prompt`,e.path);return h}for(let g=0;g<v.length;g++){const I=v[g],N=g+1<v.length?v[g+1]:n.length,S=g+1,T=`${d}:turn:${S}`,x=Rn(n[I].timestamp);let D=x,w,$;const E=[];for(let te=I;te<N;te++){const U=n[te],V=Rn(U.timestamp);if(V===void 0||U.type!=="gemini"&&U.type!=="error"&&!(U.type==="user"&&oy(U))||(V>D&&(D=V),$=U,U.type!=="gemini"))continue;w??=Zs(U.model);const z=Array.isArray(U.toolCalls)?U.toolCalls:[],se=U.tokens?m0(U.tokens):{};z.length&&(se[Z.interactions]=z.length),Object.keys(se).length!==0&&E.push({...m,occurredAt:V,kind:"progressed",subject:{type:"execution",id:T},core:{measures:se},attrs:{...z.length?{"gemini.tools":z.map(ve=>Zs(ve.name)??"unknown")}:{},...Zs(U.model)?{"gemini.model":U.model}:{},...U.tokens?{"gemini.usage.input":Xt(U.tokens.input),"gemini.usage.output":Xt(U.tokens.output),"gemini.usage.cached":Xt(U.tokens.cached),"gemini.usage.thoughts":Xt(U.tokens.thoughts),"gemini.usage.tool":Xt(U.tokens.tool)}:{}},provenance:p(U.id),seq:U.id})}h.push({...m,occurredAt:x,kind:"began",subject:{type:"execution",id:T},core:{machineId:e.machine.id,sessionId:d,label:`${u} · TURN ${S}`,executor:es,model:w,depth:0},attrs:{"gemini.turn":S},provenance:p(n[I].id),seq:`turn:${S}`}),h.push(...E);const B=$?.type==="error",C=$?.type==="gemini"&&!(Array.isArray($.toolCalls)&&$.toolCalls.length),P=g+1<v.length,L=(te,U)=>({...m,occurredAt:D,kind:"ended",subject:{type:"execution",id:T},core:te,...U?{basis:"inferred",assumption:l0}:{},provenance:p(n[I].id),seq:`turn:${S}:end`});B?h.push(L({outcome:"error",failureMessage:d0($)},!1)):P||C&&e.settled?h.push(L({outcome:"completed"},!1)):e.closeOpenTurns&&h.push(L({outcome:C?"completed":"interrupted"},!0))}return h}const g0=3e3;function Zl(){return process.env.GEMINI_HOME||ue(xn(),".gemini")}const sy=()=>ue(Zl(),"tmp"),jf=new Map;async function v0(){const t=new Map;try{const e=JSON.parse(await _r(ue(Zl(),"projects.json"),"utf8"));for(const[r,n]of Object.entries(e.projects??{}))typeof n=="string"&&t.set(n,r)}catch{}return t}async function iy(){const t=sy();if(!ge(t))return[];const e=[];let r;try{r=await Ze(t)}catch{return e}for(const n of r){let o;try{o=await Ze(ue(t,n,"chats"))}catch{continue}for(const s of o)s.startsWith("session-")&&s.endsWith(".jsonl")&&e.push({path:ue(t,n,"chats",s),slug:n})}return e}async function ay(t,e){const r=Vr(),n=Date.now(),o={envelopes:[],sessionsRead:0,sessionsFailed:0,problems:[],storedAvailable:!1},s=await iy();if(s.length===0)return o.storedAvailable=ge(sy()),o;o.storedAvailable=!0;const i=await v0();for(const a of s){let c;try{c=await sn(a.path)}catch{continue}if(c.mtimeMs<t)continue;const u=Date.now()-c.mtimeMs,d=u>g0,l=u>Yl,m=`${c.mtimeMs}:${c.size}:${d}:${l}`,p=jf.get(a.path);let h;if(p&&p.stamp===m)h=p.envelopes;else try{const v=p0(await _r(a.path,"utf8"),a.path);h=y0(v,{machine:r,host:Ur(),observedAt:n,path:a.path,workspacePath:i.get(a.slug),settled:d,closeOpenTurns:l}).map(Zt),jf.set(a.path,{stamp:m,envelopes:h})}catch(v){o.sessionsFailed++,o.problems.push({path:a.path,message:v instanceof Error?v.message:String(v)});continue}o.sessionsRead++;for(const v of h)v.occurredAt>=t&&v.occurredAt<=e&&o.envelopes.push(v)}return o}async function b0(t,e){return(await ay(t,e)).envelopes}async function Df(){const t=Zl(),e=(await iy()).length;return{available:e>0,present:ge(t),home:t,sessions:e}}const w0=new Set(["running","waiting"]);function cy(t){return w0.has(t)}function Ql(t,e){return{now:t,dayStart:t,dayEnd:e,machines:new Map,sources:new Map,sessions:new Map,executions:new Map,processes:new Map,artifacts:new Map,transfers:new Map,relationships:[],active:new Set,seen:new Set}}const A0=5*6e4;function S0(t){const e=[];for(const r of t)r.parentId&&e.push({from:{type:"session",id:r.parentId},to:{type:"session",id:r.id},kind:"spawned",basis:"measured",via:"recorded by the child session's own runtime"});return e}function k0(t,e){const r=t.now-A0,n=new Set;for(const a of e)a.from.type==="process"&&n.add(a.from.id),a.to.type==="process"&&n.add(a.to.id);const o=[];let s=0,i=0;for(const a of t.processes.values())a.lastSeenAt>=r&&s++,a.endInferred&&i++,n.has(a.id)&&o.push(a);return{now:t.now,dayStart:t.dayStart,dayEnd:t.dayEnd,machines:[...t.machines.values()],sources:[...t.sources.values()],sessions:[...t.sessions.values()],executions:[...t.executions.values()],processes:o,processTotals:{observed:t.processes.size,recentlySeen:s,exitsInferred:i},relationships:[...e,...S0(t.sessions.values())]}}function xc(t){const e=Ql(t.dayStart,t.dayEnd);e.now=t.now;for(const r of t.machines)e.machines.set(r.id,r);for(const r of t.sources)e.sources.set(`${r.id}:${r.instance}`,r);for(const r of t.sessions)e.sessions.set(r.id,r);for(const r of t.executions)e.executions.set(r.id,r),cy(r.status)&&e.active.add(r.id);for(const r of t.processes)e.processes.set(r.id,r);return e.processTotals=t.processTotals,e.relationships=t.relationships,e}function vt(t,e){const r=t[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function cs(t,e){for(const[r,n]of Object.entries(e)){if(typeof n!="number"||!Number.isFinite(n))continue;const o=r;t[o]=(t[o]??0)+n}}const E0=[Z.tokensInput,Z.tokensOutput,Z.tokensCacheRead];function jr(t){let e=0,r=!1;for(const n of E0){const o=vt(t,n);o!==void 0&&(r=!0,e+=o)}return r?e:void 0}function uy(t){return{input:vt(t,Z.tokensInput)??0,output:vt(t,Z.tokensOutput)??0,cacheRead:vt(t,Z.tokensCacheRead)??0,reasoning:vt(t,Z.tokensReasoning)??0}}function ly(t){const e=jr(t.measures);if(e!==void 0)return Lf(e/1e3,200);const r=vt(t.measures,Z.cpuMs);if(r!==void 0)return Lf(r/1e3,200)}function po(t){return vt(t.measures,Z.interactions)}function dy(t){return vt(t.measures,Z.steps)??0}function xi(t){return vt(t.measures,Z.errors)??0}function su(t){return vt(t.measures,Z.retries)??0}function Lf(t,e){return Math.min(1,Math.log1p(Math.max(0,t))/Math.log1p(e))}function x0(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return e>>>0}function Ii(t,e=0){return x0(t+"#"+e)%1e5/1e5}const Ic=[{x:430,y:508,extentX:300,extentY:186},{x:838,y:322,extentX:186,extentY:116}];function I0(t){if(t<Ic.length)return Ic[t];const r=-.9+(t-Ic.length)*1.15;return{x:620+Math.cos(r)*520,y:300+Math.sin(r)*250,extentX:150,extentY:94}}function O0(t){const e=r=>r==="laptop"?0:r==="desktop"?1:2;return[...t].sort((r,n)=>e(r.kind)-e(n.kind)||r.firstSeenAt-n.firstSeenAt||(r.id<n.id?-1:r.id>n.id?1:0))}function Pf(t,e){const r=Ii(e,1),n=Ii(e,2),o=r*Math.PI*2+n*2.399963,s=.34+.46*Math.sqrt(n);return{x:t.x+Math.cos(o)*t.extentX*s,y:t.y+Math.sin(o)*t.extentY*s}}const Uf=30,C0=74;function N0(t){return Uf+t*(C0-Uf)}const Vf=64,T0=8,$0=8,Hf=16,Ff=.45;function B0(t,e){switch(t.status){case"running":{const r=e-t.lastActivityAt;return .55+.45*Math.exp(-r/45e3)}case"waiting":return .08;case"failed":return .9;case"completed":return 0;case"idle":return .03}}const Wf=.32;function R0(t){const e=ly(t),r=t.depth>0?.62:1;return e===void 0?Wf*r:Math.min(1,(Wf+.68*e)*r)}function M0(t,e){const r=Math.max(1,(t.endedAt??e)-t.startedAt),n=(po(t)??0)/(r/6e4);return Math.min(1,.25+n/24)}function Kf(t){return(t.status==="failed"?3:t.status==="waiting"?2:t.status==="running"?1:0)*1e15+t.lastActivityAt}function _0(t){const e=new Set,r=new Set,n=new Map,o=new Map,s=(i,a,c)=>{const u=i.get(a);u?u.push(c):i.set(a,[c])};for(const i of t.relationships){const{from:a,to:c,kind:u}=i;u==="ran-as"?(a.type==="execution"&&e.add(a.id),c.type==="execution"&&e.add(c.id),a.type==="session"&&c.type==="process"&&r.add(a.id),c.type==="session"&&a.type==="process"&&r.add(c.id),a.type==="execution"&&c.type==="session"?n.set(a.id,c.id):a.type==="session"&&c.type==="execution"&&n.set(c.id,a.id)):u==="same-as"&&a.type==="execution"&&c.type==="execution"&&(e.add(a.id),e.add(c.id),s(o,a.id,c.id),s(o,c.id,a.id))}return{resolvedExecutions:e,sessionsWithProcess:r,runObservesSession:n,sameExecution:o}}function j0(t,e){const n=t.startBasis===void 0?.5:t.startBasis==="measured"?1:0,o=t.endBasis===void 0?.5:t.endBasis==="measured"?1:0,s=t.endedAt===void 0?n:(n+o)/2,i=ly(t)===void 0?0:1,a=e.resolvedExecutions.has(t.id)||e.sessionsWithProcess.has(t.sessionId)?1:0;return(1+s+i+a)/4}function Gf(t){let e=1;for(const r of t)e*=1-Math.min(1,Math.max(0,r));return 1-e}function qf(t,e,r,n){const o=Math.max(t,r),s=Math.min(e,n);if(s<o)return 0;const i=Math.max(e,n)-Math.min(t,r);return i<=0?1:(s-o)/i}function Oc(t){const e=t.now,r=O0(t.machines.values()).slice(0,T0),n=new Map,o=[];let s=1;const i=new Map;for(const w of t.executions.values()){const $=(i.get(w.machineId)??0)+1;i.set(w.machineId,$),$>s&&(s=$)}r.forEach((w,$)=>{const E=I0($);n.set(w.id,E),o.push({id:w.id,name:w.name,kind:w.kind,x:E.x,y:E.y,extentX:E.extentX,extentY:E.extentY,prominence:(i.get(w.id)??0)/s,seed:Ii(w.id,7)})});const a=45e3,c=[];for(const w of t.executions.values())(w.status==="completed"||w.status==="failed")&&e-(w.endedAt??e)>a||w.status==="idle"&&e-w.lastActivityAt>a*4||n.has(w.machineId)&&c.push(w);c.length>Vf&&(c.sort((w,$)=>Kf($)-Kf(w)),c.length=Vf);const u=_0(t),d=w=>{const $=n.get(w.machineId),{x:E,y:B}=Pf($,w.id),C=t.sessions.get(w.sessionId);return{id:w.id,massId:w.machineId,sessionId:w.sessionId,x:E,y:B,extent:R0(w),energy:B0(w,e),rate:M0(w,e),phase:Ii(w.id,3)*Math.PI*2,status:w.status,label:w.label,projectLabel:C?.projectLabel,taskLabel:C?.taskLabel,statusSince:w.waitingSince??w.endedAt??w.startedAt,articulation:j0(w,u),shoulder:0,observers:1}},l=new Set(c.map(w=>w.id)),m=new Set,p=[],h=w=>[w.startedAt,w.endedAt??e];for(const w of[...c].sort(($,E)=>$.id<E.id?-1:1)){if(m.has(w.id))continue;const $=[w];m.add(w.id);for(let te=0;te<$.length;te++)for(const U of u.sameExecution.get($[te].id)??[])!l.has(U)||m.has(U)||(m.add(U),$.push(t.executions.get(U)));if($.length===1){p.push(d(w));continue}const E=$.map(d),B=E.reduce((te,U)=>U.articulation>te.articulation||U.articulation===te.articulation&&U.id<te.id?U:te);let C=1;const[P,L]=h(t.executions.get(B.id));for(const te of $){const[U,V]=h(te);C=Math.min(C,qf(P,L,U,V))}p.push({...B,extent:Math.max(...E.map(te=>te.extent)),energy:Math.max(...E.map(te=>te.energy)),articulation:Gf(E.map(te=>te.articulation)),shoulder:Math.min(Ff,1-C),observers:$.length})}const v=new Map;for(const w of p){if(u.runObservesSession.has(w.id))continue;const $=v.get(w.sessionId);$?$.push(w):v.set(w.sessionId,[w])}const g=new Map,I=[];for(const w of p){const $=u.runObservesSession.get(w.id),E=$?v.get($):void 0;if(!$||!E||E.length===0){if(I.push(w),$){const V=v.get(w.sessionId);V?V.push(w):v.set(w.sessionId,[w])}continue}const B=t.executions.get(w.id);let C=1/0,P=-1/0;for(const V of E){const[z,se]=h(t.executions.get(V.id));C=Math.min(C,z),P=Math.max(P,se)}const[L,te]=h(B),U=g.get($)??{articulations:[],coincidence:1};U.articulations.push(w.articulation),U.coincidence=Math.min(U.coincidence,qf(L,te,C,P)),g.set($,U)}const N=[];for(const w of[...v.keys()].sort()){const $=v.get(w),E=t.sessions.get(w);if(!E||$.length===0)continue;let B=0,C=0;for(const V of $)B+=V.x,C+=V.y;B/=$.length,C/=$.length;let P=0,L=0;for(const V of $){const z=N0(V.extent);P=Math.max(P,Math.abs(V.x-B)+z*1.5),L=Math.max(L,Math.abs(V.y-C)+z)}const te=g.get(w),U=Math.max(...$.map(V=>V.articulation));N.push({id:w,massId:$[0].massId,x:B,y:C,extentX:Math.max(P,52),extentY:Math.max(L,36),presence:1,articulation:te?Gf([U,...te.articulations]):U,parentId:E.parentId,empty:!1,shoulder:te?Math.min(Ff,1-te.coincidence):0,observers:1+(te?.articulations.length??0),label:E.label??E.executor??w,projectLabel:E.projectLabel,taskLabel:E.taskLabel})}for(const w of[...t.sessions.values()].sort(($,E)=>$.id<E.id?-1:1)){if(w.executionIds.length>0||w.endedAt!==void 0&&e-w.endedAt>a)continue;const $=n.get(w.machineId);if(!$)continue;const{x:E,y:B}=Pf($,`session-presence:${w.id}`);N.push({id:w.id,massId:w.machineId,x:E,y:B,extentX:64,extentY:42,presence:1,articulation:u.sessionsWithProcess.has(w.id)?.5:.25,parentId:w.parentId,empty:!0,shoulder:0,observers:1,label:w.label??w.executor??w.id,projectLabel:w.projectLabel,taskLabel:w.taskLabel})}if(N.length>Hf){const w=$=>$.empty?0:v.get($.id)?.length??0;N.sort(($,E)=>w(E)-w($)||($.id<E.id?-1:1)),N.length=Hf}const S=[];for(const w of t.transfers.values())if(w.endedAt===void 0&&!(!n.has(w.fromMachineId)||!n.has(w.toMachineId))){if(S.length>=$0)break;S.push({id:w.id,fromMassId:w.fromMachineId,toMassId:w.toMachineId,energy:1,label:w.label})}const T=new Map;r.forEach((w,$)=>T.set(w.id,$));const x=Math.max(1,t.dayEnd-t.dayStart),D=[];for(const w of t.executions.values()){const $=T.get(w.machineId);if($===void 0)continue;const E=(w.startedAt-t.dayStart)/x,B=((w.endedAt??e)-t.dayStart)/x;D.push({id:w.id,massId:w.machineId,lane:$,startFraction:Math.max(0,Math.min(1,E)),endFraction:Math.max(0,Math.min(1,B)),status:w.status,label:w.label})}return{time:e,masses:o,disturbances:I,plinths:N,couplings:S,strata:D}}const Oi="057.landscape",us=1;function D0(t){return{contract:Oi,version:us,landscape:t}}const fy=9e4;function zf(t,e){if(t.waitingSince===void 0)return;const r=t.waitingSince,n=Math.max(r,e);t.waitingMs+=n-r,t.waits.push({start:r,end:n})}function L0(t,e){const r=`${e.source.id}:${e.source.instance}`;let n=t.sources.get(r);n||(n={id:e.source.id,instance:e.source.instance,origin:e.source.instance,firstSeenAt:e.occurredAt,lastSeenAt:e.occurredAt,events:0,strata:{}},t.sources.set(r,n)),n.events++,e.occurredAt<n.firstSeenAt&&(n.firstSeenAt=e.occurredAt),e.occurredAt>n.lastSeenAt&&(n.lastSeenAt=e.occurredAt),e.stratum&&(n.strata[e.stratum]=(n.strata[e.stratum]??0)+1);const o=e.provenance?.sourceVersion;o&&(n.sourceVersions?n.sourceVersions.includes(o)||n.sourceVersions.push(o):n.sourceVersions=[o])}function P0(t,e){if(t.seen.has(e.id))return;t.seen.add(e.id),e.occurredAt>t.now&&(t.now=e.occurredAt),L0(t,e);const r=e.core??{},n=e.occurredAt;switch(e.subject.type){case"machine":{if(t.machines.has(e.subject.id))break;const o={id:e.subject.id,name:r.machineName??e.subject.id,kind:r.machineKind??"laptop",parentId:r.parentId,firstSeenAt:n};t.machines.set(o.id,o);break}case"session":{if(e.kind==="began"){const o=t.sessions.get(e.subject.id);if(o){o.parentId===void 0&&r.parentId&&(o.parentId=r.parentId),o.projectLabel===void 0&&r.projectLabel&&(o.projectLabel=r.projectLabel),o.taskLabel===void 0&&r.taskLabel&&(o.taskLabel=r.taskLabel);break}const s={id:e.subject.id,machineId:r.machineId??"",label:r.label,projectLabel:r.projectLabel,taskLabel:r.taskLabel,context:e.attrs?.context??r.label??"",executor:r.executor,model:r.model,startedAt:n,executionIds:[],parentId:r.parentId};t.sessions.set(s.id,s)}else if(e.kind==="ended"){const o=t.sessions.get(e.subject.id);o&&(o.endedAt=n)}break}case"execution":U0(t,e,n);break;case"process":V0(t,e,n);break;case"artifact":{if(t.artifacts.has(e.subject.id))break;t.artifacts.set(e.subject.id,{id:e.subject.id,kind:"file",path:r.label??e.subject.id,firstSeenAt:n});break}}}function U0(t,e,r){const n=e.core??{},o=e.subject.id;if(e.kind==="began"){if(t.executions.has(o))return;const i={id:o,sessionId:n.sessionId??n.parentId??"",machineId:n.machineId??"",label:n.label??o,executor:n.executor??"unknown",model:n.model,status:"running",startedAt:r,lastActivityAt:r,measures:{},waitingMs:0,waits:[],parentId:n.parentId,depth:n.depth??0,startBasis:e.basis,boundsAssumption:e.assumption};n.measures&&cs(i.measures,n.measures),t.executions.set(o,i),t.active.add(o),t.sessions.get(i.sessionId)?.executionIds.push(o);return}const s=t.executions.get(o);if(s)switch(s.endBasis==="inferred"&&s.endedAt!==void 0&&r>s.endedAt&&(e.kind==="progressed"||e.kind==="blocked"||e.kind==="resumed")&&(delete s.endedAt,delete s.endBasis,delete s.outcome,delete s.failure,s.startBasis!=="inferred"&&delete s.boundsAssumption,s.status="running",t.active.add(o)),e.kind){case"progressed":{n.measures&&cs(s.measures,n.measures),s.lastActivityAt=r,s.status==="idle"&&(s.status="running",t.active.add(o));break}case"blocked":{if(!cy(s.status))break;s.status="waiting",s.waitingSince=r,s.waitReason=n.blockedOn??"input",s.lastActivityAt=r;break}case"resumed":{zf(s,r),s.status="running",s.waitingSince=void 0,s.waitReason=void 0,s.lastActivityAt=r,t.active.add(o);break}case"ended":{const i=n.outcome==="error";s.status=i?"failed":"completed",s.endedAt=r,s.endBasis=e.basis,e.assumption&&!s.boundsAssumption&&(s.boundsAssumption=e.assumption),s.lastActivityAt=r,s.outcome=n.outcome??"completed",i&&(s.failure={code:n.failureCode??"ERROR",message:n.failureMessage??"Execution failed"}),zf(s,r),s.waitingSince=void 0,s.waitReason=void 0,t.active.delete(o);break}case"observed":s.lastActivityAt=Math.max(s.lastActivityAt,r);break}}function V0(t,e,r){const n=e.core??{},o=e.subject.id,s=Number(e.attrs?.["os.pid"]??0);if(e.kind==="began"){if(t.processes.has(o))return;const a={id:o,machineId:n.machineId??"",pid:s,ppid:typeof e.attrs?.["os.ppid"]=="number"?e.attrs["os.ppid"]:void 0,command:n.label??n.executor??String(s),startedAt:r,lastSeenAt:r,status:"running",measures:{}};n.measures&&cs(a.measures,n.measures),t.processes.set(o,a);return}const i=t.processes.get(o);if(i)if(e.kind==="observed"||e.kind==="progressed"){if(i.lastSeenAt=Math.max(i.lastSeenAt,r),n.measures){const a=n.measures[Z.cpuMs];typeof a=="number"&&(i.measures[Z.cpuMs]=a);const{[Z.cpuMs]:c,...u}=n.measures;cs(i.measures,u)}}else e.kind==="ended"&&(i.endedAt=r,i.lastSeenAt=Math.max(i.lastSeenAt,r),i.status="exited",i.endInferred=e.basis==="inferred")}function py(t,e){for(let r=0;r<e.length;r++)P0(t,e[r])}function hy(t,e){e>t.now&&(t.now=e),e=t.now;for(const r of t.active){const n=t.executions.get(r);if(!n){t.active.delete(r);continue}n.status==="running"&&e-n.lastActivityAt>fy&&(n.status="idle")}}const my=`Wall-clock time covered by recorded run intervals, with parallel intervals counted once and waiting included. An open running record becomes idle after ${fy/1e3} seconds without an event; its interval then stops at its last event instead of the period end. Explicit waits still count to the period end. A later event or ending includes the intervening silence again. The estimate can decrease or be revised. In flight is not computing time or human attention.`,ft=t=>({value:t,basis:"measured"}),Oo=(t,e)=>({value:t,basis:"inferred",assumption:e});function ed(t){if(t.length===0)return[];t.sort((r,n)=>r.start-n.start);const e=[{start:t[0].start,end:t[0].end}];for(let r=1;r<t.length;r++){const n=t[r],o=e[e.length-1];n.start<=o.end?n.end>o.end&&(o.end=n.end):e.push({start:n.start,end:n.end})}return e}function yy(t){let e=0;for(const r of t)e+=r.end-r.start;return e}function H0(t){const e=t.filter(s=>s.end>s.start).flatMap(s=>[{at:s.start,delta:1},{at:s.end,delta:-1}]).sort((s,i)=>s.at-i.at||s.delta-i.delta);let r=0,n=e[0]?.at??0,o=0;for(const s of e)r>=2&&(o+=s.at-n),r+=s.delta,n=s.at;return o}function gy(t){if(t.length===0)return{peak:0,at:0};const e=[];for(const s of t)e.push({t:s.start,d:1}),e.push({t:s.end,d:-1});e.sort((s,i)=>s.t-i.t||s.d-i.d);let r=0,n=0,o=e[0].t;for(const s of e)r+=s.d,r>n&&(n=r,o=s.t);return{peak:n,at:o}}function F0(t){if(t.length===0)return;const e=[...t].sort((n,o)=>n-o),r=e.length>>1;return e.length%2?e[r]:(e[r-1]+e[r])/2}function ho(t,e,r=t.startedAt){const n=Math.max(r,t.startedAt),o=Math.min(e,t.endedAt??(t.status==="idle"?t.lastActivityAt:e));return{start:n,end:Math.max(n,o)}}function td(t,e){return t.waitingMs+(t.waitingSince===void 0?0:Math.max(0,e-t.waitingSince))}function rd(t){const e=t.now,r=[...t.executions.values()];let n=0,o=0,s=0;const i={tokens:0,tools:0,requests:0};let a=0,c=0,u=0,d=0,l=0;const m=[],p=new Map;for(const x of r){n+=dy(x),vt(x.measures,Z.steps)!==void 0&&i.requests++;const D=jr(x.measures),w=po(x);D!==void 0&&(o+=D,i.tokens++),w!==void 0&&(s+=w,i.tools++),x.status==="completed"&&x.outcome!=="interrupted"?a++:x.status==="failed"?c++:x.status==="waiting"?u++:x.status==="idle"&&d++;const $=ho(x,e,t.dayStart);m.push($),l+=x.waitingMs,x.waitingSince!==void 0&&(l+=Math.max(0,e-x.waitingSince));let E=p.get(x.machineId);E||(E={machineId:x.machineId,executions:0,tokens:0,computeTime:0},p.set(x.machineId,E)),E.executions++,E.tokens+=jr(x.measures)??0,E.computeTime+=$.end-$.start}const h=ed(m.map(x=>({...x}))),{peak:v,at:g}=gy(m),I=W0(t),N=G0(I);let S=null;for(const x of I)(!S||x.end-x.start>S.end-S.start)&&(S=x);let T=0;for(const x of t.sessions.values())x.executionIds.some(D=>t.executions.has(D))&&T++;return{requests:ft(n),sessions:ft(T),executions:ft(r.length),tokens:ft(o),toolCalls:ft(s),accounting:i,timeInFlight:Oo(yy(h),my),parallelTime:Oo(H0(m),"Wall-clock time in this period with at least two runs in flight. Parallel intervals count once; waiting is included and trailing idle silence is excluded."),peakConcurrency:r.some(x=>x.startBasis==="inferred"||x.endBasis==="inferred"||x.status==="idle")?Oo(v,"Peak overlap of the recorded run intervals in this period. Some bounds are inferred, or an idle interval ends at its last observed output."):ft(v),peakConcurrencyAt:ft(g),contextSwitches:Oo(N,"Changes between successive non-overlapping groups of runs, each confined to one known working directory. Groups containing concurrent work in different directories are excluded. This does not measure human attention."),longestContextSpan:Oo(S,"Longest span of consecutive runs in one working directory, including gaps of up to 15 minutes. Other contexts may run concurrently. This does not measure human focus."),waitingOnYou:ft(l),completed:ft(a),failed:ft(c),waiting:ft(u),idle:ft(d),byMachine:p,contextSpans:I,transfers:ft(t.transfers.size)}}function W0(t){const e=[];for(const n of t.executions.values()){const o=t.sessions.get(n.sessionId);if(!o?.context)continue;const s=ho(n,t.now,t.dayStart);s.end>s.start&&e.push({context:o.context,...s})}e.sort((n,o)=>n.start-o.start);const r=[];for(const n of e){const o=r[r.length-1];o&&o.context===n.context&&n.start<=o.end?n.end>o.end&&(o.end=n.end):o&&o.context===n.context?n.start-o.end<=K0?o.end=Math.max(o.end,n.end):r.push({context:n.context,start:n.start,end:n.end}):r.push({context:n.context,start:n.start,end:n.end})}return r}const K0=15*6e4;function G0(t){let e=-1/0,r=new Set,n,o=0;const s=()=>{const i=r.size===1?[...r][0]:void 0;n!==void 0&&i!==void 0&&n!==i&&o++,n=i};for(const i of t)i.end<=i.start||(i.start>=e&&(r.size>0&&s(),r=new Set),r.add(i.context),e=Math.max(e,i.end));return r.size>0&&s(),o}function q0(t){return{key:t,runs:0,tokens:0,tokenRuns:0,medianRuns:0,computeMs:0,failed:0,waitingMs:0,toolCalls:0}}function Qs(t,e){const r=new Map,n=new Map;for(const o of t.executions.values()){const s=e(o,t.sessions.get(o.sessionId));if(s===void 0)continue;let i=r.get(s);i||(i=q0(s),r.set(s,i)),i.runs++;const a=jr(o.measures);if(a!==void 0&&(i.tokens+=a,i.tokenRuns++,o.endedAt!==void 0&&o.startedAt>=t.dayStart&&o.endedAt<=t.now&&o.endedAt<t.dayEnd)){let u=n.get(s);u||(u=[],n.set(s,u)),u.push(a)}const c=ho(o,t.now,t.dayStart);i.computeMs+=c.end-c.start,i.waitingMs+=td(o,t.now),i.toolCalls+=po(o)??0,o.status==="failed"&&i.failed++}for(const[o,s]of n){const i=r.get(o);i&&(i.medianTokens=F0(s),i.medianRuns=s.length)}return[...r.values()].sort((o,s)=>s.computeMs-o.computeMs)}function z0(t){const e={input:0,output:0,cacheRead:0,reasoning:0,total:0};for(const r of t.executions.values()){const n=uy(r.measures);e.input+=n.input,e.output+=n.output,e.cacheRead+=n.cacheRead,e.reasoning+=n.reasoning}return e.total=e.input+e.output+e.cacheRead,e}function Y0(t){const e={count:0,totalMs:0,longestMs:0,openNow:0};for(const r of t.executions.values()){for(const n of r.waits){e.count++;const o=n.end-n.start;e.totalMs+=o,o>e.longestMs&&(e.longestMs=o)}if(r.waitingSince!==void 0){e.count++,e.openNow++;const n=t.now-r.waitingSince;e.totalMs+=n,n>e.longestMs&&(e.longestMs=n)}}return e}function vy(t){const e={toolCalls:0,toolErrors:0,retries:0,failed:0,interrupted:0,completed:0};for(const r of t.executions.values())e.toolCalls+=po(r)??0,e.toolErrors+=xi(r),e.retries+=su(r),r.status==="failed"?e.failed++:r.outcome==="interrupted"?e.interrupted++:r.outcome==="completed"&&e.completed++;return e}function Yf(t,e){const r=[...t.executions.values()].map(i=>{const a=ho(i,t.now);return{start:Math.max(t.dayStart,a.start),end:Math.min(t.now,a.end)}}).filter(i=>i.end>i.start);if(r.length===0)return[];const n=ed(r.map(i=>({...i}))),o=new Date(t.dayStart);e==="day"?o.setHours(0,0,0,0):o.setMinutes(0,0,0);const s=[];for(let i=o.getTime();i<t.now;){const a=new Date(i);e==="day"?a.setDate(a.getDate()+1):a.setTime(i+36e5);const c=a.getTime(),u=n.reduce((l,m)=>l+Math.max(0,Math.min(m.end,c)-Math.max(m.start,i)),0),d=r.filter(l=>l.start<c&&l.end>i).map(l=>({start:Math.max(l.start,i),end:Math.min(l.end,c)}));s.push({from:i,to:c,computeMs:u,runs:d.length,peak:gy(d).peak}),i=c}return s}const nd="SHAPES FIELD",od="METADATA — DOES NOT SHAPE FIELD";function sd(t){const e=new Date(t),r=n=>String(n).padStart(2,"0");return`${r(e.getHours())}:${r(e.getMinutes())}:${r(e.getSeconds())}`}function Xf(t){const e=new Date(t),r=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())} ${sd(t).slice(0,5)}`}function X0(t){return fe(t).toUpperCase().replace(/(\d)([HMS])/g,"$1 $2").replace(/\bM\b/g,"MIN")}function Jf(t,e,r,n,o=()=>{},s){if(r==="mass")return Q0(t,e,n);if(r==="coupling")return eA(t,n);const i=t.executions.get(n);if(!i)return null;const a=s?.[n],c=a?{...i,startedAt:a.at,startBasis:a.basis,boundsAssumption:a.assumption??i.boundsAssumption}:i;return J0(t,e,c,r,o("execution",n))}function J0(t,e,r,n,o){const s=t.sessions.get(r.sessionId),i=t.machines.get(r.machineId),c=e.disturbances.find(I=>I.id===r.id)?.statusSince??r.endedAt??r.startedAt,u=r.startBasis==="inferred"||r.endBasis==="inferred",d=jr(r.measures),l=r.outcome==="interrupted",m=[{key:"MACHINE",value:(i?.name??r.machineId).toUpperCase()},{key:"STATE",value:l?"STOPPED":r.status.toUpperCase(),tone:l?void 0:r.status},{key:"SINCE",value:sd(c)},d===void 0?{key:"TOKENS",value:"NOT OBSERVED",tone:"absent",note:"This source does not persist token accounting."}:{key:"TOKENS",value:ze(d)}];if(s){const I=s.executionIds.indexOf(r.id),N=e.plinths.some(T=>T.id===s.id),S=I>=0?`${I+1} OF ${s.executionIds.length}`:`OF ${s.executionIds.length}`;m.push({key:"SESSION",value:N?`${S} · PLINTH`:S})}const p=Z0(t,r.id),h=[r.model??s?.model?{key:"MODEL",value:r.model??s?.model}:{key:"MODEL",value:"not observed",tone:"absent",note:"This source does not record the model."}];s?.projectLabel&&h.push({key:"PROJECT",value:s.projectLabel}),s?.context&&h.push({key:"FOLDER",value:Ne(s.context),note:s.context}),h.push({key:"SOURCE",value:[r.executor,p===void 0?void 0:`pid ${p}`].filter(Boolean).join(" · "),note:o}),h.push({key:"REQUESTS",value:String(dy(r))}),h.push({key:"STARTED",value:`${r.startBasis==="inferred"?"~":""}${Xf(r.startedAt)}`,note:r.startBasis==="inferred"?r.boundsAssumption??"The start bound was inferred by the source.":void 0}),r.endedAt!==void 0&&h.push({key:"ENDED",value:`${r.endBasis==="inferred"?"~":""}${Xf(r.endedAt)}`,note:r.endBasis==="inferred"?r.boundsAssumption??"The end bound was inferred by the source.":void 0});const v=po(r);if(h.push(v===void 0?{key:"TOOL CALLS",value:"not observed",tone:"absent",note:"This source does not count discrete operations."}:{key:"TOOL CALLS",value:Jb(v)}),h.push({key:"ELAPSED",value:`${fe((r.endedAt??t.now)-r.startedAt)}${u?" · inferred":""}`,note:[u?r.boundsAssumption:void 0,r.startedAt<t.dayStart?"Full elapsed interval includes time before the selected window.":void 0].filter(Boolean).join(" · ")||void 0}),d!==void 0){const I=uy(r.measures);h.push({key:"INPUT",value:ze(I.input)},{key:"OUTPUT",value:ze(I.output)}),h.push({key:"CACHE READ",value:ze(I.cacheRead)},{key:"REASONING",value:ze(I.reasoning)})}xi(r)>0&&h.push({key:"TOOL ERRORS",value:String(xi(r)),tone:"failed"}),su(r)>0&&h.push({key:"RETRIES",value:String(su(r)),tone:"waiting",note:"Provider retries."}),(r.waits.length>0||r.waitingMs>0||r.waitingSince!==void 0)&&h.push({key:"BLOCKED",value:`${fe(td(r,t.now))} on you · ${r.waits.length+(r.waitingSince===void 0?0:1)}×${r.waitingSince===void 0?"":" · still waiting"}`,tone:"waiting"}),r.depth>0&&h.push({key:"SUB-AGENT",value:`depth ${r.depth}`});const g=!l&&(r.status==="running"||r.status==="waiting");return{id:r.id,eyebrow:n==="stratum"||!g?"SELECTED · RUN":"SELECTED · PROCESS",title:r.label.toUpperCase(),state:{text:l?"STOPPED":g?`${r.status.toUpperCase()} · ${X0(t.now-c)}`:r.status.toUpperCase(),status:l?void 0:r.status},groups:[{title:nd,metadata:!1,rows:m},{title:od,metadata:!0,rows:h}],failure:r.failure?`${r.failure.code}: ${r.failure.message}`:void 0,reveal:o}}function Z0(t,e){for(const r of t.relationships){if(r.kind!=="ran-as")continue;const n=r.from.type==="execution"&&r.from.id===e&&r.to.type==="process"?r.to.id:r.to.type==="execution"&&r.to.id===e&&r.from.type==="process"?r.from.id:void 0;if(n)return t.processes.get(n)?.pid}}function Q0(t,e,r){const n=t.machines.get(r);if(!n)return null;let o=0,s=0,i=0,a;for(const p of t.executions.values()){if(p.machineId!==n.id)continue;const h=jr(p.measures);h!==void 0&&(a=(a??0)+h),p.status==="running"?o++:p.status==="waiting"?s++:i++}const u=[{key:"KIND",value:(e.masses.find(p=>p.id===r)?.kind??n.kind).toUpperCase()},{key:"RUNNING",value:String(o),tone:o>0?"running":void 0}];s>0&&u.push({key:"WAITING",value:String(s),tone:"waiting"}),u.push({key:"RAN TODAY",value:String(i)});const d=[a===void 0?{key:"TOKENS",value:"not observed",tone:"absent",note:"No execution in this window reported token accounting."}:{key:"TOKENS",value:ze(a)}],l=t.processTotals;if(l){const p=new Set;for(const h of t.relationships)h.kind==="ran-as"&&(h.from.type==="process"&&p.add(h.from.id),h.to.type==="process"&&p.add(h.to.id));d.push({key:"PROCESSES",value:`${l.observed} observed`}),d.push({key:"LAST 5 MIN",value:`${l.recentlySeen} seen`,note:"Processes with a liveness observation in the last five minutes. The sampler never witnesses an exit, so recency is the honest liveness signal."}),d.push({key:"ATTRIBUTED",value:`${p.size} of ${l.observed}`,note:"Processes tied to a session or execution by resolved identity. The rest are observed, not explained."})}const m=o+s;return{id:r,eyebrow:"SELECTED · MACHINE",title:n.name.toUpperCase(),state:m>0?{text:`${m} ACTIVE`,status:o>0?"running":"waiting"}:{text:"QUIET"},groups:[{title:nd,metadata:!1,rows:u},{title:od,metadata:!0,rows:d}]}}function eA(t,e){const r=t.transfers.get(e);if(!r)return null;const n=t.machines.get(r.fromMachineId)?.name??r.fromMachineId,o=t.machines.get(r.toMachineId)?.name??r.toMachineId;return{id:e,eyebrow:"SELECTED · TRANSFER",title:`${n} → ${o}`.toUpperCase(),state:{text:"TRANSFERRING",status:"running"},groups:[{title:nd,metadata:!1,rows:[{key:"FROM",value:n.toUpperCase()},{key:"TO",value:o.toUpperCase()},{key:"SINCE",value:sd(r.startedAt)}]},{title:od,metadata:!0,rows:[{key:"WHAT",value:r.label},{key:"SIZE",value:Zb(r.bytes)}]}]}}const tA=6e4;function rA(t,e){const r=[],n=e.contextSpans,o=e.longestContextSpan.value;if(e.executions.value===0)return{headline:"NO RUN RECORDS",clauses:["No runs observed in this window. This does not establish inactivity."]};const s=e.peakConcurrency.value>1?`UP TO ${e.peakConcurrency.value} RUNS AT ONCE`:"ONE RUN AT A TIME";if(e.peakConcurrency.value>=2?(r.push(`Up to ${e.peakConcurrency.value} runs in flight at once; ${fe(e.timeInFlight.value)} of wall-clock time had a run in flight.`),r.push(`Parallel runs overlapped for ${fe(e.parallelTime.value)} within this period; each instant counts once.`)):r.push(`Runs happened one at a time, across ${fe(e.timeInFlight.value)} of wall-clock time.`),o&&r.push(`The longest context span covered ${fe(o.end-o.start)} in ${Ne(o.context)}; gaps of up to 15 minutes are included.`),e.contextSwitches.value>0){const i=new Set(n.map(a=>a.context)).size;r.push(`${e.contextSwitches.value} sequential ${e.contextSwitches.value===1?"change":"changes"} between working directories, across ${i} contexts; concurrent contexts are excluded.`)}if(e.waitingOnYou.value>tA&&r.push(`${fe(e.waitingOnYou.value)} was spent with a run waiting on your answer.`),e.failed.value>0&&r.push(`${e.failed.value} of ${e.executions.value} runs ended in failure; ${e.completed.value} completed.`),e.byMachine.size>1){const i=[...e.byMachine.values()].sort((a,c)=>c.computeTime-a.computeTime).map(a=>`${t.machines.get(a.machineId)?.name??a.machineId} ${fe(a.computeTime)}`);r.push(`Summed run intervals by machine: ${i.join(", ")}.`)}return{headline:s,clauses:r}}const Zf="(no model)";function nA(t){if(t.medianTokens===void 0)return t.tokenRuns>0?{text:"no complete runs in this window for a median",title:"Token accounting is present. The median requires ended runs with both bounds inside this window; open and boundary-crossing runs are excluded.",absent:!0}:{text:"no token accounting",title:"No run in this group reports token accounting, so there is no figure — not a figure of zero.",absent:!0};if(t.medianRuns===1)return{text:`single run ${ze(t.medianTokens)}`,title:"One ended run fully inside this window reports accounting, so this is its figure, not a median. Open and boundary-crossing runs are excluded.",absent:!1};const e=t.medianRuns===t.runs?`${t.runs}`:`${t.medianRuns} of ${t.runs}`;return{text:`median ${ze(t.medianTokens)} over ${e} runs`,title:`Median billed tokens per complete run, over the runs in this group fully inside this window that have ended and whose source reports token accounting — ${t.medianRuns} of ${t.runs} here. Runs still in flight are excluded: their totals are partial. Boundary-crossing runs are excluded. Runs whose source persists no accounting are excluded: absence is not zero. Same window as the rest of TODAY.`,absent:!1}}function oA(t,e,r){if(r&&r.reported===0)return jt("WAITING ON YOU","—",void 0,{note:"not reported by sources in this window"});const n=e.count>0?`${e.count} ${e.count===1?"block":"blocks"} · longest ${fe(e.longestMs)}`:void 0,o=r&&r.reported<r.runs?`from the ${r.reported} of ${r.runs} runs whose sources report waits`:void 0;return jt("WAITING ON YOU",fe(t.value),t,{tone:t.value>0?"waiting":void 0,note:[n,o].filter(Boolean).join(" · ")||void 0})}function jt(t,e,r,n={}){const o=r?.basis==="inferred";return{key:t,value:e,inferred:o,assumption:o?r?.assumption:void 0,...n}}function Cc(t,e,r,n,o){return jt(t,r>0?ze(e.value):"—",e,{note:r===0?"not reported in this window":[o,r<n?`reported for ${r} of ${n} runs`:void 0].filter(Boolean).join(" · ")||void 0})}function sA(t){const e=[["CACHE READS",t.cacheRead],["INPUT",t.input],["OUTPUT",t.output]].map(([r,n])=>({key:r,value:ze(n),fraction:n/Math.max(1,t.total),percent:Math.round(n/Math.max(1,t.total)*100),percentLabel:wi(n,t.total)}));return t.reasoning>0&&e.push({key:"REASONING · OF OUTPUT",value:ze(t.reasoning),subset:!0,fraction:t.reasoning/Math.max(1,t.output),percent:Math.round(t.reasoning/Math.max(1,t.output)*100),percentLabel:wi(t.reasoning,t.output)}),e}function Nc(t,e,r){const n=t[0]?.computeMs??0;return t.map(o=>({key:o.key,label:e(o.key),detail:`${o.runs} ${o.runs===1?"run":"runs"}${o.tokenRuns>0?` · ${ze(o.tokens)} tok${o.tokenRuns<o.runs?` (${o.tokenRuns}/${o.runs} reported)`:""}`:" · tokens not reported"} · ${fe(o.computeMs)}`,failed:o.failed,fraction:n>0?o.computeMs/n:0,median:r?nA(o):void 0}))}function Qf(t,e,r="today"){const n=rd(t),o=rA(t,n),s=z0(t),i=Y0(t),a=vy(t),c=r==="today"?Yf(t,"hour"):[],u=r==="last-7d"?Yf(t,"day"):[],d=Qs(t,(A,ae)=>ae?.context),l=Qs(t,A=>A.model??Zf),m=Qs(t,A=>A.machineId),p=[...t.executions.values()],h=p.filter(A=>A.endedAt===void 0),v=p.length-h.length,g=p.filter(A=>A.endBasis==="inferred").length,I=p.filter(A=>(A.measures.errors??0)>0),N=[[I.filter(A=>A.outcome==="completed").length,"completed"],[I.filter(A=>A.status==="failed").length,"failed"],[I.filter(A=>A.outcome==="interrupted").length,"stopped"],[I.filter(A=>A.endedAt===void 0).length,"still open"]],S=Qs(t,A=>A.sessionId).filter(A=>A.tokenRuns>0).sort((A,ae)=>ae.tokens-A.tokens).slice(0,3).map(A=>({sessionId:A.key,label:t.sessions.get(A.key)?.taskLabel??t.sessions.get(A.key)?.label??"Session",detail:`${ze(A.tokens)} tok · ${wi(A.tokens,n.tokens.value)} of reported volume · ${A.runs} runs${A.tokenRuns<A.runs?` · ${A.tokenRuns}/${A.runs} reported`:""}`,fraction:A.tokens/Math.max(1,n.tokens.value)})),T=p.filter(A=>A.depth>0).length,x=n.longestContextSpan.value,D=A=>r==="today"?wf(A):`${new Date(A).toLocaleDateString("en-GB",{day:"2-digit",month:"short"})} ${wf(A)}`,w=(A,ae)=>`${A} ${ae}${A===1?"":"s"}`,$=A=>[[A.filter(ye=>ye.outcome==="completed").length,"completed","completed","completed"],[A.filter(ye=>ye.status==="failed"&&ye.outcome!=="interrupted").length,"failed","failed","failed"],[A.filter(ye=>ye.outcome==="interrupted").length,"stopped","stopped","stopped"],[A.filter(ye=>ye.endedAt===void 0&&ye.status==="waiting").length,"waiting","waiting for your response","need response"],[A.filter(ye=>ye.endedAt===void 0&&ye.status==="running").length,"running","with recent events","with recent events"],[A.filter(ye=>ye.endedAt===void 0&&ye.status==="idle").length,"idle","without a recorded ending","no ending"]].filter(([ye])=>ye>0).map(([ye,we,Wt,He])=>({filter:we,label:`${ye} ${we==="waiting"&&ye===1?"needs response":He}`,text:`${ye} ${Wt}`})),E=A=>$(A).map(ae=>ae.text).join(" · "),B=new Map;for(const A of p){const ae=B.get(A.sessionId)??[];ae.push(A),B.set(A.sessionId,ae)}const C=[...B].map(([A,ae])=>{const ye=t.sessions.get(A),we=ae.map(Kt=>ho(Kt,t.now,t.dayStart)),Wt=yy(ed(we)),He=Math.min(t.now,ae.reduce((Kt,Ir)=>Math.max(Kt,Ir.endedAt??Ir.lastActivityAt),t.dayStart)),$n=ae.reduce((Kt,Ir)=>Math.min(Kt,Math.max(t.dayStart,Ir.startedAt)),t.now),Gr=we.reduce((Kt,Ir)=>Math.max(Kt,Ir.end),$n);return{sessionId:A,label:ye?.taskLabel??ye?.label??"Untitled session",taskLabel:ye?.taskLabel??null,project:ye?.projectLabel??null,context:ye?.context?Ne(ye.context):null,detail:`${w(ae.length,"run")} · ${fe(Wt)} recorded run time · ${D($n)}–${D(Gr)}`,outcomes:E(ae),states:$(ae),time:fe(Wt),span:`${D($n)}–${D(Gr)}`,runCount:ae.length,timeMs:Wt,lastAt:He}}).sort((A,ae)=>ae.timeMs-A.timeMs||ae.lastAt-A.lastAt||A.sessionId.localeCompare(ae.sessionId)),P=[],L=h.filter(A=>A.status==="waiting"),te=h.filter(A=>A.status==="running"),U=h.filter(A=>A.status==="idle");L.length&&P.push({filter:"waiting",title:`${w(L.length,"run")} waiting for your response`,detail:"The source explicitly recorded a request for input or approval."}),te.length&&P.push({filter:"running",title:`${w(te.length,"run")} with recent events`,detail:"An ending has not been recorded. Open the runs to inspect their latest events."}),a.failed&&P.push({filter:"failed",title:`${w(a.failed,"run")} ended with a failure`,detail:"Open the records to inspect the reported failure. A later retry may be a separate run."}),a.interrupted&&P.push({filter:"stopped",title:`${w(a.interrupted,"run")} stopped before completion`,detail:"The source recorded an interruption; it does not say whether stopping was intentional."}),I.length&&P.push({filter:"toolErrors",title:`${w(I.length,"run")} reported tool errors`,detail:N.filter(([A])=>A>0).map(([A,ae])=>`${A} ${ae}`).join(" · ")+". Error resolution is not recorded."}),U.length&&P.push({filter:"idle",title:`${w(U.length,"run")} without a recorded ending`,detail:(U.length===1?`Last event ${D(U[0].lastActivityAt)}. `:"No recent events. ")+"Activity beyond those events is unknown."});const V=["waiting","failed","running","idle","stopped"].map(A=>P.find(ae=>ae.filter===A)).find(A=>A!==void 0)??null,z=V?p.filter(A=>V.filter==="stopped"?A.outcome==="interrupted":V.filter==="failed"?A.status==="failed"&&A.outcome!=="interrupted":A.endedAt===void 0&&A.status===V.filter):[],se=[...new Set(z.map(A=>A.sessionId))],ve=se.length===1?t.sessions.get(se[0]):void 0,Ae=[ve?.projectLabel,ve?.taskLabel].filter(Boolean).join(" · "),_e=V?{...V,detail:(Ae?Ae+". ":"")+V.detail}:null,Ie=[Cc("REQUESTS",n.requests,n.accounting.requests,p.length),jt("RUNS",String(n.executions.value),n.executions,{note:T>0?`${T} of them sub-agents`:void 0}),jt("SESSIONS",String(n.sessions.value),n.sessions),Cc("TOKENS",n.tokens,n.accounting.tokens,p.length,`${wi(s.cacheRead,s.total)} cache reads${h.some(A=>Object.keys(A.measures).some(ae=>ae.startsWith("tokens.")))?" · includes accumulating open runs":""}`),Cc("TOOL CALLS",n.toolCalls,n.accounting.tools,p.length,a.toolErrors>0?`${a.toolErrors} tool ${a.toolErrors===1?"error":"errors"}`:void 0),jt("TIME IN FLIGHT",fe(n.timeInFlight.value),n.timeInFlight,{note:`${h.length>0?"provisional open intervals · ":""}within period · includes waiting · parallel intervals count once`}),jt("TIME WITH PARALLEL RUNS",fe(n.parallelTime.value),n.parallelTime),jt("PEAK CONCURRENCY",n.peakConcurrency.value>0?`${n.peakConcurrency.value} · ${D(n.peakConcurrencyAt.value)}`:"0",n.peakConcurrency),jt("CONTEXT CHANGES",String(n.contextSwitches.value),n.contextSwitches,{note:`sequential only · known contexts: ${d.filter(A=>A.key.length>0).length}`}),jt("LONGEST CONTEXT SPAN",x?fe(x.end-x.start):"—",n.longestContextSpan,{note:x?`${Ne(x.context)} · ${D(x.start)}–${D(x.end)}`:void 0}),oA(n.waitingOnYou,i,e),jt("FAILED",v>0?String(a.failed):"—",void 0,{tone:a.failed>0?"failed":void 0,note:v>0?`${v} terminal records${g?` · ${g} endings inferred`:""}${h.length?` · ${h.length} runs still open`:""}${a.interrupted?` · ${a.interrupted} stopped`:""}`:"no terminal outcomes recorded yet"})],q=c.length>0?c.reduce((A,ae)=>ae.computeMs>A.computeMs?ae:A,c[0]):void 0,qe=A=>`${String(A).padStart(2,"0")}:00`,rt=[{title:"WHERE THE TIME WENT",rows:Nc(d,Ne,!1)}];return m.length>0&&rt.push({title:"BY MACHINE",rows:Nc(m,A=>t.machines.get(A)?.name??A,!1)}),l.length>0&&rt.push({title:"BY MODEL",rows:Nc(l,A=>A===Zf?"model not observed":A,!0)}),{activity:{summary:`${w(p.length,"run")} recorded in ${w(B.size,"session")}.`,leadSessionId:C[0]?.timeMs>0?C[0].sessionId:null,focus:_e,outcomes:E(p),states:$(p),timing:`Recorded run intervals cover ${fe(n.timeInFlight.value)}. `+(n.parallelTime.value>0?`For ${fe(n.parallelTime.value)}, two or more runs overlapped.`:"No overlapping run intervals were recorded."),timingSummary:`${fe(n.timeInFlight.value)} in recorded runs · waiting included · overlaps counted once${h.length?" · open runs estimated":""}`,timingNote:"Waiting is included; overlapping intervals count once. "+(h.length?"Open intervals are provisional: silence can shorten the estimate and later events can revise it. ":"")+"This measures recorded intervals, not CPU time or your time at work.",checks:P,sessions:C},observation:"Only events 057 could read are included. Gaps may mean missing data; they do not establish inactivity.",overview:`${p.length} runs observed · ${a.completed} completed · ${a.failed} failed · ${a.interrupted} stopped · ${h.length} still open${g?` · ${g} endings inferred`:""}`,errorOutcomes:I.length?`${I.length} runs reported tool errors: ${N.filter(([A])=>A>0).map(([A,ae])=>`${A} ${ae}`).join(", ")}. Completion does not establish that every error was resolved.`:void 0,contributors:S,headline:o.headline,empty:p.length===0?"No runs observed in this window. This does not establish that no work happened.":void 0,clauses:[...o.clauses],measures:Ie.map(A=>({...A,...iA[A.key]})),hours:c.map(A=>({hour:new Date(A.from).getHours(),from:Math.max(t.dayStart,A.from),to:Math.min(t.now,A.to),partial:A.from<t.dayStart||A.to>t.now,computeMs:A.computeMs,runs:A.runs,peak:A.peak})),busiest:q?`most time in flight ${qe(new Date(q.from).getHours())} · ${fe(q.computeMs)}`:void 0,timeline:r==="last-7d"?{title:"DAY BY DAY",legend:"Time in flight within the selected window · first and last days may be partial · brighter columns contain parallel runs",buckets:u.map(A=>({label:new Date(A.from).toLocaleDateString("en-GB",{day:"2-digit",month:"short"}).toUpperCase(),from:Math.max(t.dayStart,A.from),to:Math.min(t.now,A.to),partial:A.from<t.dayStart||A.to>t.now,computeMs:A.computeMs,fraction:A.computeMs/(A.to-A.from),runs:A.runs,peak:A.peak}))}:void 0,groups:rt,tokens:n.accounting.tokens===0?[]:sA(s),tokensNote:n.accounting.tokens===0?"Token accounting is not reported in this window.":"Input, output and cache reads form the total. Reasoning is part of output and is never added again. Cache reads count replayed context, not newly generated output.",failures:p.filter(A=>A.status==="failed").sort((A,ae)=>ae.startedAt-A.startedAt).slice(0,12).map(A=>({id:A.id,at:D(A.startedAt),label:A.label,reason:A.failure?`${A.failure.code}: ${A.failure.message}`:"failed"})),notAvailable:[{key:"COST",text:"Every source here reports tokens or CPU time; none reports money. Converting one to the other needs a price table 057 does not have, so no cost figure is shown anywhere."},{key:"TOKENS, FROM SOME SOURCES",text:"Cursor persists no usage and 0x2F records none; their runs read NOT OBSERVED rather than 0, and the token totals sum only the runs that report."},{key:"CLAUDE IN A BROWSER",text:"Claude on claude.ai — chat, Claude Design, cloud Claude Code sessions — runs on Anthropic's servers and writes nothing to this Mac. Only Claude Code sessions that run here (a terminal, an editor, the desktop app's Code tab) leave the files 057 reads; the browser is seen as a process, never as work."},{key:"MACHINE-TO-MACHINE TRANSFER",text:"Every observed source is single-host. Transfers are modelled and the field renders them, but no real adapter emits one; only the synthetic source does."},{key:"PROCESS EXITS",text:"The OS collector samples; an exit is inferred from disappearance between samples, never witnessed."},{key:"OUTCOME QUALITY",text:"The log records that a run completed, not whether the work was any good."}]}}const iA={REQUESTS:{title:"REPORTED REQUESTS",meaning:"Model requests counted by sources that report them. One run can make several requests."},RUNS:{title:"RECORDED RUNS",meaning:"Recorded attempts or turns inside AI-tool sessions. This is not a count of solved tasks."},SESSIONS:{title:"SESSIONS WITH RUNS",meaning:"Conversations or task containers with at least one run in this period."},TOKENS:{title:"REPORTED TOKENS",meaning:"Input + output + cache reads. Repeated context can dominate this total; it is not generated output alone."},"TOOL CALLS":{title:"REPORTED TOOL CALLS",meaning:"Operations such as commands or tool requests. Errors can occur in a run that later completes."},"TIME IN FLIGHT":{title:"RECORDED RUN TIME",meaning:"Time covered by at least one recorded run, including waiting. Overlapping runs count once."},"TIME WITH PARALLEL RUNS":{title:"TIME WITH OVERLAPPING RUNS",meaning:"Time covered by two or more recorded run intervals. This does not measure CPU load."},"PEAK CONCURRENCY":{title:"MOST RUNS AT ONCE",meaning:"Largest number of overlapping run intervals, followed by the local time it was first reached."},"CONTEXT CHANGES":{title:"WORKING FOLDER CHANGES",meaning:"Sequential changes between observed working folders. Parallel folders have no definite order."},"LONGEST CONTEXT SPAN":{title:"LONGEST WORKING FOLDER SPAN",meaning:"Recorded run continuity in one folder, joining gaps up to 15 minutes. This does not measure human focus."},"WAITING ON YOU":{title:"WAITING FOR YOUR RESPONSE",meaning:"Recorded requests for your input or approval. Summed across runs; simultaneous waits add together."},FAILED:{title:"RUNS ENDED WITH FAILURE",meaning:"Runs with a recorded failure outcome. Later retries and the quality of the task result are separate."}};function ep(t,e=!1){const{period:r,asOf:n,project:o,today:s,comparison:i}=t,a=u=>new Date(u).toISOString(),c=["057 · ACTIVITY SUMMARY",`Period: ${r.label}`,`From (inclusive, UTC): ${a(r.from)}`,`To (exclusive, UTC): ${a(r.to)}`,`Snapshot (UTC): ${a(n)}`,`Working context: ${o?e?o.privateLabel:o.label:"ALL WORKING CONTEXTS"}`];o&&!e&&c.push(`Working context: ${o.detail}`),e&&c.push("Privacy Mode: identifying labels and free-text details omitted."),c.push("","OBSERVATION",s.empty??"Records are present. Historical observation continuity is unknown; absence of records does not establish inactivity.","","MEASURES");for(const u of s.measures)c.push(`${u.key}: ${u.value}${u.inferred?" [inferred]":""}`),u.note&&(!e||u.key!=="LONGEST CONTEXT SPAN")&&c.push(` ${u.note}`),u.assumption&&c.push(` Basis: ${u.assumption}`);if(c.push("","TIME DEFINITIONS","Time in flight is the union of run intervals within this window. Parallel intervals count once.","Group run time adds run intervals within the window. Parallel intervals add together.","LOG run intervals are clipped to this window and exclude trailing idle silence; parallel runs add together.","Tokens and tool counts include only accounting events in the selected half-open window. Open runs are accumulating.","The inspector separates these period contributions from the full retained run record as of the window end.","Completion records an outcome, not the quality of the work."),!e){c.push("","READING THE PERIOD",s.headline,...s.clauses);for(const u of s.groups){c.push("",u.title);for(const d of u.rows)c.push(`${d.label}: ${d.detail}${d.failed?` · ${d.failed} failed`:""}${d.median?` · ${d.median.text}`:""}`,...d.median?[` ${d.median.title}`]:[])}if(s.failures.length){c.push("","FAILURE RECORDS");for(const u of s.failures)c.push(`${u.at} · ${u.label}: ${u.reason}`)}}c.push("","TOKEN COMPOSITION",s.tokensNote);for(const u of s.tokens)c.push(`${u.key}: ${u.value} · ${u.percentLabel}${u.subset?" (subset of output)":""}`);if(i){c.push("","PERIOD COMPARISON",t.comparisonLabel?`B: ${t.comparisonLabel}. Exact bounds and qualifications follow.`:"B immediately precedes A and has the same duration.",i.verdict??"");for(const u of i.periods??[])c.push(`${u.k}: ${u.w} · ${u.s}`);for(const u of i.evidence){const d=u.comparison;d&&c.push(`${u.k}: A ${d.a} [${d.aEvidence}] · B ${d.b} [${d.bEvidence}] · ${d.eligibility}`,...d.reasons.map(l=>` ${l}`))}for(const u of i.reasons)c.push(`${u.k}: ${u.v}`)}c.push("","SOURCE LIMITS");for(const u of s.notAvailable)c.push(`${u.key}: ${u.text}`);return c.join(`
10
+ `)+`
11
+ `}function id(t){const e=t?.context.trim()||t?.projectLabel?.trim();if(!e)return{key:'["unassigned"]',kind:"unassigned"};const r=t?.context.trim()?"context":"label",n=t?.machineId??"";return{key:JSON.stringify([r,n,e]),kind:r,machine:n,value:e}}function li(t){if(t.length>4096)return null;try{const e=JSON.parse(t);if(!Array.isArray(e))return null;if(t==='["unassigned"]'&&e.length===1&&e[0]==="unassigned")return{key:t,kind:"unassigned"};const[r,n,o]=e;return e.length!==3||r!=="context"&&r!=="label"||typeof n!="string"||typeof o!="string"||!o.trim()?null:JSON.stringify([r,n,o])===t?{key:t,kind:r,machine:n,value:o}:null}catch{return null}}function ls(t,e){if(e===void 0)return t;const r=new Map([...t.executions].filter(([,o])=>id(t.sessions.get(o.sessionId)).key===e)),n=new Set([...r.values()].map(o=>o.sessionId));return{...t,executions:r,sessions:new Map([...t.sessions].filter(([o])=>n.has(o)).map(([o,s])=>[o,{...s,executionIds:s.executionIds.filter(i=>r.has(i))}])),active:new Set([...t.active].filter(o=>r.has(o)))}}function Tc(t,e,r={}){const n=new Set(e.disturbances.map(i=>i.id)),o=new Set(e.strata.map(i=>i.id)),s=[...t.executions.values()].sort((i,a)=>a.startedAt-i.startedAt).map(i=>{const a=t.sessions.get(i.sessionId),c=r.starts?.[i.id],u=c?.at??i.startedAt,d=ho(i,t.now,t.dayStart);return{id:i.id,startedAt:u,endedAt:i.endedAt??null,windowClipped:u<t.dayStart,boundsAssumption:c?.assumption??i.boundsAssumption??null,label:i.label,sessionId:i.sessionId,projectKey:id(a).key,sessionLabel:a?.taskLabel??a?.label??null,taskLabel:a?.taskLabel??null,project:a?.projectLabel??null,toolErrors:xi(i),toolErrorsReported:vt(i.measures,Z.errors)!==void 0,waitsReported:r.waitReportedIds?r.waitReportedIds.includes(i.id):null,depth:i.depth,context:a?.context?Ne(a.context):null,model:i.model??null,status:i.status,stopped:i.outcome==="interrupted",durationMs:d.end-d.start,intervalFrom:d.start,intervalTo:d.end,durationBasis:"window-in-flight",inferred:(c?.basis??i.startBasis)==="inferred"||i.endBasis==="inferred",tokens:jr(i.measures)??null,tools:po(i)??null,waitedMs:td(i,t.now),inField:n.has(i.id)?"disturbance":o.has(i.id)?"stratum":null}});return s.sort((i,a)=>a.startedAt-i.startedAt),{now:t.now,rows:s}}function by(t,e){const r=ls(t,e.key),n=rd(r),o=vy(r).toolErrors,s=e.kind==="unassigned"?"CONTEXT NOT REPORTED":e.kind==="context"?Ne(e.value??""):e.value??"",i=e.machine?t.machines.get(e.machine)?.name??e.machine:void 0,a=e.kind==="unassigned"?"No working context or project label reported":[e.value,i,e.kind==="label"?"grouped by reported label; no working context":void 0].filter(Boolean).join(" · "),c=n.accounting.tokens,u=r.executions.size;let d=2166136261;for(const l of e.key)d=Math.imul(d^l.charCodeAt(0),16777619);return{key:e.key,label:s,detail:a,runs:u,context:e.value,machine:i,privateLabel:e.kind==="unassigned"?"CONTEXT NOT REPORTED":`PROJECT ${(d>>>0).toString(16).padStart(8,"0").toUpperCase()}`,summary:`${u} ${u===1?"run":"runs"} · ${fe(n.timeInFlight.value)} in flight`+(c>0?` · ${ze(n.tokens.value)} tok${c<u?` (${c}/${u} reported)`:""}`:" · tokens not reported")+(o>0?` · ${o} tool ${o===1?"error":"errors"}`:"")}}function aA(t){const e=new Map;for(const r of t.executions.values()){const n=id(t.sessions.get(r.sessionId));e.set(n.key,n)}return[...e.values()].map(r=>by(t,r)).sort((r,n)=>n.runs-r.runs||r.detail.localeCompare(n.detail))}function cA(t,e){const r=e===void 0?null:li(e);return r?by(t,r):null}const ad={width:80,color:!1,ascii:!1},uA={dim:"2",bold:"1",yellow:"33","bold-yellow":"1;33"};class lA{segments=[];length=0;text(e,r){return e.length>0&&(this.segments.push({text:e,role:r}),this.length+=$e(e)),this}at(e,r,n){return this.padTo(e),this.text(r,n)}right(e,r,n){return this.at(e-$e(r)+1,r,n)}append(e){for(const r of e.segments)this.text(r.text,r.role);return this}padTo(e){const r=e-this.length;return r>0?this.text(" ".repeat(r)):this.length>0&&!this.endsWithSpace()&&this.text(" "),this}endsWithSpace(){const e=this.segments[this.segments.length-1];return e!==void 0&&e.text.endsWith(" ")}}function _(){return new lA}function ha(t,e){return`${t.map(r=>dA(r,e.color)).join(`
10
12
  `)}
11
- `}function Bw(t,e){const r=t.segments.map(n=>({...n}));for(;r.length>0&&r[r.length-1].text.trim()==="";)r.pop();if(r.length>0){const n=r[r.length-1];n.text=n.text.trimEnd()}return r.map(n=>{if(!e||!n.role||n.text.trim()==="")return n.text;const s=n.text.length-n.text.trimStart().length,o=n.text.trim(),i=n.text.length-s-o.length;return`${" ".repeat(s)}\x1B[${Nw[n.role]}m${o}\x1B[0m${" ".repeat(i)}`}).join("")}function ke(t){return[...t].length}function $w(t,e){const r=t.split(/\s+/).filter(o=>o.length>0),n=[];let s="";for(const o of r)s.length===0?s=o:ke(s)+1+ke(o)<=e?s+=` ${o}`:(n.push(s),s=o);return(s.length>0||n.length===0)&&n.push(s),n}function $n(t,e,r,n,s,o){const i=Math.max(12,s-Math.max(e,r)),a=$w(n,i),c=[t.at(e,a[0],o)];for(const u of a.slice(1))c.push(_().at(r,u,o));return c}function Yr(t){return t.ascii?{sep:", ",dash:"--",arrow:"->",range:"-"}:{sep:" · ",dash:"—",arrow:"→",range:"–"}}function Bt(t,e){const r=Yr(e).sep,n=r.trim(),s=r.slice(0,r.indexOf(n));return t.text(s).text(n,"dim").text(r.slice(s.length+n.length))}function G(t){return t.replace(/-/g," ")}function Ke(t){return t==="observed"?"dim":void 0}function ie(t){return"value"in t?t.value:void 0}function Ue(t,e){return t===1?e:`${e}s`}function Se(t){return Number.isInteger(t)?t.toLocaleString("en-US"):t.toLocaleString("en-US",{minimumFractionDigits:1,maximumFractionDigits:1})}function Nt(t){if(t<1e3)return String(Math.round(t));if(t<1e6)return`${(t/1e3).toFixed(t<1e4?1:0)}K`;if(t<1e9)return`${(t/1e6).toFixed(t<1e7?1:0)}M`;const e=t/1e9;return`${e.toFixed(e<10?3:e<100?2:1)}B`}function Pe(t){const e=Math.round(t/6e4);return e<1?`${Math.round(t/1e3)}s`:e<60?`${e}m`:`${Math.floor(e/60)}h ${e%60}m`}function Km(t){if(t<6e4)return`${Math.round(t/1e3)}s`;if(t<36e5)return`${Math.round(t/6e4)}m`;const e=Math.round(t/6e4);return`${Math.floor(e/60)}h ${e%60}m`}function Gm(t){const e=Math.round(t/1e3);if(e<60)return`${e}s`;if(e<3600){const n=e%60;return n===0?`${Math.floor(e/60)}m`:`${Math.floor(e/60)}m ${n}s`}const r=Math.round(t/6e4);return`${Math.floor(r/60)}h ${r%60}m`}function Rn(t,e){const r=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(new Date(t)),n=s=>r.find(o=>o.type===s)?.value??"";return{day:`${n("year")}-${n("month")}-${n("day")}`,time:`${n("hour")}:${n("minute")}`,zone:Rw(t,e)}}function Rw(t,e){const r=o=>new Intl.DateTimeFormat(o,{timeZone:e,timeZoneName:"short"}).formatToParts(new Date(t)).find(i=>i.type==="timeZoneName")?.value??"",n=r("en-US");if(!n.startsWith("GMT"))return n;const s=r("en-GB");return s.length>0?s:n}function zs(t,e){const r=Yr(e),n=Rn(t.from,e.timeZone),s=Rn(t.to,e.timeZone);if(n.day===s.day&&n.zone===s.zone)return`${n.day}${r.sep}${n.time}${r.range}${s.time} ${s.zone}`;const o=n.zone===s.zone?"":` ${n.zone}`;return`${n.day} ${n.time}${o} ${r.arrow} ${s.day} ${s.time} ${s.zone}`}function Wc(t,e,r){const n=Rn(t,r.timeZone);return Rn(e.from,r.timeZone).day===Rn(e.to,r.timeZone).day?n.time:`${n.day} ${n.time}`}function Pl(t,e){const r=Rn(t,e.timeZone);return`${r.day} ${r.time} ${r.zone}`}function na(t,e){const r=_().text("057","dim").text(" ").text("COMPUTATIONAL ACTIVITY","bold");return r.length+2+ke(t)<=e?[r.right(e-1,t,"dim")]:[r,_().right(e-1,t,"dim")]}function Ll(t,e,r,n){const s=zs(t,n),o=_();return e.forEach((i,a)=>{a>0&&Bt(o,n),o.text(i.text,i.role)}),e.length===0?[_().text(s)]:ke(s)+2+o.length<=r?[_().text(s).padTo(r-o.length).append(o)]:[_().text(s),o]}function Ys(t){return t==="observed"?void 0:"yellow"}function qm(t){return t==="within-retention"||t==="retained-indefinitely"?void 0:"yellow"}function dt(t,e){const r=t.match(/^\[(.+)\]$/);if(!r)return{text:t,pseudo:!1};const n=G(r[1]);return{text:e==="model"||e==="executor"?`${e} ${n}`:n,pseudo:!0}}function _w(t,e=Dl){const r=Mw(e.width),{summary:n,availability:s}=t,o=[...na("SUMMARY",r.measure),...Ll(t.period,[{text:G(s.observation),role:Ys(s.observation)},{text:G(s.retention.state),role:qm(s.retention.state)}],r.measure,e),Bt(_().text(String(n.executions),"bold").text(` ${Ue(n.executions,"execution")}`),e).text(String(n.sessions),"bold").text(` ${Ue(n.sessions,"session")}`)];for(const i of jw(t,e)){o.push(_(),_().text(i.head,"dim"));const a=Math.max(4,...i.rows.map(c=>c.kind==="model"?(c.tokens??"").length:0));for(const c of i.rows)o.push(...Dw(c,r,a,e))}return ra(o,e)}function Mw(t){if(t>=80)return{measure:79,labelMax:22,figureEnd:33,compositeCol:24,tailCol:35,evidenceCol:67,split:!1,stacked:!1};const e=Math.max(1,t-1);if(t>=56)return{measure:e,labelMax:20,figureEnd:29,compositeCol:4,tailCol:31,evidenceCol:43,split:!0,stacked:!1};const r=Math.min(43,Math.max(24,e-12));return{measure:e,labelMax:20,figureEnd:29,compositeCol:4,tailCol:31,evidenceCol:r,split:!0,stacked:!0}}function jw(t,e){const{summary:r,availability:n}=t,s=Yr(e).dash,o=(v,g,C,A)=>{const I=ie(g);return I===void 0?{kind:"figure",label:v,figure:s,dash:!0,evidence:g.state}:{kind:"figure",label:v,figure:C(I),dash:!1,tail:A?.(I),evidence:g.state}},i=(v,g)=>({kind:"figure",label:v,figure:String(g),dash:!1}),a=r.executions===0&&n.observation!=="observed"?{head:"RECORDED LIFECYCLE",rows:[{kind:"prose",text:"no execution records; zero work is not established"}]}:{head:n.observation==="observed"?"NOW":"RECORDED LIFECYCLE",rows:[i("running",r.runningNow),o("waiting",r.waitingNow,String),i("idle",r.idleNow)]},c=r.terminalExecutionDuration,u=ie(c),l=u===void 0?{kind:"figure",label:"terminal execution",figure:s,dash:!0,evidence:c.state}:{kind:"composite",label:"terminal execution",evidence:c.state,value:Bt(Bt(_().text("median ").text(Pe(u.median),"bold"),e).text("p90 ").text(Pe(u.p90),"bold"),e).text("max ").text(Pe(u.maximum),"bold")},d=r.usageByModel.map(v=>{const g=ie(v.tokens);return{kind:"model",label:v.model,pseudo:!1,executions:v.executions,tokens:g===void 0?s:Nt(g),dash:g===void 0,evidence:v.tokens.state}}),m=r.modelMix.filter(v=>dt(v.key,"model").pseudo);if(m.reduce((v,g)=>v+g.executions,0)===r.executionsWithoutModel)for(const v of m)d.push({kind:"model",label:dt(v.key,"model").text,pseudo:!0,executions:v.executions});else r.executionsWithoutModel>0&&d.push({kind:"model",label:"model not observed",pseudo:!0,executions:r.executionsWithoutModel});const y=[a,{head:"OUTCOMES",rows:[o("completed",r.completed,String),o("failed",r.failed,String),o("interrupted",r.interrupted,String)]},{head:"DURATION",rows:[l,o("terminal interval",r.terminalExecutionIntervalMs,Pe),o("overlapping interval",r.overlappingTerminalIntervalMs,Pe),o("peak concurrency",r.peakTerminalConcurrency,v=>String(v.peak),v=>v.at===null?_():_().text(`at ${Wc(v.at,t.period,e)}`))]},{head:"USAGE",rows:[o("tokens",r.tokens,Nt),o("tool interactions",r.toolInteractions,Nt),o("tool errors",r.toolErrors,Nt),o("explicit waits",r.waits,v=>String(v.count),v=>{const g=_().text("for ").text(Pe(v.durationMs),"bold");return v.openNow>0?Bt(g,e).text(String(v.openNow),"bold").text(" open"):g})]}];return d.length>0&&y.push({head:"BY MODEL",rows:d}),y}function Dw(t,e,r,n){const s=(o,i)=>i===void 0?o:o.at(e.evidenceCol,G(i),Ke(i));switch(t.kind){case"prose":return[_().at(2,t.text)];case"figure":{const o=t.dash?void 0:"bold";if(e.stacked){const c=_().at(4,t.figure,o);return t.tail&&t.tail.length>0&&c.text(" ").append(t.tail),[s(_().at(2,t.label),t.evidence),c]}const i=[];let a=_();return t.label.length>e.labelMax?i.push(_().at(2,t.label)):a.at(2,t.label),a.right(e.figureEnd,t.figure,o),t.tail&&t.tail.length>0&&a.at(e.tailCol,"").append(t.tail),i.push(s(a,t.evidence)),i}case"composite":{if(e.split)return[s(_().at(2,t.label),t.evidence),_().at(4,"").append(t.value)];const o=[],i=_();return t.label.length>e.labelMax?o.push(_().at(2,t.label)):i.at(2,t.label),o.push(s(i.at(e.compositeCol,"").append(t.value),t.evidence)),o}case"model":{const o=t.pseudo?"dim":void 0,i=t.tokens===void 0?` ${Ue(t.executions,"execution")}`:` ${Ue(t.executions,"execution").padEnd(10)}`,a=l=>(l.text(String(t.executions),"bold").text(i),t.tokens===void 0?l:Bt(l,n).text(t.tokens.padStart(r),t.dash?void 0:"bold").text(" tokens"));if(e.split){const l=_().padTo(7-String(t.executions).length);return[s(_().at(2,t.label,o),t.evidence),a(l)]}const c=[],u=_();return t.label.length>e.labelMax?c.push(_().at(2,t.label,o)):u.at(2,t.label,o),u.padTo(e.figureEnd-String(t.executions).length+1),c.push(s(a(u),t.evidence)),c}}}const Xs={"median terminal execution duration":{label:"median terminal duration",duration:!0},"terminal execution interval union":{label:"terminal interval union",duration:!0},"overlapping terminal interval":{label:"overlapping interval",duration:!0},"explicit wait count":{label:"explicit waits"}};function Pw(t,e){const r=Yr(e).dash,n=[],s=[];for(const u of t.dimensions)if(Lw(u)){const l=u.dimension.replace(/ mix$/,"");s.push({head:u.dimension.toUpperCase(),subject:l,a:Tf(u.periodA,l),b:Tf(u.periodB,l),result:G(u.eligibility)})}else{const l=Xs[u.dimension],d=m=>{const p=ie(m);return typeof p!="number"?{value:r,dash:!0,evidence:m.state}:{value:l?.duration?Gm(p):Se(p),dash:!1,evidence:m.state}};n.push({label:l?.label??u.dimension,a:d(u.periodA),b:d(u.periodB),result:G(u.eligibility)})}const o=Vw(n,s),i=o.measure<=e.width-1?"wide":e.width>=80?"paired":"stacked",a=i==="wide"?o.measure:i==="paired"?79:Math.max(1,e.width-1),c=[...na("COMPARISON",a)];return c.push(...Bf("A",t.periodA,t.availabilityA.observation,a,e)),c.push(...Bf("B",t.periodB,t.availabilityB.observation,a,e)),c.push(_(),...Uw(t,a)),c.push(_()),i==="wide"?c.push(...Hw(n,s,o,r)):i==="paired"?c.push(...Fw(n,s)):c.push(...Ww(n,s)),ra(c,e)}function Lw(t){const e=ie(t.periodA)??ie(t.periodB);return t.dimension.endsWith(" mix")||e!==void 0&&typeof e=="object"}function Tf(t,e){const r=ie(t);return r===void 0||typeof r=="number"?{evidence:t.state}:{evidence:t.state,items:Object.entries(r).map(([n,s])=>{const o=dt(n,e);return{key:o.text,pseudo:o.pseudo,count:s}})}}function Bf(t,e,r,n,s){const o=zs(e,s),i=G(r),a=Math.max(46,3+ke(o)+3),c=_().text(t,"bold").at(3,o);return a+ke(i)<=n?[c.at(a,i,Ys(r))]:[c,_().at(3,i,Ys(r))]}function Uw(t,e){const r=[_().text(G(t.eligibility).toUpperCase(),t.eligibility==="comparable"?"bold":"bold-yellow")];for(const s of t.reasons){const o=s.match(/^period ([AB]): (.*)$/);o?r.push(...$n(_().at(2,o[1],"dim"),5,5,o[2],e)):r.push(...$n(_(),2,2,s,e))}const n=new Map;for(const s of t.dimensions)for(const o of s.reasons){const i=n.get(o)??[];i.push(Xs[s.dimension]?.label??s.dimension),n.set(o,i)}for(const[s,o]of n){const i=o.length===t.dimensions.length?"All dimensions":o.join(", ");r.push(...$n(_(),2,2,`${i}: ${s}.`,e))}return r}function Vw(t,e){const r=p=>e.flatMap(y=>y[p].items?.map(v=>Se(v.count))??[]),n=(p,y)=>Math.max(y,...p.map(ke)),s=n([...t.map(p=>p.a.value),...r("a")],13),o=n([...t.map(p=>p.b.value),...r("b")],13),i=n([...t.flatMap(p=>[G(p.a.evidence),G(p.b.evidence)]),...e.flatMap(p=>[G(p.a.evidence),G(p.b.evidence)])],12),a=29+s-1,c=a+3,u=c+i+2+o,l=u+3,d=l+i+3,m=n([...t.map(p=>p.result),...e.map(p=>p.result)],0);return{measure:d+m,aEnd:a,aEvidence:c,bEnd:u,bEvidence:l,result:d}}function mi(t){return t.dash?void 0:"bold"}function Kc(t,e,r,n){return ke(t)>e?{lead:[_().at(r,t,n)],row:_()}:{lead:[],row:_().at(r,t,n)}}function Hw(t,e,r,n){const s=[_().text("MEASURE","dim").right(r.aEnd,"A","dim").right(r.bEnd,"B","dim").at(r.result,"COMPARISON","dim")];for(const o of t){const{lead:i,row:a}=Kc(o.label,25,2);s.push(...i,a.right(r.aEnd,o.a.value,mi(o.a)).at(r.aEvidence,G(o.a.evidence),Ke(o.a.evidence)).right(r.bEnd,o.b.value,mi(o.b)).at(r.bEvidence,G(o.b.evidence),Ke(o.b.evidence)).at(r.result,o.result))}for(const o of e){s.push(_(),_().text(o.head,"dim").at(r.aEvidence,G(o.a.evidence),Ke(o.a.evidence)).at(r.bEvidence,G(o.b.evidence),Ke(o.b.evidence)).at(r.result,o.result));const i=new Map;for(const a of o.a.items??[])i.set(a.key,{pseudo:a.pseudo,a:a.count});for(const a of o.b.items??[])i.set(a.key,{...i.get(a.key),pseudo:a.pseudo,b:a.count});for(const[a,c]of i){const{lead:u,row:l}=Kc(a,25,2,c.pseudo?"dim":void 0);o.a.items&&l.right(r.aEnd,c.a===void 0?n:Se(c.a),c.a===void 0?void 0:"bold"),o.b.items&&l.right(r.bEnd,c.b===void 0?n:Se(c.b),c.b===void 0?void 0:"bold"),s.push(...u,l)}}return s}function Fw(t,e){const r=[_().text("MEASURES","dim").right(78,"COMPARISON","dim")],n=(s,o,i,a)=>s.at(i,o,"dim").right(i+15,a.value,mi(a)).at(i+18,G(a.evidence),Ke(a.evidence));for(const s of t)r.push(_().at(2,s.label).right(78,s.result)),r.push(n(n(_(),"A",4,s.a),"B",40,s.b));for(const s of e)r.push(_(),_().text(s.head,"dim").right(78,s.result)),r.push(...zm(s,29));return r}function Ww(t,e){const r=[_().text("MEASURES","dim")],n=(s,o)=>_().at(4,s,"dim").right(28,o.value,mi(o)).at(31,G(o.evidence),Ke(o.evidence));t.forEach((s,o)=>{o>0&&r.push(_()),r.push(_().at(2,s.label),n("A",s.a),n("B",s.b),_().at(4,"comparison","dim").at(16,s.result))});for(const s of e)r.push(_(),_().text(s.head,"dim"),...zm(s,28)),r.push(_().at(2,"comparison","dim").at(16,s.result));return r}function zm(t,e){const r=[];for(const[n,s]of[["A",t.a],["B",t.b]]){r.push(_().at(2,n,"dim").at(5,G(s.evidence),Ke(s.evidence)));for(const o of s.items??[]){const{lead:i,row:a}=Kc(o.key,e-5-1-ke(Se(o.count)),5,o.pseudo?"dim":void 0);r.push(...i,a.right(e,Se(o.count),"bold"))}}return r}const Kw=["summary","availability","compare","breakdown"];function qt(t,e,r=Dl){switch(t.operation){case"summary":return _w(t.result,r);case"availability":return Gw(t.result,r);case"compare":return Pw(t.result,r);case"breakdown":return qw(t.result,e,r)}}const Ym={"tool-interactions":"tool interactions","tool-errors":"tool errors"};function Gw(t,e){const r=e.width>=80,n=e.width<56,s=r?79:Math.max(1,e.width-1),o=25,i=[...na("AVAILABILITY",s),...Ll(t.period,[],s,e)],a=(m,p)=>n?[_().at(2,m),_().padTo(4).append(p)]:[_().at(2,m).padTo(o).append(p)],c=(m,p)=>_().text(m,p),u=m=>i.push(_(),_().text(m,"dim"));u("OBSERVATION"),i.push(...a("state",c(G(t.observation),Ys(t.observation))),...a("records",Bt(_().text(String(t.executionRecords),"bold").text(` ${Ue(t.executionRecords,"execution")}`),e).text(String(t.sessionRecords),"bold").text(` ${Ue(t.sessionRecords,"session")}`)),...a("continuity",c(G(t.continuity.state),Ke(t.continuity.state))),...a("observation gaps",c(G(t.observationGaps.state),Ke(t.observationGaps.state))),...a("unprojected work",c(G(t.unprojectedSourceWork.state),Ke(t.unprojectedSourceWork.state)))),u("RETENTION"),i.push(...a("state",c(G(t.retention.state),qm(t.retention.state)))),t.retention.semanticFrom!==null&&i.push(...a("semantic history from",c(Pl(t.retention.semanticFrom,e),"bold")));const l=t.bounds;if(s>=51)i.push(_(),_().text("BOUNDS","dim").right(32,"observed","dim").right(42,"inferred","dim").right(50,"open","dim"),_().at(2,"starts").right(32,String(l.observedStarts),"bold").right(42,String(l.inferredStarts),"bold"),_().at(2,"ends").right(32,String(l.observedEnds),"bold").right(42,String(l.inferredEnds),"bold").right(50,String(l.openEnds),"bold"));else{const m=p=>{const y=_().padTo(4);return p.forEach(([v,g],C)=>{C>0&&Bt(y,e),y.text(String(v),"bold").text(` ${g}`)}),y};u("BOUNDS"),i.push(_().at(2,"starts"),m([[l.observedStarts,"observed"],[l.inferredStarts,"inferred"]]),_().at(2,"ends"),m([[l.observedEnds,"observed"],[l.inferredEnds,"inferred"],[l.openEnds,"open"]]))}u("COMPARISON");const d=t.comparisonReadiness==="comparable"?void 0:"yellow";i.push(...a("readiness",c(G(t.comparisonReadiness),d))),t.reasons.forEach((m,p)=>{const y=p===0?"because":"";n?(y&&i.push(_().at(2,y)),i.push(...$n(_(),4,4,m,s))):i.push(...$n(_().at(2,y),o,o,m,s))}),i.push(_()),r?i.push(_().text("MEASURES","dim").at(21,"state","dim").at(35,"coverage","dim").right(78,"records","dim")):i.push(_().text("MEASURES","dim").at(o,"state","dim").right(s-1,"records","dim"));for(const m of t.measures){const p=Ym[m.dimension]??G(m.dimension),y=G(m.state),v=_().text("/","dim").text(" ").text(String(m.coverage.records),"bold");if(r){const g=_().at(2,p).at(21,y,Ke(m.state));i.push(...$f(g,35,78,m.coverage,v,e))}else i.push(_().at(2,p).at(o,y,Ke(m.state))),i.push(...$f(_(),4,s-1,m.coverage,v,e))}u("SOURCES"),t.sources.length===0&&i.push(_().at(2,"none observed"));for(const m of t.sources){const p=String(m.executionRecords),y=`execution ${Ue(m.executionRecords,"record")}`;if(29+ke(y)>s){i.push(_().at(2,m.source),_().at(4,p,"bold").text(` ${y}`));continue}const v=g=>g.right(27,p,"bold").at(29,y);ke(m.source)>22?i.push(_().at(2,m.source),v(_())):i.push(v(_().at(2,m.source)))}return ra(i,e)}function $f(t,e,r,n,s,o){const a=[[n.observed,"observed"],[n.inferred,"inferred"],[n.partial,"partial"],[n.notObserved,"not-observed"],[n.unsupported,"unsupported"],[n.unknown,"unknown"]].filter(([m])=>m>0).map(([m,p])=>_().text(String(m),"bold").text(" ").text(G(p),Ke(p))),c=Yr(o).sep,u=r-s.length,l=[[]];let d=e;for(const m of a){const p=l[l.length-1],y=d+(p.length>0?c.length:0)+m.length;p.length>0&&y>u?(l.push([m]),d=e+m.length):(p.push(m),d=y)}return l.map((m,p)=>{const y=p===0?t.padTo(e):_().padTo(e);if(m.forEach((v,g)=>{g>0&&Bt(y,o),y.append(v)}),p<l.length-1){const v=c.trim();return y.text(c.slice(0,c.indexOf(v))).text(v,"dim"),y}return y.padTo(r-s.length+1).append(s)})}function qw(t,e,r){const n=Yr(r).dash,s=l=>{const d=ie(l);return d===void 0?{value:n,dash:!0,evidence:l.state}:{value:Se(d),dash:!1,evidence:l.state}},o=t.items.filter(l=>e===void 0||l.key===e).map(l=>{const d=dt(l.key,t.dimension),m=ie(l.terminalDuration);return{key:d.text,pseudo:d.pseudo,executions:Se(l.executions),singular:l.executions===1,terminal:Se(l.terminalExecutions),median:m===void 0?n:Km(m.median),medianDash:m===void 0,tokens:s(l.tokens),tools:s(l.toolInteractions),errors:s(l.toolErrors),failed:s(l.failed)}}),i=zw(o,t.dimension),a=o.length>0&&i.measure<=r.width-1?"table":r.width>=80?"records":"narrow",c=a==="table"?i.measure:a==="records"?79:Math.max(1,r.width-1),u=[...na(`BREAKDOWN${Yr(r).sep}${G(t.dimension).toUpperCase()}`,c),...Ll(t.period,[{text:G(t.availability.observation),role:Ys(t.availability.observation)}],c,r),_()];if(o.length===0)u.push(_().text("none observed"));else if(a==="table")u.push(...i.lines);else{const l=a==="records"?Yw(o):null;o.forEach((d,m)=>{m>0&&u.push(_()),u.push(...l?Xw(d,l,r):Jw(d,o,r))})}return u.push(_(),...$n(_(),0,0,t.qualification,c,"dim")),ra(u,r)}function yi(t){return t.pseudo?"dim":"bold"}function gi(t,e,r){return r.evidence===void 0?t:t.at(e,G(r.evidence),Ke(r.evidence))}function zw(t,e){const r=G(e).toUpperCase(),n=[{caption:"EXECUTIONS",value:m=>m.executions},{caption:"TERMINAL",value:m=>m.terminal},{caption:"MEDIAN",value:m=>m.median}],s=[{caption:"TOKENS",value:m=>m.tokens},{caption:"TOOLS",value:m=>m.tools},{caption:"ERRORS",value:m=>m.errors},{caption:"FAILED",value:m=>m.failed}],o=m=>Math.max(0,...m.map(ke));let i=Math.max(ke(r),o(t.map(m=>m.key))),a=ke(r)-1;const c=n.map(m=>{const p=i+2+Math.max(ke(m.caption),o(t.map(m.value)))-1;return i=p+1,a=p,p}),u=s.map(m=>{const p=t.map(m.value);let y=i+2+o(p.map(v=>v.value))-1;return y=Math.max(y,a+2+ke(m.caption)),i=y+3+o(p.map(v=>G(v.evidence??""))),a=y,y}),l=_().text(r,"dim");n.forEach((m,p)=>l.right(c[p],m.caption,"dim")),s.forEach((m,p)=>l.right(u[p],m.caption,"dim"));const d=[l];for(const m of t){const p=_().text(m.key,yi(m));n.forEach((y,v)=>p.right(c[v],y.value(m),"bold")),s.forEach((y,v)=>{const g=y.value(m);gi(p.right(u[v],g.value,g.dash?void 0:"bold"),u[v]+3,g)}),d.push(p)}return{measure:i,lines:d}}function Xm(t){const e=r=>Math.max(3,...t.map(n=>ke(r(n))));return{countWidth:e(r=>r.executions),terminalWidth:e(r=>r.terminal),medianWidth:e(r=>r.median)}}function Yw(t){const e=s=>Math.max(1,...t.flatMap(o=>s(o).map(i=>ke(i.value)))),r=Math.max(24,10+e(s=>[s.tokens,s.errors])-1),n=Math.max(44,r+3+12+2);return{...Xm(t),countEnd:34,leftEnd:r,rightLabel:n,rightEnd:Math.max(61,n+6+2+e(s=>[s.tools,s.failed])-1)}}function Jm(t,e,r,n){return t.text(e.executions.padStart(r.countWidth),"bold").text(` ${(e.singular?"execution":"executions").padEnd(10)}`),Bt(t,n).text(e.terminal.padStart(r.terminalWidth),"bold").text(" terminal"),Bt(t,n).text("median "),t.text(e.median.padStart(r.medianWidth),e.medianDash?void 0:"bold")}function Xw(t,e,r){const n=[],s=e.countEnd-e.countWidth+1,o=_();ke(t.key)>=s?n.push(_().text(t.key,yi(t))):o.text(t.key,yi(t)),n.push(Jm(o.padTo(s),t,e,r));const i=(a,c,u,l)=>{const d=_().at(2,a);return gi(d.right(e.leftEnd,c.value,c.dash?void 0:"bold"),e.leftEnd+3,c),d.at(e.rightLabel,u),gi(d.right(e.rightEnd,l.value,l.dash?void 0:"bold"),e.rightEnd+3,l)};return n.push(i("tokens",t.tokens,"tools",t.tools),i("errors",t.errors,"failed",t.failed)),n}function Jw(t,e,r){const n=Math.max(1,...e.flatMap(i=>[i.tokens,i.tools,i.errors,i.failed].map(a=>ke(a.value)))),s=Math.max(24,10+n-1),o=(i,a)=>gi(_().at(2,i).right(s,a.value,a.dash?void 0:"bold"),s+3,a);return[_().text(t.key,yi(t)),Jm(_().padTo(2),t,Xm(e),r),o("tokens",t.tokens),o("tools",t.tools),o("errors",t.errors),o("failed",t.failed)]}const Rf=["summary","availability","compare","breakdown"],_f=["lifecycle","duration","tokens","waits","errors"],Mf=["model","executor"],jf=["today","last-7d"];function Zw(t){const e=Rf.find(a=>a===t.query),r=jf.find(a=>a===(t.scope??"today"));if(!e)return{error:`query must be one of ${Rf.join(", ")}`};if(!r)return{error:`scope must be one of ${jf.join(", ")}`};const n=t.focus?_f.find(a=>a===t.focus):void 0,s=t.by?Mf.find(a=>a===t.by):void 0;if(t.focus&&!n)return{error:`focus must be one of ${_f.join(", ")}`};if(t.by&&!s)return{error:`by must be one of ${Mf.join(", ")}`};if(!{summary:[void 0,"lifecycle","duration"],availability:[void 0,"tokens","waits"],breakdown:[void 0,"errors"],compare:[void 0]}[e].includes(n))return{error:`${e} has no ${n} reading`};if(e==="breakdown"&&!s)return{error:"breakdown needs by=model|executor"};if(e!=="breakdown"&&s)return{error:`${e} takes no dimension`};if(n==="errors"&&s!=="model")return{error:"errors are read by model"};const i={query:e,scope:r};return n&&(i.focus=n),s&&(i.by=s),i}function Qw(t,e){if(t==="last-7d")return{from:e-7*864e5,to:e};const r=new Date(e);return r.setHours(0,0,0,0),{from:r.getTime(),to:e}}function eA(t){const e=t.to-t.from;return{from:t.from-e,to:t.from}}function tA(t,e,r,n={}){const s=Qw(e.scope,r),o={};switch(e.query){case"summary":o.summary=t.summary(s);break;case"availability":e.focus&&(o.summary=t.summary(s)),o.availability=o.summary?.availability??t.availability(s);break;case"breakdown":o.breakdown=t.breakdown(s,e.by??"model"),e.focus==="errors"&&(o.summary=t.summary(s));break;case"compare":o.comparison=t.compare(s,eA(s));break}return rA(e,o,n)}function rA(t,e,r={}){const n={...Dl,timeZone:r.timeZone};switch(t.query){case"summary":{const s=Lr(e.summary,"summary");return t.focus==="duration"?oA(t,s,r,n):t.focus==="lifecycle"?sA(t,s,r,n):nA(t,s,r,n)}case"availability":{const s=Lr(e.availability,"availability");return t.focus==="tokens"?aA(t,Lr(e.summary,"summary"),r,n):t.focus==="waits"?cA(t,Lr(e.summary,"summary"),r,n):iA(t,s,r,n)}case"breakdown":{const s=Lr(e.breakdown,"breakdown");return t.focus==="errors"?lA(t,s,Lr(e.summary,"summary"),r,n):uA(t,s,r,n)}case"compare":return dA(t,Lr(e.comparison,"comparison"),n)}}function nA(t,e,r,n){const{summary:s,availability:o}=e,i=Mr(t,"SUMMARY",o,!0,r,n),a=qt({operation:"summary",result:e},void 0,n);if(s.executions===0||yr(o))return jr(i,o,a,n);const c=[Zm(e)],u=ie(s.completed),l=ie(s.failed);u!==void 0&&l!==void 0&&c.push(`${u} completed and ${l} failed${iy([s.completed,s.failed])}.`);const d=Xr(o,"waits");d&&Ln(d.coverage,"unsupported")&&c.push(`Waits are unsupported for all ${s.executions}.`);const m=[...i.observation,Ul(o)],p=yA(o);return p&&m.push(p),m.push({k:"ENDS",v:ny(o)}),{...i,finding:c.join(" "),observation:m,evidence:[...Qm(e,"lifecycle",t),je("completed",s.completed,String,Ae(t,"summary","lifecycle")),je("failed",s.failed,String,Ae(t,"summary","lifecycle")),je("interrupted",s.interrupted,String,Ae(t,"summary","lifecycle")),je("terminal interval",s.terminalExecutionIntervalMs,Pe,Ae(t,"summary","duration")),je("overlapping interval",s.overlappingTerminalIntervalMs,Pe,Ae(t,"summary","duration")),je("tokens",s.tokens,Nt,Ae(t,"availability","tokens")),je("tool interactions",s.toolInteractions,Nt,Ae(t,"breakdown","errors")),je("tool errors",s.toolErrors,Nt,Ae(t,"breakdown","errors")),ey(e,Ae(t,"availability","waits"))],command:zt("summary",t.scope),text:a}}function sA(t,e,r,n){const{summary:s,availability:o}=e,i=Mr(t,"SUMMARY · LIFECYCLE",o,!0,r,n),a=qt({operation:"summary",result:e},void 0,n);if(s.executions===0||yr(o))return jr(i,o,a,n);const c=[Zm(e)],u=[s.completed,s.failed,s.interrupted],[l,d,m]=u.map(C=>ie(C));l!==void 0&&d!==void 0&&m!==void 0&&c.push(`${l} completed, ${d} failed and ${m} interrupted${iy(u)}.`),Ln(s.waitingNow.coverage,"unsupported")&&c.push(`Waiting is unsupported for all ${s.executions}.`);const p=Xr(o,"outcomes"),y=[...i.observation];p&&y.push({k:"OUTCOMES",v:Js(p.state,p.coverage)}),y.push({k:"ENDS",v:ny(o)});const v=s.terminalExecutionDuration,g=ie(v);return{...i,finding:c.join(" "),observation:y,evidence:[...Qm(e,void 0,t),je("completed",s.completed,String),je("failed",s.failed,String),je("interrupted",s.interrupted,String),{k:"terminal execution",...g?{t:oy(g)}:{},v:g?"":"—",e:G(v.state),focus:Ae(t,"summary","duration")}],command:zt("summary",t.scope),text:a}}function oA(t,e,r,n){const{summary:s,availability:o}=e,i=Mr(t,"SUMMARY · DURATION",o,!0,r,n),a=qt({operation:"summary",result:e},void 0,n);if(s.executions===0||yr(o))return jr(i,o,a,n);const c=ie(s.terminalExecutionIntervalMs),u=ie(s.overlappingTerminalIntervalMs),l=ie(s.peakTerminalConcurrency),d=[];c!==void 0&&u!==void 0&&c>0?(d.push(u===0?"Sequential.":u*2<c?"Mostly sequential.":"Mostly overlapping."),d.push(`Two or more executions were in flight for ${Pe(u)} of the ${Pe(c)} covered by terminal executions.`),l&&l.at!==null&&d.push(`The peak was ${l.peak}, at ${Wc(l.at,e.period,n)}.`)):d.push("No terminal execution covers any of this period, so there is no interval to divide.");const m=[...i.observation];o.bounds.openEnds>0&&m.push({k:"OPEN ENDS",v:`${o.bounds.openEnds} of ${s.executions} executions ${o.bounds.openEnds===1?"has":"have"} no observed end`}),o.continuity.state!=="observed"&&m.push({k:"CONTINUITY",v:`${G(o.continuity.state)} — time 057 did not observe is in neither figure`});const p=s.terminalExecutionDuration,y=ie(p);return{...i,finding:d.join(" "),observation:m,evidence:[je("terminal interval",s.terminalExecutionIntervalMs,Pe),je("overlapping interval",s.overlappingTerminalIntervalMs,Pe),{...je("peak concurrency",s.peakTerminalConcurrency,v=>String(v.peak)),...l&&l.at!==null?{t:`at ${Wc(l.at,e.period,n)}`}:{}},{k:"terminal execution",...y?{t:oy(y)}:{},v:y?"":"—",e:G(p.state)},{k:"executions",v:String(s.executions),e:"",focus:Ae(t,"summary","lifecycle")},{k:"sessions",v:String(s.sessions),e:"",focus:Ae(t,"summary","lifecycle")}],command:zt("summary",t.scope),text:a}}function Zm(t){const{summary:e}=t,r=ie(e.waitingNow),n=[e.runningNow>0?`${e.runningNow} running`:void 0,r!==void 0&&r>0?`${r} waiting`:void 0,e.idleNow>0?`${e.idleNow} idle`:void 0].filter(o=>o!==void 0),s=`${e.executions} ${Ue(e.executions,"execution")} across ${e.sessions} ${Ue(e.sessions,"session")}`;return n.length>0?`${s}; ${Un(n)}.`:`${s}.`}function Qm(t,e,r){const{summary:n}=t,s=e?Ae(r,"summary",e):void 0,o=(i,a)=>({k:i,v:String(a),e:"",...s?{focus:s}:{}});return[o("executions",n.executions),o("sessions",n.sessions),o("running",n.runningNow),je("waiting",n.waitingNow,String,s),o("idle",n.idleNow)]}function ey(t,e){const r=t.summary.waits,n=ie(r);return{k:"explicit waits",...n?{t:`for ${Pe(n.durationMs)}${n.openNow>0?` · ${n.openNow} open`:""}`}:{},v:n?String(n.count):"—",e:G(r.state),...e?{focus:e}:{}}}function iA(t,e,r,n){const s=Mr(t,"AVAILABILITY",e,!1,r,n),o=qt({operation:"availability",result:e},void 0,n),i=e.executionRecords;if(yr(e))return jr(s,e,o,n);const a=[],c=[e.continuity.state==="unknown"?"Continuity":void 0,e.observationGaps.state==="unknown"?"gaps":void 0,e.unprojectedSourceWork.state==="unknown"?"unprojected work":void 0].filter(d=>d!==void 0);if(c.length>0){const d=Un(c);a.push(`${d[0].toUpperCase()}${d.slice(1)} ${c.length===1?"is":"are"} unknown.`)}if(i===0)a.push("No execution records, so no measure has coverage to report.");else{const d=e.measures.filter(p=>Ln(p.coverage,"unsupported"));if(d.length>0){const p=Un(d.map(y=>hc(y.dimension)));a.push(`${p[0].toUpperCase()}${p.slice(1)} ${d.length===1?"is":"are"} unsupported for all ${i}.`)}const m=[...e.measures].filter(p=>!Ln(p.coverage,"unsupported")&&p.coverage.notObserved>0).sort((p,y)=>y.coverage.notObserved-p.coverage.notObserved)[0];m&&a.push(`The ${hc(m.dimension)} is not observed for ${m.coverage.notObserved} of ${i}.`)}const u=[...s.observation,{k:"RETENTION",v:sy(e,n)},{k:"COMPARISON",v:G(e.comparisonReadiness)}],l=[{k:"continuity",v:G(e.continuity.state),e:""},{k:"observation gaps",v:G(e.observationGaps.state),e:""},{k:"unprojected work",v:G(e.unprojectedSourceWork.state),e:""},{k:"execution records",v:String(i),e:""},...e.measures.map(d=>{const m=pA(t,d.dimension);return{k:hc(d.dimension),...d.coverage.records>0?{t:ry(d.coverage)}:{},v:"",e:G(d.state),...m?{focus:m}:{}}})];return{...s,finding:a.join(" ")||void 0,observation:u,evidenceCaption:"COVERAGE",evidence:l,command:zt("availability",t.scope),text:o}}function aA(t,e,r,n){const{summary:s,availability:o}=e,i=Mr(t,"AVAILABILITY · TOKENS",o,!1,r,n),a=qt({operation:"availability",result:o},void 0,n);if(s.executions===0||yr(o))return jr(i,o,a,n);const c=Xr(o,"tokens"),u=Xr(o,"model"),l=ie(s.tokens),d=[];if(l!==void 0&&c){const p=c.coverage,y=[p.inferred>0?`${p.inferred} ${p.inferred===1?"is":"are"} inferred`:void 0,p.partial>0?`${p.partial} ${p.partial===1?"is":"are"} partial`:void 0,p.notObserved>0?`${p.notObserved} ${p.notObserved===1?"was":"were"} not observed`:void 0,p.unsupported>0?`${p.unsupported} ${p.unsupported===1?"is":"are"} unsupported`:void 0,p.unknown>0?`${p.unknown} ${p.unknown===1?"is":"are"} unknown`:void 0].filter(v=>v!==void 0);d.push(y.length===0?`${Nt(l)} is fully observed for all ${p.records} executions.`:`${Nt(l)} is fully observed for ${p.observed} of ${p.records} executions; ${Un(y)}.`)}else d.push(`Tokens are ${G(s.tokens.state)} for this period.`);s.executionsWithoutModel>0&&d.push(`${s.executionsWithoutModel} ${Ue(s.executionsWithoutModel,"execution")} carry no observed model, so it cannot be divided completely by model.`);const m=[...i.observation];return c&&m.push({k:"TOKENS",v:Js(c.state,c.coverage)}),u&&m.push({k:"MODEL",v:Js(u.state,u.coverage)}),m.push(Ul(o)),{...i,finding:d.join(" "),observation:m,evidence:[je("tokens",s.tokens,Nt),...fA(e)],command:zt("availability",t.scope),text:a}}function cA(t,e,r,n){const{summary:s,availability:o}=e,i=Mr(t,"AVAILABILITY · WAITS",o,!1,r,n),a=qt({operation:"availability",result:o},void 0,n);if(s.executions===0||yr(o))return jr(i,o,a,n);const c=Xr(o,"waits"),u=s.executions,l=ie(s.waits);let d,m;const p=c&&(Ln(c.coverage,"unsupported")||Ln(c.coverage,"notObserved"));!l||p?(d="NOT OBSERVED",m=`Wait behaviour is ${G(s.waits.state)} for all ${u} executions in this period, so time blocked on a person cannot be read from it.`):(m=`${l.count} explicit ${Ue(l.count,"wait")} for ${Pe(l.durationMs)}${l.openNow>0?`, ${l.openNow} open now`:""}.`,c&&c.coverage.unsupported>0&&(m+=` Waits are unsupported for ${c.coverage.unsupported} of ${u} executions.`));const y=[...i.observation];return c&&y.push({k:"WAITS",v:Js(c.state,c.coverage)}),y.push({k:"SOURCES",v:o.sources.map(v=>`${v.source} ${v.executionRecords}`).join(" · ")}),{...i,...d?{verdict:d}:{},finding:m,observation:y,evidence:[ey(e),{...je("waiting",s.waitingNow,String),t:"recorded lifecycle"},{k:"executions",v:String(u),e:""}],command:zt("availability",t.scope),text:a}}function uA(t,e,r,n){const s=t.by??"model",o=Mr(t,`BREAKDOWN · ${s.toUpperCase()}`,e.availability,!1,r,n),i=qt({operation:"breakdown",result:e},void 0,n),a=e.availability.executionRecords;if(a===0||yr(e.availability))return jr(o,e.availability,i,n);const c=e.items.filter(p=>!dt(p.key,s).pseudo),u=e.items.filter(p=>dt(p.key,s).pseudo),l=[];if(s==="executor")l.push(`${Un(c.map(p=>`${p.key} ${p.executions}`))} execution ${Ue(c.reduce((p,y)=>p+y.executions,0),"record")}.`);else if(c[0]){const p=c[0],y=ie(p.tokens);l.push(`${p.key} accounts for ${p.executions} of ${a} executions${y!==void 0?` and ${Se(y)} tokens`:""}.`)}for(const p of u)l.push(`${p.executions} ${Ue(p.executions,"execution")} ${p.executions===1?"carries":"carry"} ${gA(p.key,s)}.`);const d=Xr(e.availability,s),m=[...o.observation];return d&&m.push({k:s.toUpperCase(),v:Js(d.state,d.coverage)}),m.push({k:"CAUSALITY",v:"grouped records; not a causal performance difference"}),{...o,finding:l.join(" "),observation:m,evidenceCaption:"TOKENS",evidence:e.items.map(p=>{const y=ie(p.terminalDuration),v=ie(p.tokens);return{k:dt(p.key,s).text,t:`${Se(p.executions)} ${Ue(p.executions,"execution")}${y?` · median ${Km(y.median)}`:""}`,v:v===void 0?"—":Se(v),e:G(p.tokens.state)}}),command:zt("breakdown",t.scope,s),text:i}}function lA(t,e,r,n,s){const o=Mr(t,"BREAKDOWN · MODEL · ERRORS",e.availability,!1,n,s),i=qt({operation:"breakdown",result:e},void 0,s);if(e.availability.executionRecords===0||yr(e.availability))return jr(o,e.availability,i,s);const a=[...e.items].sort((v,g)=>(ie(g.toolErrors)??-1)-(ie(v.toolErrors)??-1)||g.executions-v.executions),c=ie(r.summary.toolErrors),u=a.filter(v=>!dt(v.key,"model").pseudo&&ie(v.toolErrors)!==void 0),l=[],d=v=>{const g=ie(v.toolInteractions);return g===void 0?"":`, across ${Se(g)} tool interactions`};if(c===void 0)l.push(`Tool errors are ${G(r.summary.toolErrors.state)} for this period.`);else if(c===0)l.push("No tool errors were recorded.");else if(u[0]){const[v,g]=u,C=ie(v.toolErrors)??0;if(l.push(C*2>c?`Tool errors are concentrated in ${v.key}: ${Se(C)} of ${Se(c)} recorded errors${d(v)}.`:`Tool errors are spread across models: ${v.key} recorded ${Se(C)} of ${Se(c)}${d(v)}.`),g){const A=ie(g.toolInteractions);l.push(`${g.key} recorded ${Se(ie(g.toolErrors)??0)}${A===void 0?"":` across ${Se(A)}`}.`)}}const m=[...o.observation],p=e.items.filter(v=>v.toolErrors.state==="unsupported").map(v=>dt(v.key,"model").text);p.length>0&&m.push({k:"ERRORS",v:`unsupported for ${Un(p)}`}),m.push({k:"CAUSALITY",v:"grouped records; not a causal performance difference"});const y=(v,g)=>{const C=ie(v),A=ie(g);return`${C===void 0?"—":Se(C)} / ${A===void 0?"—":Se(A)}`};return{...o,finding:l.join(" "),observation:m,evidenceCaption:"ERRORS / TOOLS",evidence:[{k:"all executions",v:y(r.summary.toolErrors,r.summary.toolInteractions),e:G(r.summary.toolErrors.state)},...a.map(v=>({k:dt(v.key,"model").text,v:y(v.toolErrors,v.toolInteractions),e:G(v.toolErrors.state)}))],command:zt("breakdown",t.scope,"model"),text:i}}function dA(t,e,r){const n=[{k:"A",w:zs(e.periodA,r),s:G(e.availabilityA.observation)},{k:"B",w:zs(e.periodB,r),s:G(e.availabilityB.observation)}],s=[...e.availabilityA.reasons.map(l=>({k:"A",v:l})),...e.availabilityB.reasons.map(l=>({k:"B",v:l})),...e.reasons.filter(l=>!l.startsWith("period A: ")&&!l.startsWith("period B: ")).map(l=>({k:"",v:l}))],o=e.dimensions.filter(l=>!l.dimension.endsWith(" mix")),i=new Set(e.dimensions.flatMap(l=>l.reasons)),c=[{k:"DIMENSIONS",v:e.dimensions.every(l=>l.eligibility===e.eligibility)&&i.size===1?`all — ${[...i][0]}`:["comparable","partially-comparable","not-comparable"].map(l=>[e.dimensions.filter(d=>d.eligibility===l).length,G(l)]).filter(([l])=>l>0).map(([l,d])=>`${l} ${d}`).join(" · ")}],u=(l,d)=>{const m=ie(d);return typeof m!="number"?"—":Xs[l]?.duration?Gm(m):Se(m)};return{request:t,title:ty(t.scope),resolution:`COMPARISON · AGAINST PREVIOUS${t.scope==="last-7d"?" 7D":""}`,periods:n,partial:e.availabilityA.observation!=="observed"||e.availabilityB.observation!=="observed",verdict:G(e.eligibility).toUpperCase(),reasons:s,observation:c,evidenceCaption:"A · B",evidence:o.map(l=>{const d=hA(t,l.dimension);return{k:Xs[l.dimension]?.label??l.dimension,t:`B ${u(l.dimension,l.periodB)} ${G(l.periodB.state)}`,v:u(l.dimension,l.periodA),e:G(l.periodA.state),...d?{focus:d}:{}}}),command:zt("compare",t.scope),text:qt({operation:"compare",result:e},void 0,r)}}function Mr(t,e,r,n,s,o){const i=[G(r.observation),...n?[G(r.retention.state)]:[]].join(" · "),a=[],c=ty(t.scope);return s.view&&s.view!==c&&a.push({k:"PERIOD",v:`${c.toLowerCase()}, as asked · the view is showing ${s.view.toLowerCase()}`}),{request:t,title:c,resolution:e,window:zs(r.period,o),qualification:i,partial:r.observation!=="observed",reasons:[],observation:a}}function jr(t,e,r,n){const s=t.request,o=zt(s.query,s.scope,s.by);if(yr(e)){const i=e.retention.semanticFrom;return{...t,verdict:"OUTSIDE RETENTION",finding:i===null?"This period precedes semantic history.":`Semantic history starts at ${Pl(i,n)}; this period precedes it.`,observation:[...t.observation,{k:"RETENTION",v:sy(e,n)}],evidence:[],command:o,text:r}}return{...t,finding:"No execution records. A quiet period cannot be told from an unobserved one, so zero work is not established.",observation:[...t.observation,Ul(e)],evidence:[{k:"execution records",v:"0",e:""}],command:o,text:r}}function fA(t){const{summary:e}=t,r=e.usageByModel.map(s=>{const o=ie(s.tokens);return{k:s.model,t:`${s.executions} ${Ue(s.executions,"execution")}`,v:o===void 0?"—":Nt(o),e:G(s.tokens.state)}}),n=e.modelMix.filter(s=>dt(s.key,"model").pseudo);if(n.reduce((s,o)=>s+o.executions,0)===e.executionsWithoutModel)for(const s of n)r.push({k:dt(s.key,"model").text,t:`${s.executions} ${Ue(s.executions,"execution")}`,v:"",e:""});else e.executionsWithoutModel>0&&r.push({k:"model not observed",t:`${e.executionsWithoutModel} ${Ue(e.executionsWithoutModel,"execution")}`,v:"",e:""});return r}function je(t,e,r,n){const s=ie(e);return{k:t,v:s===void 0?"—":r(s),e:G(e.state),...n?{focus:n}:{}}}function Ae(t,e,r){const n=e==="breakdown"?{query:e,scope:t.scope,focus:r,by:"model"}:{query:e,scope:t.scope,focus:r};return mA(n,t)?void 0:n}function pA(t,e){switch(e){case"tokens":return Ae(t,"availability","tokens");case"waits":return Ae(t,"availability","waits");case"tool-errors":case"tool-interactions":return Ae(t,"breakdown","errors");case"outcomes":return Ae(t,"summary","lifecycle");case"bounds":return Ae(t,"summary","duration");case"model":return{query:"breakdown",scope:t.scope,by:"model"};case"executor":return{query:"breakdown",scope:t.scope,by:"executor"}}}function hA(t,e){return e==="tokens"?Ae(t,"availability","tokens"):e==="explicit wait count"?Ae(t,"availability","waits"):e==="tool interactions"||e==="tool errors"?Ae(t,"breakdown","errors"):Xs[e]?.duration||e==="peak terminal concurrency"?Ae(t,"summary","duration"):Ae(t,"summary","lifecycle")}function mA(t,e){return t.query===e.query&&t.scope===e.scope&&t.focus===e.focus&&t.by===e.by}function zt(t,e,r){const n=e==="last-7d"?" --last 7d":"";switch(t){case"summary":return`057 activity summary${n}`;case"availability":return`057 activity availability${n}`;case"breakdown":return`057 activity breakdown${n} --by ${r??"model"}`;case"compare":return`057 activity compare${n} --previous`}}function ty(t){return t==="last-7d"?"LAST 7D":"TODAY"}function Xr(t,e){return t.measures.find(r=>r.dimension===e)}function hc(t){return Ym[t]??t}function yr(t){return t.retention.state==="outside-retention"}function Ln(t,e){return t.records>0&&t[e]===t.records}function ry(t){return[[t.observed,"observed"],[t.inferred,"inferred"],[t.partial,"partial"],[t.notObserved,"not observed"],[t.unsupported,"unsupported"],[t.unknown,"unknown"]].filter(([e])=>e>0).map(([e,r])=>`${e} ${r}`).join(" · ")}function Js(t,e){return e.records===0?G(t):`${G(t)} · ${ry(e)} / ${e.records}`}function Ul(t){return{k:"CONTINUITY",v:G(t.continuity.state)}}function yA(t){const e=Xr(t,"model");if(!e||e.coverage.records===0)return;const r=e.coverage,n=[r.notObserved>0?`${r.notObserved} of ${r.records} not observed`:void 0,r.unsupported>0?`${r.unsupported} of ${r.records} unsupported`:void 0,r.unknown>0?`${r.unknown} of ${r.records} unknown`:void 0].filter(s=>s!==void 0);return n.length>0?{k:"MODEL",v:n.join(" · ")}:void 0}function ny(t){const e=t.bounds;return[e.observedEnds>0?`${e.observedEnds} observed`:void 0,e.inferredEnds>0?`${e.inferredEnds} inferred`:void 0,e.openEnds>0?`${e.openEnds} open`:void 0].filter(n=>n!==void 0).join(" · ")||"none"}function sy(t,e){const r=t.retention.semanticFrom;return`${G(t.retention.state)}${r===null?"":` · from ${Pl(r,e)}`}`}function oy(t){return`median ${Pe(t.median)} · p90 ${Pe(t.p90)} · max ${Pe(t.maximum)}`}function iy(t){const e=new Set(t.map(n=>n.state));if(e.size!==1)return` (${t.map(n=>G(n.state)).join(", ")})`;const[r]=[...e];return r==="observed"?"":`, ${t.length===2?"both":"all"} ${G(r)}`}function gA(t,e){const r=dt(t,e).text.replace(`${e} `,"");return r==="not observed"?`no observed ${e}`:`a ${e} that is ${r}`}function Un(t){return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function Lr(t,e){if(t===void 0)throw new Error(`the ${e} result is missing`);return t}const Df=448,vA=384;function bA(){return se(hn(),".057")}function sa(){const t=process.env.O57_STORE;return t&&t.length>0?t===":memory:"||Pc(t)?t:yo(process.cwd(),t):se(bA(),"events.db")}function ay(){const t=process.env.O57_STORE;return typeof t=="string"&&t.length>0}function oa(t){return[t,`${t}-wal`,`${t}-shm`]}function wA(t){return t===":memory:"?[]:[...oa(t),`${t}.display`]}function AA(t){if(t===":memory:")return;const e=ii(t);Dc(e,{recursive:!0,mode:Df}),cy(e,Df)}function Gc(t){if(t===":memory:")return[];const e=[];for(const r of oa(t))if(fe(r)&&!cy(r,vA)){const n=Vl(r);n!==null&&(n&63)!==0&&e.push({path:r,mode:n})}return e}function Vl(t){try{return Qi(t).mode&511}catch{return null}}function cy(t,e){if(process.platform==="win32")return!1;const r=Vl(t);if(r===null)return!1;if((r&~e)===0)return!0;try{return ea(t,e),!0}catch{return!1}}function uy(){if(ay())return null;const t=yo(process.cwd(),".057","events.db");return fe(t)&&t!==sa()?t:null}const qc={processDays:7,eventDays:90},SA=["machine"],Pf=["process"],mc={processEvents:0,otherEvents:0,claims:0,subjects:0,retainedByDependents:0,processBefore:null,otherBefore:null},kA=["execution","session","artifact"];function ly(t=process.env){return{processDays:Lf(t.O57_RETAIN_PROCESS_DAYS,qc.processDays),eventDays:Lf(t.O57_RETAIN_DAYS,qc.eventDays)}}function Lf(t,e){if(t===void 0||t.trim()==="")return e;const r=Number(t);return Number.isFinite(r)&&r>=0?r:e}function ia(t){const e=(r,n)=>r===0?`${n} kept indefinitely`:`${n} ${r}d`;return`${e(t.processDays,"processes")}, ${e(t.eventDays,"sessions/executions")}, machines never expire`}const xA=`-- 057 local store.
13
+ `}function dA(t,e){const r=t.segments.map(n=>({...n}));for(;r.length>0&&r[r.length-1].text.trim()==="";)r.pop();if(r.length>0){const n=r[r.length-1];n.text=n.text.trimEnd()}return r.map(n=>{if(!e||!n.role||n.text.trim()==="")return n.text;const o=n.text.length-n.text.trimStart().length,s=n.text.trim(),i=n.text.length-o-s.length;return`${" ".repeat(o)}\x1B[${uA[n.role]}m${s}\x1B[0m${" ".repeat(i)}`}).join("")}function $e(t){return[...t].length}function fA(t,e){const r=t.split(/\s+/).filter(s=>s.length>0),n=[];let o="";for(const s of r)o.length===0?o=s:$e(o)+1+$e(s)<=e?o+=` ${s}`:(n.push(o),o=s);return(o.length>0||n.length===0)&&n.push(o),n}function tn(t,e,r,n,o,s){const i=Math.max(12,o-Math.max(e,r)),a=fA(n,i),c=[t.at(e,a[0],s)];for(const u of a.slice(1))c.push(_().at(r,u,s));return c}function an(t){return t.ascii?{sep:", ",dash:"--",arrow:"->",range:"-"}:{sep:" · ",dash:"—",arrow:"→",range:"–"}}function Lt(t,e){const r=an(e).sep,n=r.trim(),o=r.slice(0,r.indexOf(n));return t.text(o).text(n,"dim").text(r.slice(o.length+n.length))}function J(t){return t.replace(/-/g," ")}function Je(t){return t==="observed"?"dim":void 0}function ce(t){return"value"in t?t.value:void 0}function Ke(t,e){return t===1?e:`${e}s`}function Te(t){return Number.isInteger(t)?t.toLocaleString("en-US"):t.toLocaleString("en-US",{minimumFractionDigits:1,maximumFractionDigits:1})}function Et(t){if(t<1e3)return String(Math.round(t));if(t<1e6)return`${(t/1e3).toFixed(t<1e4?1:0)}K`;if(t<1e9)return`${(t/1e6).toFixed(t<1e7?1:0)}M`;const e=t/1e9;return`${e.toFixed(e<10?3:e<100?2:1)}B`}function mt(t){const e=Math.round(t/6e4);return e<1?`${Math.round(t/1e3)}s`:e<60?`${e}m`:`${Math.floor(e/60)}h ${e%60}m`}function wy(t){if(t<6e4)return`${Math.round(t/1e3)}s`;if(t<36e5)return`${Math.round(t/6e4)}m`;const e=Math.round(t/6e4);return`${Math.floor(e/60)}h ${e%60}m`}function iu(t){const e=Math.round(t/1e3);if(e<60)return`${e}s`;if(e<3600){const n=e%60;return n===0?`${Math.floor(e/60)}m`:`${Math.floor(e/60)}m ${n}s`}const r=Math.round(t/6e4);return`${Math.floor(r/60)}h ${r%60}m`}function Wn(t,e){const r=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(new Date(t)),n=o=>r.find(s=>s.type===o)?.value??"";return{day:`${n("year")}-${n("month")}-${n("day")}`,time:`${n("hour")}:${n("minute")}`,zone:pA(t,e)}}function pA(t,e){const r=s=>new Intl.DateTimeFormat(s,{timeZone:e,timeZoneName:"short"}).formatToParts(new Date(t)).find(i=>i.type==="timeZoneName")?.value??"",n=r("en-US");if(!n.startsWith("GMT"))return n;const o=r("en-GB");return o.length>0?o:n}function ds(t,e){const r=an(e),n=Wn(t.from,e.timeZone),o=Wn(t.to,e.timeZone);if(n.day===o.day&&n.zone===o.zone)return`${n.day}${r.sep}${n.time}${r.range}${o.time} ${o.zone}`;const s=n.zone===o.zone?"":` ${n.zone}`;return`${n.day} ${n.time}${s} ${r.arrow} ${o.day} ${o.time} ${o.zone}`}function au(t,e,r){const n=Wn(t,r.timeZone);return Wn(e.from,r.timeZone).day===Wn(e.to,r.timeZone).day?n.time:`${n.day} ${n.time}`}function cd(t,e){const r=Wn(t,e.timeZone);return`${r.day} ${r.time} ${r.zone}`}function ma(t,e){const r=_().text("057","dim").text(" ").text("COMPUTATIONAL ACTIVITY","bold");return r.length+2+$e(t)<=e?[r.right(e-1,t,"dim")]:[r,_().right(e-1,t,"dim")]}function ud(t,e,r,n){const o=ds(t,n),s=_();return e.forEach((i,a)=>{a>0&&Lt(s,n),s.text(i.text,i.role)}),e.length===0?[_().text(o)]:$e(o)+2+s.length<=r?[_().text(o).padTo(r-s.length).append(s)]:[_().text(o),s]}function fs(t){return t==="observed"?void 0:"yellow"}function Ay(t){return t==="within-retention"||t==="retained-indefinitely"?void 0:"yellow"}function bt(t,e){const r=t.match(/^\[(.+)\]$/);if(!r)return{text:t,pseudo:!1};const n=J(r[1]);return{text:e==="model"||e==="executor"?`${e} ${n}`:n,pseudo:!0}}function hA(t,e=ad){const r=mA(e.width),{summary:n,availability:o}=t,s=[...ma("SUMMARY",r.measure),...ud(t.period,[{text:J(o.observation),role:fs(o.observation)},{text:J(o.retention.state),role:Ay(o.retention.state)}],r.measure,e),Lt(_().text(String(n.executions),"bold").text(` ${Ke(n.executions,"execution")}`),e).text(String(n.sessions),"bold").text(` ${Ke(n.sessions,"session")}`)];for(const i of yA(t,e)){s.push(_(),_().text(i.head,"dim"));const a=Math.max(4,...i.rows.map(c=>c.kind==="model"?(c.tokens??"").length:0));for(const c of i.rows)s.push(...gA(c,r,a,e))}return ha(s,e)}function mA(t){if(t>=80)return{measure:79,labelMax:22,figureEnd:33,compositeCol:24,tailCol:35,evidenceCol:67,split:!1,stacked:!1};const e=Math.max(1,t-1);if(t>=56)return{measure:e,labelMax:20,figureEnd:29,compositeCol:4,tailCol:31,evidenceCol:43,split:!0,stacked:!1};const r=Math.min(43,Math.max(24,e-12));return{measure:e,labelMax:20,figureEnd:29,compositeCol:4,tailCol:31,evidenceCol:r,split:!0,stacked:!0}}function yA(t,e){const{summary:r,availability:n}=t,o=an(e).dash,s=(v,g,I,N)=>{const S=ce(g);return S===void 0?{kind:"figure",label:v,figure:o,dash:!0,evidence:g.state}:{kind:"figure",label:v,figure:I(S),dash:!1,tail:N?.(S),evidence:g.state}},i=(v,g)=>({kind:"figure",label:v,figure:String(g),dash:!1}),a=r.executions===0&&n.observation!=="observed"?{head:"RECORDED LIFECYCLE",rows:[{kind:"prose",text:"no execution records; zero work is not established"}]}:{head:n.observation==="observed"?"NOW":"RECORDED LIFECYCLE",rows:[i("running",r.runningNow),s("waiting",r.waitingNow,String),i("idle",r.idleNow)]},c=r.terminalExecutionDuration,u=ce(c),d=u===void 0?{kind:"figure",label:"terminal execution",figure:o,dash:!0,evidence:c.state}:{kind:"composite",label:"terminal execution",evidence:c.state,value:Lt(Lt(_().text("median ").text(mt(u.median),"bold"),e).text("p90 ").text(mt(u.p90),"bold"),e).text("max ").text(mt(u.maximum),"bold")},l=r.usageByModel.map(v=>{const g=ce(v.tokens);return{kind:"model",label:v.model,pseudo:!1,executions:v.executions,tokens:g===void 0?o:Et(g),dash:g===void 0,evidence:v.tokens.state}}),m=r.modelMix.filter(v=>bt(v.key,"model").pseudo);if(m.reduce((v,g)=>v+g.executions,0)===r.executionsWithoutModel)for(const v of m)l.push({kind:"model",label:bt(v.key,"model").text,pseudo:!0,executions:v.executions});else r.executionsWithoutModel>0&&l.push({kind:"model",label:"model not observed",pseudo:!0,executions:r.executionsWithoutModel});const h=[a,{head:"OUTCOMES",rows:[s("completed",r.completed,String),s("failed",r.failed,String),s("interrupted",r.interrupted,String)]},{head:"DURATION",rows:[s("time in flight",r.inFlight.totalMs,fe),s("added by open records",r.inFlight.openContributionMs,fe),s("parallel in flight",r.inFlight.parallelMs,fe),s("in-flight peak",r.inFlight.peak,v=>String(v.peak),v=>v.at===null?_():_().text(`at ${au(v.at,t.period,e)}`)),d,s("terminal interval",r.terminalExecutionIntervalMs,mt),s("terminal overlap",r.overlappingTerminalIntervalMs,mt),s("terminal peak",r.peakTerminalConcurrency,v=>String(v.peak),v=>v.at===null?_():_().text(`at ${au(v.at,t.period,e)}`))]},{head:"USAGE",rows:[s("tokens",r.tokens,Et),s("tool interactions",r.toolInteractions,Et),s("tool errors",r.toolErrors,Et),s("explicit waits",r.waits,v=>String(v.count),v=>{const g=_().text("for ").text(mt(v.durationMs),"bold");return v.openNow>0?Lt(g,e).text(String(v.openNow),"bold").text(" open"):g})]}];return h.push({head:"INTERVAL POLICY",rows:[{kind:"prose",text:r.inFlight.assumption}]}),l.length>0&&h.push({head:"BY MODEL",rows:l}),h}function gA(t,e,r,n){const o=(s,i)=>i===void 0?s:s.at(e.evidenceCol,J(i),Je(i));switch(t.kind){case"prose":return tn(_(),2,2,t.text,e.measure);case"figure":{const s=t.dash?void 0:"bold";if(e.stacked){const c=_().at(4,t.figure,s);return t.tail&&t.tail.length>0&&c.text(" ").append(t.tail),[o(_().at(2,t.label),t.evidence),c]}const i=[];let a=_();return t.label.length>e.labelMax?i.push(_().at(2,t.label)):a.at(2,t.label),a.right(e.figureEnd,t.figure,s),t.tail&&t.tail.length>0&&a.at(e.tailCol,"").append(t.tail),i.push(o(a,t.evidence)),i}case"composite":{if(e.split)return[o(_().at(2,t.label),t.evidence),_().at(4,"").append(t.value)];const s=[],i=_();return t.label.length>e.labelMax?s.push(_().at(2,t.label)):i.at(2,t.label),s.push(o(i.at(e.compositeCol,"").append(t.value),t.evidence)),s}case"model":{const s=t.pseudo?"dim":void 0,i=t.tokens===void 0?` ${Ke(t.executions,"execution")}`:` ${Ke(t.executions,"execution").padEnd(10)}`,a=d=>(d.text(String(t.executions),"bold").text(i),t.tokens===void 0?d:Lt(d,n).text(t.tokens.padStart(r),t.dash?void 0:"bold").text(" tokens"));if(e.split){const d=_().padTo(7-String(t.executions).length);return[o(_().at(2,t.label,s),t.evidence),a(d)]}const c=[],u=_();return t.label.length>e.labelMax?c.push(_().at(2,t.label,s)):u.at(2,t.label,s),u.padTo(e.figureEnd-String(t.executions).length+1),c.push(o(a(u),t.evidence)),c}}}const Kn={"median terminal execution duration":{label:"median terminal duration",duration:!0},"terminal execution interval union":{label:"terminal interval union",duration:!0},"overlapping terminal interval":{label:"overlapping interval",duration:!0},"explicit wait count":{label:"explicit waits"}};function vA(t,e){const r=an(e).dash,n=[],o=[];for(const u of t.dimensions)if(bA(u)){const d=u.dimension.replace(/ mix$/,"");o.push({head:u.dimension.toUpperCase(),subject:d,a:tp(u.periodA,d),b:tp(u.periodB,d),result:J(u.eligibility)})}else{const d=Kn[u.dimension],l=m=>{const p=ce(m);return typeof p!="number"?{value:r,dash:!0,evidence:m.state}:{value:d?.duration?iu(p):Te(p),dash:!1,evidence:m.state}};n.push({label:d?.label??u.dimension,a:l(u.periodA),b:l(u.periodB),result:J(u.eligibility)})}const s=AA(n,o),i=s.measure<=e.width-1?"wide":e.width>=80?"paired":"stacked",a=i==="wide"?s.measure:i==="paired"?79:Math.max(1,e.width-1),c=[...ma("COMPARISON",a)];return c.push(...rp("A",t.periodA,t.availabilityA.observation,a,e)),c.push(...rp("B",t.periodB,t.availabilityB.observation,a,e)),c.push(_(),...wA(t,a)),c.push(_()),i==="wide"?c.push(...SA(n,o,s,r)):i==="paired"?c.push(...kA(n,o)):c.push(...EA(n,o)),ha(c,e)}function bA(t){const e=ce(t.periodA)??ce(t.periodB);return t.dimension.endsWith(" mix")||e!==void 0&&typeof e=="object"}function tp(t,e){const r=ce(t);return r===void 0||typeof r=="number"?{evidence:t.state}:{evidence:t.state,items:Object.entries(r).map(([n,o])=>{const s=bt(n,e);return{key:s.text,pseudo:s.pseudo,count:o}})}}function rp(t,e,r,n,o){const s=ds(e,o),i=J(r),a=Math.max(46,3+$e(s)+3),c=_().text(t,"bold").at(3,s);return a+$e(i)<=n?[c.at(a,i,fs(r))]:[c,_().at(3,i,fs(r))]}function wA(t,e){const r=[_().text(J(t.eligibility).toUpperCase(),t.eligibility==="comparable"?"bold":"bold-yellow")];for(const o of t.reasons){const s=o.match(/^period ([AB]): (.*)$/);s?r.push(...tn(_().at(2,s[1],"dim"),5,5,s[2],e)):r.push(...tn(_(),2,2,o,e))}const n=new Map;for(const o of t.dimensions)for(const s of o.reasons){const i=n.get(s)??[];i.push(Kn[o.dimension]?.label??o.dimension),n.set(s,i)}for(const[o,s]of n){const i=s.length===t.dimensions.length?"All dimensions":s.join(", ");r.push(...tn(_(),2,2,`${i}: ${o}.`,e))}return r}function AA(t,e){const r=p=>e.flatMap(h=>h[p].items?.map(v=>Te(v.count))??[]),n=(p,h)=>Math.max(h,...p.map($e)),o=n([...t.map(p=>p.a.value),...r("a")],13),s=n([...t.map(p=>p.b.value),...r("b")],13),i=n([...t.flatMap(p=>[J(p.a.evidence),J(p.b.evidence)]),...e.flatMap(p=>[J(p.a.evidence),J(p.b.evidence)])],12),a=29+o-1,c=a+3,u=c+i+2+s,d=u+3,l=d+i+3,m=n([...t.map(p=>p.result),...e.map(p=>p.result)],0);return{measure:l+m,aEnd:a,aEvidence:c,bEnd:u,bEvidence:d,result:l}}function Ci(t){return t.dash?void 0:"bold"}function cu(t,e,r,n){return $e(t)>e?{lead:[_().at(r,t,n)],row:_()}:{lead:[],row:_().at(r,t,n)}}function SA(t,e,r,n){const o=[_().text("MEASURE","dim").right(r.aEnd,"A","dim").right(r.bEnd,"B","dim").at(r.result,"COMPARISON","dim")];for(const s of t){const{lead:i,row:a}=cu(s.label,25,2);o.push(...i,a.right(r.aEnd,s.a.value,Ci(s.a)).at(r.aEvidence,J(s.a.evidence),Je(s.a.evidence)).right(r.bEnd,s.b.value,Ci(s.b)).at(r.bEvidence,J(s.b.evidence),Je(s.b.evidence)).at(r.result,s.result))}for(const s of e){o.push(_(),_().text(s.head,"dim").at(r.aEvidence,J(s.a.evidence),Je(s.a.evidence)).at(r.bEvidence,J(s.b.evidence),Je(s.b.evidence)).at(r.result,s.result));const i=new Map;for(const a of s.a.items??[])i.set(a.key,{pseudo:a.pseudo,a:a.count});for(const a of s.b.items??[])i.set(a.key,{...i.get(a.key),pseudo:a.pseudo,b:a.count});for(const[a,c]of i){const{lead:u,row:d}=cu(a,25,2,c.pseudo?"dim":void 0);s.a.items&&d.right(r.aEnd,c.a===void 0?n:Te(c.a),c.a===void 0?void 0:"bold"),s.b.items&&d.right(r.bEnd,c.b===void 0?n:Te(c.b),c.b===void 0?void 0:"bold"),o.push(...u,d)}}return o}function kA(t,e){const r=[_().text("MEASURES","dim").right(78,"COMPARISON","dim")],n=(o,s,i,a)=>o.at(i,s,"dim").right(i+15,a.value,Ci(a)).at(i+18,J(a.evidence),Je(a.evidence));for(const o of t)r.push(_().at(2,o.label).right(78,o.result)),r.push(n(n(_(),"A",4,o.a),"B",40,o.b));for(const o of e)r.push(_(),_().text(o.head,"dim").right(78,o.result)),r.push(...Sy(o,29));return r}function EA(t,e){const r=[_().text("MEASURES","dim")],n=(o,s)=>_().at(4,o,"dim").right(28,s.value,Ci(s)).at(31,J(s.evidence),Je(s.evidence));t.forEach((o,s)=>{s>0&&r.push(_()),r.push(_().at(2,o.label),n("A",o.a),n("B",o.b),_().at(4,"comparison","dim").at(16,o.result))});for(const o of e)r.push(_(),_().text(o.head,"dim"),...Sy(o,28)),r.push(_().at(2,"comparison","dim").at(16,o.result));return r}function Sy(t,e){const r=[];for(const[n,o]of[["A",t.a],["B",t.b]]){r.push(_().at(2,n,"dim").at(5,J(o.evidence),Je(o.evidence)));for(const s of o.items??[]){const{lead:i,row:a}=cu(s.key,e-5-1-$e(Te(s.count)),5,s.pseudo?"dim":void 0);r.push(...i,a.right(e,Te(s.count),"bold"))}}return r}const xA=["summary","availability","compare","breakdown"];function tr(t,e,r=ad){switch(t.operation){case"summary":return hA(t.result,r);case"availability":return IA(t.result,r);case"compare":return vA(t.result,r);case"breakdown":return OA(t.result,e,r)}}const ky={"tool-interactions":"tool interactions","tool-errors":"tool errors"};function IA(t,e){const r=e.width>=80,n=e.width<56,o=r?79:Math.max(1,e.width-1),s=25,i=[...ma("AVAILABILITY",o),...ud(t.period,[],o,e)],a=(m,p)=>n?[_().at(2,m),_().padTo(4).append(p)]:[_().at(2,m).padTo(s).append(p)],c=(m,p)=>_().text(m,p),u=m=>i.push(_(),_().text(m,"dim"));u("OBSERVATION"),i.push(...a("state",c(J(t.observation),fs(t.observation))),...a("records",Lt(_().text(String(t.executionRecords),"bold").text(` ${Ke(t.executionRecords,"execution")}`),e).text(String(t.sessionRecords),"bold").text(` ${Ke(t.sessionRecords,"session")}`)),...a("continuity",c(J(t.continuity.state),Je(t.continuity.state))),...a("observation gaps",c(J(t.observationGaps.state),Je(t.observationGaps.state))),...a("unprojected work",c(J(t.unprojectedSourceWork.state),Je(t.unprojectedSourceWork.state)))),u("RETENTION"),i.push(...a("state",c(J(t.retention.state),Ay(t.retention.state)))),t.retention.semanticFrom!==null&&i.push(...a("semantic history from",c(cd(t.retention.semanticFrom,e),"bold")));const d=t.bounds;if(o>=51)i.push(_(),_().text("BOUNDS","dim").right(32,"observed","dim").right(42,"inferred","dim").right(50,"open","dim"),_().at(2,"starts").right(32,String(d.observedStarts),"bold").right(42,String(d.inferredStarts),"bold"),_().at(2,"ends").right(32,String(d.observedEnds),"bold").right(42,String(d.inferredEnds),"bold").right(50,String(d.openEnds),"bold"));else{const m=p=>{const h=_().padTo(4);return p.forEach(([v,g],I)=>{I>0&&Lt(h,e),h.text(String(v),"bold").text(` ${g}`)}),h};u("BOUNDS"),i.push(_().at(2,"starts"),m([[d.observedStarts,"observed"],[d.inferredStarts,"inferred"]]),_().at(2,"ends"),m([[d.observedEnds,"observed"],[d.inferredEnds,"inferred"],[d.openEnds,"open"]]))}u("COMPARISON");const l=t.comparisonReadiness==="comparable"?void 0:"yellow";i.push(...a("readiness",c(J(t.comparisonReadiness),l))),t.reasons.forEach((m,p)=>{const h=p===0?"because":"";n?(h&&i.push(_().at(2,h)),i.push(...tn(_(),4,4,m,o))):i.push(...tn(_().at(2,h),s,s,m,o))}),i.push(_()),r?i.push(_().text("MEASURES","dim").at(21,"state","dim").at(35,"coverage","dim").right(78,"records","dim")):i.push(_().text("MEASURES","dim").at(s,"state","dim").right(o-1,"records","dim"));for(const m of t.measures){const p=ky[m.dimension]??J(m.dimension),h=J(m.state),v=_().text("/","dim").text(" ").text(String(m.coverage.records),"bold");if(r){const g=_().at(2,p).at(21,h,Je(m.state));i.push(...np(g,35,78,m.coverage,v,e))}else i.push(_().at(2,p).at(s,h,Je(m.state))),i.push(...np(_(),4,o-1,m.coverage,v,e))}u("SOURCES"),t.sources.length===0&&i.push(_().at(2,"none observed"));for(const m of t.sources){const p=String(m.executionRecords),h=`execution ${Ke(m.executionRecords,"record")}`;if(29+$e(h)>o){i.push(_().at(2,m.source),_().at(4,p,"bold").text(` ${h}`));continue}const v=g=>g.right(27,p,"bold").at(29,h);$e(m.source)>22?i.push(_().at(2,m.source),v(_())):i.push(v(_().at(2,m.source)))}return ha(i,e)}function np(t,e,r,n,o,s){const a=[[n.observed,"observed"],[n.inferred,"inferred"],[n.partial,"partial"],[n.notObserved,"not-observed"],[n.unsupported,"unsupported"],[n.unknown,"unknown"]].filter(([m])=>m>0).map(([m,p])=>_().text(String(m),"bold").text(" ").text(J(p),Je(p))),c=an(s).sep,u=r-o.length,d=[[]];let l=e;for(const m of a){const p=d[d.length-1],h=l+(p.length>0?c.length:0)+m.length;p.length>0&&h>u?(d.push([m]),l=e+m.length):(p.push(m),l=h)}return d.map((m,p)=>{const h=p===0?t.padTo(e):_().padTo(e);if(m.forEach((v,g)=>{g>0&&Lt(h,s),h.append(v)}),p<d.length-1){const v=c.trim();return h.text(c.slice(0,c.indexOf(v))).text(v,"dim"),h}return h.padTo(r-o.length+1).append(o)})}function OA(t,e,r){const n=an(r).dash,o=d=>{const l=ce(d);return l===void 0?{value:n,dash:!0,evidence:d.state}:{value:Te(l),dash:!1,evidence:d.state}},s=t.items.filter(d=>e===void 0||d.key===e).map(d=>{const l=bt(d.key,t.dimension),m=ce(d.terminalDuration);return{key:l.text,pseudo:l.pseudo,executions:Te(d.executions),singular:d.executions===1,terminal:Te(d.terminalExecutions),median:m===void 0?n:wy(m.median),medianDash:m===void 0,tokens:o(d.tokens),tools:o(d.toolInteractions),errors:o(d.toolErrors),failed:o(d.failed)}}),i=CA(s,t.dimension),a=s.length>0&&i.measure<=r.width-1?"table":r.width>=80?"records":"narrow",c=a==="table"?i.measure:a==="records"?79:Math.max(1,r.width-1),u=[...ma(`BREAKDOWN${an(r).sep}${J(t.dimension).toUpperCase()}`,c),...ud(t.period,[{text:J(t.availability.observation),role:fs(t.availability.observation)}],c,r),_()];if(s.length===0)u.push(_().text("none observed"));else if(a==="table")u.push(...i.lines);else{const d=a==="records"?NA(s):null;s.forEach((l,m)=>{m>0&&u.push(_()),u.push(...d?TA(l,d,r):$A(l,s,r))})}return u.push(_(),...tn(_(),0,0,t.qualification,c,"dim")),ha(u,r)}function Ni(t){return t.pseudo?"dim":"bold"}function Ti(t,e,r){return r.evidence===void 0?t:t.at(e,J(r.evidence),Je(r.evidence))}function CA(t,e){const r=J(e).toUpperCase(),n=[{caption:"EXECUTIONS",value:m=>m.executions},{caption:"TERMINAL",value:m=>m.terminal},{caption:"MEDIAN",value:m=>m.median}],o=[{caption:"TOKENS",value:m=>m.tokens},{caption:"TOOLS",value:m=>m.tools},{caption:"ERRORS",value:m=>m.errors},{caption:"FAILED",value:m=>m.failed}],s=m=>Math.max(0,...m.map($e));let i=Math.max($e(r),s(t.map(m=>m.key))),a=$e(r)-1;const c=n.map(m=>{const p=i+2+Math.max($e(m.caption),s(t.map(m.value)))-1;return i=p+1,a=p,p}),u=o.map(m=>{const p=t.map(m.value);let h=i+2+s(p.map(v=>v.value))-1;return h=Math.max(h,a+2+$e(m.caption)),i=h+3+s(p.map(v=>J(v.evidence??""))),a=h,h}),d=_().text(r,"dim");n.forEach((m,p)=>d.right(c[p],m.caption,"dim")),o.forEach((m,p)=>d.right(u[p],m.caption,"dim"));const l=[d];for(const m of t){const p=_().text(m.key,Ni(m));n.forEach((h,v)=>p.right(c[v],h.value(m),"bold")),o.forEach((h,v)=>{const g=h.value(m);Ti(p.right(u[v],g.value,g.dash?void 0:"bold"),u[v]+3,g)}),l.push(p)}return{measure:i,lines:l}}function Ey(t){const e=r=>Math.max(3,...t.map(n=>$e(r(n))));return{countWidth:e(r=>r.executions),terminalWidth:e(r=>r.terminal),medianWidth:e(r=>r.median)}}function NA(t){const e=o=>Math.max(1,...t.flatMap(s=>o(s).map(i=>$e(i.value)))),r=Math.max(24,10+e(o=>[o.tokens,o.errors])-1),n=Math.max(44,r+3+12+2);return{...Ey(t),countEnd:34,leftEnd:r,rightLabel:n,rightEnd:Math.max(61,n+6+2+e(o=>[o.tools,o.failed])-1)}}function xy(t,e,r,n){return t.text(e.executions.padStart(r.countWidth),"bold").text(` ${(e.singular?"execution":"executions").padEnd(10)}`),Lt(t,n).text(e.terminal.padStart(r.terminalWidth),"bold").text(" terminal"),Lt(t,n).text("median "),t.text(e.median.padStart(r.medianWidth),e.medianDash?void 0:"bold")}function TA(t,e,r){const n=[],o=e.countEnd-e.countWidth+1,s=_();$e(t.key)>=o?n.push(_().text(t.key,Ni(t))):s.text(t.key,Ni(t)),n.push(xy(s.padTo(o),t,e,r));const i=(a,c,u,d)=>{const l=_().at(2,a);return Ti(l.right(e.leftEnd,c.value,c.dash?void 0:"bold"),e.leftEnd+3,c),l.at(e.rightLabel,u),Ti(l.right(e.rightEnd,d.value,d.dash?void 0:"bold"),e.rightEnd+3,d)};return n.push(i("tokens",t.tokens,"tools",t.tools),i("errors",t.errors,"failed",t.failed)),n}function $A(t,e,r){const n=Math.max(1,...e.flatMap(i=>[i.tokens,i.tools,i.errors,i.failed].map(a=>$e(a.value)))),o=Math.max(24,10+n-1),s=(i,a)=>Ti(_().at(2,i).right(o,a.value,a.dash?void 0:"bold"),o+3,a);return[_().text(t.key,Ni(t)),xy(_().padTo(2),t,Ey(e),r),s("tokens",t.tokens),s("tools",t.tools),s("errors",t.errors),s("failed",t.failed)]}const op=["summary","availability","compare","breakdown"],sp=["lifecycle","duration","tokens","waits","errors"],ip=["model","executor"],ap=["today","last-7d"];function BA(t){const e=op.find(a=>a===t.query),r=ap.find(a=>a===(t.scope??"today"));if(!e)return{error:`query must be one of ${op.join(", ")}`};if(!r)return{error:`scope must be one of ${ap.join(", ")}`};const n=t.focus?sp.find(a=>a===t.focus):void 0,o=t.by?ip.find(a=>a===t.by):void 0;if(t.focus&&!n)return{error:`focus must be one of ${sp.join(", ")}`};if(t.by&&!o)return{error:`by must be one of ${ip.join(", ")}`};if(!{summary:[void 0,"lifecycle","duration"],availability:[void 0,"tokens","waits"],breakdown:[void 0,"errors"],compare:[void 0]}[e].includes(n))return{error:`${e} has no ${n} reading`};if(e==="breakdown"&&!o)return{error:"breakdown needs by=model|executor"};if(e!=="breakdown"&&o)return{error:`${e} takes no dimension`};if(n==="errors"&&o!=="model")return{error:"errors are read by model"};const i={query:e,scope:r};return n&&(i.focus=n),o&&(i.by=o),i}function uu(t,e){if(t==="last-7d")return{from:e-7*864e5,to:e};const r=new Date(e);return r.setHours(0,0,0,0),{from:r.getTime(),to:e}}function ld(t){const e=t.to-t.from;return{from:t.from-e,to:t.from}}function Iy(t,e){const r=n=>{const o=new Date(n);return o.setDate(o.getDate()-e),o.getTime()};return{from:r(t.from),to:r(t.to)}}function RA(t,e,r,n={}){const o=n.period??uu(e.scope,r),s={};switch(e.query){case"summary":s.summary=t.summary(o);break;case"availability":e.focus&&(s.summary=t.summary(o)),s.availability=s.summary?.availability??t.availability(o);break;case"breakdown":s.breakdown=t.breakdown(o,e.by??"model"),e.focus==="errors"&&(s.summary=t.summary(o));break;case"compare":s.comparison=t.compare(o,ld(o));break}return Oy(e,s,n)}function Oy(t,e,r={}){const n=MA(t,e,r);return r.projectKey!==void 0&&(n.observation.unshift({k:"WORKING CONTEXT",v:"Selected working context only; the same filter applies to every period."}),n.command="No equivalent CLI command for this working-context selection.",n.text=`SELECTED WORKING CONTEXT ONLY — filtered before aggregation.
14
+
15
+ `+n.text),r.period&&(n.title="SELECTED PERIOD",n.command="Selected historical bounds; use the period controls to reproduce this reading."),n}function MA(t,e,r){const n={...ad,timeZone:r.timeZone};switch(t.query){case"summary":{const o=qr(e.summary,"summary");return t.focus==="duration"?DA(t,o,r,n):t.focus==="lifecycle"?jA(t,o,r,n):_A(t,o,r,n)}case"availability":{const o=qr(e.availability,"availability");return t.focus==="tokens"?PA(t,qr(e.summary,"summary"),r,n):t.focus==="waits"?UA(t,qr(e.summary,"summary"),r,n):LA(t,o,r,n)}case"breakdown":{const o=qr(e.breakdown,"breakdown");return t.focus==="errors"?HA(t,o,qr(e.summary,"summary"),r,n):VA(t,o,r,n)}case"compare":return FA(t,qr(e.comparison,"comparison"),n)}}function _A(t,e,r,n){const{summary:o,availability:s}=e,i=Hr(t,"SUMMARY",s,!0,r,n),a=tr({operation:"summary",result:e},void 0,n);if(o.executions===0||Ar(s))return Fr(i,s,a,n);const c=[Cy(e)],u=ce(o.completed),d=ce(o.failed);u!==void 0&&d!==void 0&&c.push(`${u} completed and ${d} failed${jy([o.completed,o.failed])}.`);const l=cn(s,"waits");l&&Jn(l.coverage,"unsupported")&&c.push(`Waits are unsupported for all ${o.executions}.`);const m=[...i.observation,ya(s)],p=zA(s);return p&&m.push(p),m.push({k:"ENDS",v:Ry(s)}),{...i,finding:c.join(" "),observation:m,evidence:[...Ny(e,"lifecycle",t),De("completed",o.completed,String,Ce(t,"summary","lifecycle")),De("failed",o.failed,String,Ce(t,"summary","lifecycle")),De("interrupted",o.interrupted,String,Ce(t,"summary","lifecycle")),De("terminal interval",o.terminalExecutionIntervalMs,mt,Ce(t,"summary","duration")),De("overlapping interval",o.overlappingTerminalIntervalMs,mt,Ce(t,"summary","duration")),De("tokens",o.tokens,Et,Ce(t,"availability","tokens")),De("tool interactions",o.toolInteractions,Et,Ce(t,"breakdown","errors")),De("tool errors",o.toolErrors,Et,Ce(t,"breakdown","errors")),Ty(e,Ce(t,"availability","waits"))],command:rr("summary",t.scope),text:a}}function jA(t,e,r,n){const{summary:o,availability:s}=e,i=Hr(t,"SUMMARY · LIFECYCLE",s,!0,r,n),a=tr({operation:"summary",result:e},void 0,n);if(o.executions===0||Ar(s))return Fr(i,s,a,n);const c=[Cy(e)],u=[o.completed,o.failed,o.interrupted],[d,l,m]=u.map(I=>ce(I));d!==void 0&&l!==void 0&&m!==void 0&&c.push(`${d} completed, ${l} failed and ${m} interrupted${jy(u)}.`),Jn(o.waitingNow.coverage,"unsupported")&&c.push(`Waiting is unsupported for all ${o.executions}.`);const p=cn(s,"outcomes"),h=[...i.observation];p&&h.push({k:"OUTCOMES",v:ps(p.state,p.coverage)}),h.push({k:"ENDS",v:Ry(s)});const v=o.terminalExecutionDuration,g=ce(v);return{...i,finding:c.join(" "),observation:h,evidence:[...Ny(e,void 0,t),De("completed",o.completed,String),De("failed",o.failed,String),De("interrupted",o.interrupted,String),{k:"terminal execution",...g?{t:_y(g)}:{},v:g?"":"—",e:J(v.state),focus:Ce(t,"summary","duration")}],command:rr("summary",t.scope),text:a}}function DA(t,e,r,n){const{summary:o,availability:s}=e,i=Hr(t,"SUMMARY · DURATION",s,!0,r,n),a=tr({operation:"summary",result:e},void 0,n);if(o.executions===0||Ar(s))return Fr(i,s,a,n);const c=ce(o.inFlight.totalMs),u=ce(o.terminalExecutionIntervalMs),d=ce(o.inFlight.openContributionMs),l=ce(o.inFlight.parallelMs),m=ce(o.inFlight.peak),p=[];c!==void 0&&u!==void 0&&d!==void 0&&l!==void 0&&(p.push(`Recorded intervals cover ${fe(c)} — the TIME IN FLIGHT estimate.`),p.push(`Ended runs cover ${fe(u)}; open records add ${fe(d)} after overlaps are removed.`),p.push(`Parallel intervals overlap for ${fe(l)}.`));const h=[...i.observation];s.bounds.openEnds>0&&h.push({k:"OPEN ENDS",v:`${s.bounds.openEnds} of ${o.executions} executions ${s.bounds.openEnds===1?"has":"have"} no observed end`}),s.continuity.state!=="observed"&&h.push(ya(s)),h.push({k:"INTERVAL POLICY",v:o.inFlight.assumption}),h.push({k:"ROUNDING",v:"Durations are rounded independently; displayed parts may differ from their total by a minute."});const v=o.terminalExecutionDuration,g=ce(v);return{...i,finding:p.join(" "),observation:h,evidence:[De("time in flight",o.inFlight.totalMs,fe),De("ended interval union",o.terminalExecutionIntervalMs,fe),De("added by open records",o.inFlight.openContributionMs,fe),De("overlapping interval",o.inFlight.parallelMs,fe),{...De("peak concurrency",o.inFlight.peak,I=>String(I.peak)),...m&&m.at!==null?{t:`at ${au(m.at,e.period,n)}`}:{}},{k:"terminal execution",...g?{t:_y(g)}:{},v:g?"":"—",e:J(v.state)},{k:"executions",v:String(o.executions),e:"",focus:Ce(t,"summary","lifecycle")},{k:"sessions",v:String(o.sessions),e:"",focus:Ce(t,"summary","lifecycle")}],command:rr("summary",t.scope),text:a}}function Cy(t){const{summary:e}=t,r=ce(e.waitingNow),n=[e.runningNow>0?`${e.runningNow} running`:void 0,r!==void 0&&r>0?`${r} waiting`:void 0,e.idleNow>0?`${e.idleNow} idle`:void 0].filter(s=>s!==void 0),o=`${e.executions} ${Ke(e.executions,"execution")} across ${e.sessions} ${Ke(e.sessions,"session")}`;return n.length>0?`${o}; ${Zn(n)}.`:`${o}.`}function Ny(t,e,r){const{summary:n}=t,o=e?Ce(r,"summary",e):void 0,s=(i,a)=>({k:i,v:String(a),e:"",...o?{focus:o}:{}});return[s("executions",n.executions),s("sessions",n.sessions),s("running",n.runningNow),De("waiting",n.waitingNow,String,o),s("idle",n.idleNow)]}function Ty(t,e){const r=t.summary.waits,n=ce(r);return{k:"explicit waits",...n?{t:`for ${mt(n.durationMs)}${n.openNow>0?` · ${n.openNow} open`:""}`}:{},v:n?String(n.count):"—",e:J(r.state),...e?{focus:e}:{}}}function LA(t,e,r,n){const o=Hr(t,"AVAILABILITY",e,!1,r,n),s=tr({operation:"availability",result:e},void 0,n),i=e.executionRecords;if(Ar(e))return Fr(o,e,s,n);const a=[],c=[e.continuity.state==="unknown"?"Continuity":void 0,e.observationGaps.state==="unknown"?"gaps":void 0,e.unprojectedSourceWork.state==="unknown"?"unprojected work":void 0].filter(l=>l!==void 0);if(c.length>0){const l=Zn(c);a.push(`${l[0].toUpperCase()}${l.slice(1)} ${c.length===1?"is":"are"} unknown.`)}if(i===0)a.push("No execution records, so no measure has coverage to report.");else{const l=e.measures.filter(p=>Jn(p.coverage,"unsupported"));if(l.length>0){const p=Zn(l.map(h=>$c(h.dimension)));a.push(`${p[0].toUpperCase()}${p.slice(1)} ${l.length===1?"is":"are"} unsupported for all ${i}.`)}const m=[...e.measures].filter(p=>!Jn(p.coverage,"unsupported")&&p.coverage.notObserved>0).sort((p,h)=>h.coverage.notObserved-p.coverage.notObserved)[0];m&&a.push(`The ${$c(m.dimension)} is not observed for ${m.coverage.notObserved} of ${i}.`)}const u=[...o.observation,{k:"RETENTION",v:My(e,n)},{k:"COMPARISON",v:J(e.comparisonReadiness)}],d=[{k:"continuity",v:J(e.continuity.state),e:""},{k:"observation gaps",v:J(e.observationGaps.state),e:""},{k:"unprojected work",v:J(e.unprojectedSourceWork.state),e:""},{k:"execution records",v:String(i),e:""},...e.measures.map(l=>{const m=KA(t,l.dimension);return{k:$c(l.dimension),...l.coverage.records>0?{t:By(l.coverage)}:{},v:"",e:J(l.state),...m?{focus:m}:{}}})];return{...o,finding:a.join(" ")||void 0,observation:u,evidenceCaption:"COVERAGE",evidence:d,command:rr("availability",t.scope),text:s}}function PA(t,e,r,n){const{summary:o,availability:s}=e,i=Hr(t,"AVAILABILITY · TOKENS",s,!1,r,n),a=tr({operation:"availability",result:s},void 0,n);if(o.executions===0||Ar(s))return Fr(i,s,a,n);const c=cn(s,"tokens"),u=cn(s,"model"),d=ce(o.tokens),l=[];if(d!==void 0&&c){const p=c.coverage,h=[p.inferred>0?`${p.inferred} ${p.inferred===1?"is":"are"} inferred`:void 0,p.partial>0?`${p.partial} ${p.partial===1?"is":"are"} partial`:void 0,p.notObserved>0?`${p.notObserved} ${p.notObserved===1?"was":"were"} not observed`:void 0,p.unsupported>0?`${p.unsupported} ${p.unsupported===1?"is":"are"} unsupported`:void 0,p.unknown>0?`${p.unknown} ${p.unknown===1?"is":"are"} unknown`:void 0].filter(v=>v!==void 0);l.push(h.length===0?`${Et(d)} is fully observed for all ${p.records} executions.`:`${Et(d)} is fully observed for ${p.observed} of ${p.records} executions; ${Zn(h)}.`)}else l.push(`Tokens are ${J(o.tokens.state)} for this period.`);o.executionsWithoutModel>0&&l.push(`${o.executionsWithoutModel} ${Ke(o.executionsWithoutModel,"execution")} carry no observed model, so it cannot be divided completely by model.`);const m=[...i.observation];return c&&m.push({k:"TOKENS",v:ps(c.state,c.coverage)}),u&&m.push({k:"MODEL",v:ps(u.state,u.coverage)}),m.push(ya(s)),{...i,finding:l.join(" "),observation:m,evidence:[De("tokens",o.tokens,Et),...WA(e)],command:rr("availability",t.scope),text:a}}function UA(t,e,r,n){const{summary:o,availability:s}=e,i=Hr(t,"AVAILABILITY · WAITS",s,!1,r,n),a=tr({operation:"availability",result:s},void 0,n);if(o.executions===0||Ar(s))return Fr(i,s,a,n);const c=cn(s,"waits"),u=o.executions,d=ce(o.waits);let l,m;const p=c&&(Jn(c.coverage,"unsupported")||Jn(c.coverage,"notObserved"));!d||p?(l="NOT OBSERVED",m=`Wait behaviour is ${J(o.waits.state)} for all ${u} executions in this period, so time blocked on a person cannot be read from it.`):(m=`${d.count} explicit ${Ke(d.count,"wait")} for ${mt(d.durationMs)}${d.openNow>0?`, ${d.openNow} open now`:""}.`,c&&c.coverage.unsupported>0&&(m+=` Waits are unsupported for ${c.coverage.unsupported} of ${u} executions.`));const h=[...i.observation];return c&&h.push({k:"WAITS",v:ps(c.state,c.coverage)}),h.push({k:"SOURCES",v:s.sources.map(v=>`${v.source} ${v.executionRecords}`).join(" · ")}),{...i,...l?{verdict:l}:{},finding:m,observation:h,evidence:[Ty(e),{...De("waiting",o.waitingNow,String),t:"recorded lifecycle"},{k:"executions",v:String(u),e:""}],command:rr("availability",t.scope),text:a}}function VA(t,e,r,n){const o=t.by??"model",s=Hr(t,`BREAKDOWN · ${o.toUpperCase()}`,e.availability,!1,r,n),i=tr({operation:"breakdown",result:e},void 0,n),a=e.availability.executionRecords;if(a===0||Ar(e.availability))return Fr(s,e.availability,i,n);const c=e.items.filter(p=>!bt(p.key,o).pseudo),u=e.items.filter(p=>bt(p.key,o).pseudo),d=[];if(o==="executor")d.push(`${Zn(c.map(p=>`${p.key} ${p.executions}`))} execution ${Ke(c.reduce((p,h)=>p+h.executions,0),"record")}.`);else if(c[0]){const p=c[0],h=ce(p.tokens);d.push(`${p.key} accounts for ${p.executions} of ${a} executions${h!==void 0?` and ${Te(h)} tokens`:""}.`)}for(const p of u)d.push(`${p.executions} ${Ke(p.executions,"execution")} ${p.executions===1?"carries":"carry"} ${YA(p.key,o)}.`);const l=cn(e.availability,o),m=[...s.observation];return l&&m.push({k:o.toUpperCase(),v:ps(l.state,l.coverage)}),m.push({k:"CAUSALITY",v:"grouped records; not a causal performance difference"}),{...s,finding:d.join(" "),observation:m,evidenceCaption:"TOKENS",evidence:e.items.map(p=>{const h=ce(p.terminalDuration),v=ce(p.tokens);return{k:bt(p.key,o).text,t:`${Te(p.executions)} ${Ke(p.executions,"execution")}${h?` · median ${wy(h.median)}`:""}`,v:v===void 0?"—":Te(v),e:J(p.tokens.state)}}),command:rr("breakdown",t.scope,o),text:i}}function HA(t,e,r,n,o){const s=Hr(t,"BREAKDOWN · MODEL · ERRORS",e.availability,!1,n,o),i=tr({operation:"breakdown",result:e},void 0,o);if(e.availability.executionRecords===0||Ar(e.availability))return Fr(s,e.availability,i,o);const a=[...e.items].sort((v,g)=>(ce(g.toolErrors)??-1)-(ce(v.toolErrors)??-1)||g.executions-v.executions),c=ce(r.summary.toolErrors),u=a.filter(v=>!bt(v.key,"model").pseudo&&ce(v.toolErrors)!==void 0),d=[],l=v=>{const g=ce(v.toolInteractions);return g===void 0?"":`, across ${Te(g)} tool interactions`};if(c===void 0)d.push(`Tool errors are ${J(r.summary.toolErrors.state)} for this period.`);else if(c===0)d.push("No tool errors were recorded.");else if(u[0]){const[v,g]=u,I=ce(v.toolErrors)??0;if(d.push(I*2>c?`Tool errors are concentrated in ${v.key}: ${Te(I)} of ${Te(c)} recorded errors${l(v)}.`:`Tool errors are spread across models: ${v.key} recorded ${Te(I)} of ${Te(c)}${l(v)}.`),g){const N=ce(g.toolInteractions);d.push(`${g.key} recorded ${Te(ce(g.toolErrors)??0)}${N===void 0?"":` across ${Te(N)}`}.`)}}const m=[...s.observation],p=e.items.filter(v=>v.toolErrors.state==="unsupported").map(v=>bt(v.key,"model").text);p.length>0&&m.push({k:"ERRORS",v:`unsupported for ${Zn(p)}`}),m.push({k:"CAUSALITY",v:"grouped records; not a causal performance difference"});const h=(v,g)=>{const I=ce(v),N=ce(g);return`${I===void 0?"—":Te(I)} / ${N===void 0?"—":Te(N)}`};return{...s,finding:d.join(" "),observation:m,evidenceCaption:"ERRORS / TOOLS",evidence:[{k:"all executions",v:h(r.summary.toolErrors,r.summary.toolInteractions),e:J(r.summary.toolErrors.state)},...a.map(v=>({k:bt(v.key,"model").text,v:h(v.toolErrors,v.toolInteractions),e:J(v.toolErrors.state)}))],command:rr("breakdown",t.scope,"model"),text:i}}function FA(t,e,r){const n=[{k:"A",w:ds(e.periodA,r),s:J(e.availabilityA.observation)},{k:"B",w:ds(e.periodB,r),s:J(e.availabilityB.observation)}],o=[...e.availabilityA.reasons.map(l=>({k:"A",v:l})),...e.availabilityB.reasons.map(l=>({k:"B",v:l})),...e.reasons.filter(l=>!l.startsWith("period A: ")&&!l.startsWith("period B: ")).map(l=>({k:"",v:l}))],s=e.dimensions.filter(l=>!l.dimension.endsWith(" mix")),i=new Set(e.dimensions.flatMap(l=>l.reasons)),c=[{k:"DIMENSIONS",v:e.dimensions.every(l=>l.eligibility===e.eligibility)&&i.size===1?`all — ${[...i][0]}`:["comparable","partially-comparable","not-comparable"].map(l=>[e.dimensions.filter(m=>m.eligibility===l).length,J(l)]).filter(([l])=>l>0).map(([l,m])=>`${l} ${m}`).join(" · ")}],u=(l,m)=>{const p=ce(m);return typeof p!="number"?"—":Kn[l]?.duration?iu(p):Te(p)},d=(l,m)=>{const p=ce(m);return typeof p!="number"?"—":Kn[l]?.duration?iu(p):Et(p)};return{request:t,title:$y(t.scope),resolution:`COMPARISON · AGAINST PREVIOUS${t.scope==="last-7d"?" 7D":""}`,periods:n,partial:e.availabilityA.observation!=="observed"||e.availabilityB.observation!=="observed",verdict:J(e.eligibility).toUpperCase(),reasons:o,observation:c,evidenceCaption:"A · B",evidence:s.map(l=>{const m=GA(t,l.dimension);return{k:Kn[l.dimension]?.label??l.dimension,t:`B ${u(l.dimension,l.periodB)} ${J(l.periodB.state)}`,v:u(l.dimension,l.periodA),e:J(l.periodA.state),comparison:{a:u(l.dimension,l.periodA),b:u(l.dimension,l.periodB),aCompact:d(l.dimension,l.periodA),bCompact:d(l.dimension,l.periodB),aEvidence:J(l.periodA.state),bEvidence:J(l.periodB.state),eligibility:J(l.eligibility),reasons:l.reasons},...m?{focus:m}:{}}}),command:rr("compare",t.scope),text:tr({operation:"compare",result:e},void 0,r)}}function Hr(t,e,r,n,o,s){const i=[J(r.observation),...n?[J(r.retention.state)]:[]].join(" · "),a=[],c=$y(t.scope);return o.view&&o.view!==c&&a.push({k:"PERIOD",v:`${c.toLowerCase()}, as asked · the view is showing ${o.view.toLowerCase()}`}),{request:t,title:c,resolution:e,window:ds(r.period,s),qualification:i,partial:r.observation!=="observed",reasons:[],observation:a}}function Fr(t,e,r,n){const o=t.request,s=rr(o.query,o.scope,o.by);if(Ar(e)){const i=e.retention.semanticFrom;return{...t,verdict:"OUTSIDE RETENTION",finding:i===null?"This period precedes semantic history.":`Semantic history starts at ${cd(i,n)}; this period precedes it.`,observation:[...t.observation,{k:"RETENTION",v:My(e,n)}],evidence:[],command:s,text:r}}return{...t,finding:"No execution records. A quiet period cannot be told from an unobserved one, so zero work is not established.",observation:[...t.observation,ya(e)],evidence:[{k:"execution records",v:"0",e:""}],command:s,text:r}}function WA(t){const{summary:e}=t,r=e.usageByModel.map(o=>{const s=ce(o.tokens);return{k:o.model,t:`${o.executions} ${Ke(o.executions,"execution")}`,v:s===void 0?"—":Et(s),e:J(o.tokens.state)}}),n=e.modelMix.filter(o=>bt(o.key,"model").pseudo);if(n.reduce((o,s)=>o+s.executions,0)===e.executionsWithoutModel)for(const o of n)r.push({k:bt(o.key,"model").text,t:`${o.executions} ${Ke(o.executions,"execution")}`,v:"",e:""});else e.executionsWithoutModel>0&&r.push({k:"model not observed",t:`${e.executionsWithoutModel} ${Ke(e.executionsWithoutModel,"execution")}`,v:"",e:""});return r}function De(t,e,r,n){const o=ce(e);return{k:t,v:o===void 0?"—":r(o),e:J(e.state),...n?{focus:n}:{}}}function Ce(t,e,r){const n=e==="breakdown"?{query:e,scope:t.scope,focus:r,by:"model"}:{query:e,scope:t.scope,focus:r};return qA(n,t)?void 0:n}function KA(t,e){switch(e){case"tokens":return Ce(t,"availability","tokens");case"waits":return Ce(t,"availability","waits");case"tool-errors":case"tool-interactions":return Ce(t,"breakdown","errors");case"outcomes":return Ce(t,"summary","lifecycle");case"bounds":return Ce(t,"summary","duration");case"model":return{query:"breakdown",scope:t.scope,by:"model"};case"executor":return{query:"breakdown",scope:t.scope,by:"executor"}}}function GA(t,e){return e==="tokens"?Ce(t,"availability","tokens"):e==="explicit wait count"?Ce(t,"availability","waits"):e==="tool interactions"||e==="tool errors"?Ce(t,"breakdown","errors"):Kn[e]?.duration||e==="peak terminal concurrency"?Ce(t,"summary","duration"):Ce(t,"summary","lifecycle")}function qA(t,e){return t.query===e.query&&t.scope===e.scope&&t.focus===e.focus&&t.by===e.by}function rr(t,e,r){const n=e==="last-7d"?" --last 7d":"";switch(t){case"summary":return`057 activity summary${n}`;case"availability":return`057 activity availability${n}`;case"breakdown":return`057 activity breakdown${n} --by ${r??"model"}`;case"compare":return`057 activity compare${n} --previous`}}function $y(t){return t==="last-7d"?"LAST 7D":"TODAY"}function cn(t,e){return t.measures.find(r=>r.dimension===e)}function $c(t){return ky[t]??t}function Ar(t){return t.retention.state==="outside-retention"}function Jn(t,e){return t.records>0&&t[e]===t.records}function By(t){return[[t.observed,"observed"],[t.inferred,"inferred"],[t.partial,"partial"],[t.notObserved,"not observed"],[t.unsupported,"unsupported"],[t.unknown,"unknown"]].filter(([e])=>e>0).map(([e,r])=>`${e} ${r}`).join(" · ")}function ps(t,e){return e.records===0?J(t):`${J(t)} · ${By(e)} / ${e.records}`}function ya(t){return{k:"CONTINUITY",v:J(t.continuity.state)}}function zA(t){const e=cn(t,"model");if(!e||e.coverage.records===0)return;const r=e.coverage,n=[r.notObserved>0?`${r.notObserved} of ${r.records} not observed`:void 0,r.unsupported>0?`${r.unsupported} of ${r.records} unsupported`:void 0,r.unknown>0?`${r.unknown} of ${r.records} unknown`:void 0].filter(o=>o!==void 0);return n.length>0?{k:"MODEL",v:n.join(" · ")}:void 0}function Ry(t){const e=t.bounds;return[e.observedEnds>0?`${e.observedEnds} observed`:void 0,e.inferredEnds>0?`${e.inferredEnds} inferred`:void 0,e.openEnds>0?`${e.openEnds} open`:void 0].filter(n=>n!==void 0).join(" · ")||"none"}function My(t,e){const r=t.retention.semanticFrom;return`${J(t.retention.state)}${r===null?"":` · from ${cd(r,e)}`}`}function _y(t){return`median ${mt(t.median)} · p90 ${mt(t.p90)} · max ${mt(t.maximum)}`}function jy(t){const e=new Set(t.map(n=>n.state));if(e.size!==1)return` (${t.map(n=>J(n.state)).join(", ")})`;const[r]=[...e];return r==="observed"?"":`, ${t.length===2?"both":"all"} ${J(r)}`}function YA(t,e){const r=bt(t,e).text.replace(`${e} `,"");return r==="not observed"?`no observed ${e}`:`a ${e} that is ${r}`}function Zn(t){return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function qr(t,e){if(t===void 0)throw new Error(`the ${e} result is missing`);return t}const cp=448,XA=384;function JA(){return ue(xn(),".057")}function ga(){const t=process.env.O57_STORE;return t&&t.length>0?t===":memory:"||tu(t)?t:$s(process.cwd(),t):ue(JA(),"events.db")}function Dy(){const t=process.env.O57_STORE;return typeof t=="string"&&t.length>0}function va(t){return[t,`${t}-wal`,`${t}-shm`]}function ZA(t){return t===":memory:"?[]:[...va(t),`${t}.display`]}function QA(t){if(t===":memory:")return;const e=vi(t);eu(e,{recursive:!0,mode:cp}),Ly(e,cp)}function lu(t){if(t===":memory:")return[];const e=[];for(const r of va(t))if(ge(r)&&!Ly(r,XA)){const n=dd(r);n!==null&&(n&63)!==0&&e.push({path:r,mode:n})}return e}function dd(t){try{return fa(t).mode&511}catch{return null}}function Ly(t,e){if(process.platform==="win32")return!1;const r=dd(t);if(r===null)return!1;if((r&~e)===0)return!0;try{return pa(t,e),!0}catch{return!1}}function Py(){if(Dy())return null;const t=$s(process.cwd(),".057","events.db");return ge(t)&&t!==ga()?t:null}const du={processDays:7,eventDays:90},eS=["machine"],up=["process"],Bc={processEvents:0,otherEvents:0,claims:0,subjects:0,retainedByDependents:0,processBefore:null,otherBefore:null},tS=["execution","session","artifact"];function Uy(t=process.env){return{processDays:lp(t.O57_RETAIN_PROCESS_DAYS,du.processDays),eventDays:lp(t.O57_RETAIN_DAYS,du.eventDays)}}function lp(t,e){if(t===void 0||t.trim()==="")return e;const r=Number(t);return Number.isFinite(r)&&r>=0?r:e}function ba(t){const e=(r,n)=>r===0?`${n} kept indefinitely`:`${n} ${r}d`;return`${e(t.processDays,"processes")}, ${e(t.eventDays,"sessions/executions")}, machines never expire`}const rS=`-- 057 local store.
12
16
  --
13
17
  -- \`events\` is the only durable truth. \`claims\` is denormalized out of events so identity
14
18
  -- resolution is one indexed read rather than a scan; it is rebuildable from events at any time.
@@ -64,59 +68,73 @@ CREATE TABLE IF NOT EXISTS claims (
64
68
  CREATE INDEX IF NOT EXISTS claims_key ON claims(key, valid_from, valid_to);
65
69
  CREATE INDEX IF NOT EXISTS claims_window ON claims(valid_to, valid_from);
66
70
  CREATE INDEX IF NOT EXISTS claims_event ON claims(event_id);
67
- `,rr=1;class gt extends Error{constructor(e,r,n){super(e),this.kind=r,this.remedy=n,this.name="StoreError"}kind;remedy}function Qo(t){const e=t?.code;if(e==="EACCES"||e==="EPERM"||e==="EROFS")return!0;const r=t instanceof Error?t.message:String(t);return/readonly|read-only|attempt to write a readonly database|unable to open database file|permission denied|SQLITE_(READONLY|PERM|CANTOPEN)/i.test(r)}function yc(t,e){const r=e instanceof Error?e.message:String(e);return new gt(`store ${t} cannot be written: ${r}`,"permission","The store itself looks intact — this is a permissions problem, not a corrupt file. Do NOT delete it. Check that you own the file and its directory and that both are writable (057 needs 0600 on the store and 0700 on its directory), or point O57_STORE at a writable path.")}function EA(t){AA(t);let e;try{e=new go(t)}catch(p){throw Qo(p)?yc(t,p):new gt(`cannot open the store at ${t}: ${p instanceof Error?p.message:String(p)}`,"unreadable","Check that the path exists and names a file 057 can open, or point O57_STORE elsewhere.")}let r;try{r=Number(e.prepare("PRAGMA user_version").get().user_version)}catch(p){throw e.close(),Qo(p)?yc(t,p):new gt(`store ${t} is not a readable database: ${p instanceof Error?p.message:String(p)}`,"unreadable","The file exists but is not a 057 store. Move it aside and 057 will start a new one; `057 reset` does that for you. Back it up first if it might be data you want.")}if(r>rr)throw e.close(),new gt(`store ${t} was written by a newer 057 (schema ${r}, this build understands ${rr})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified.");try{e.exec(xA);const p=new Set(e.prepare("PRAGMA table_info(events)").all().map(y=>String(y.name)));p.has("stratum")||e.exec("ALTER TABLE events ADD COLUMN stratum TEXT"),p.has("provenance")||e.exec("ALTER TABLE events ADD COLUMN provenance TEXT"),r!==rr&&e.exec(`PRAGMA user_version = ${rr}`)}catch(p){e.close();const y=p instanceof Error?p.message:String(p);throw Qo(p)?yc(t,p):new gt(`store ${t} could not be prepared: ${y}`,"unreadable","The file may be corrupt. Back it up, then move it aside and 057 will start a new store; `057 reset` does that for you.")}Gc(t);const n=1e3,s=new Set,o=new Set;let i=null;const a=(p,y)=>{o.add(p),i??=Date.now(),s.size<n&&s.add(y)},c=p=>py(p,a),u=e.prepare(`INSERT OR IGNORE INTO events
71
+ -- Semantic readings need claims sharing their subjects' keys, not every unrelated OS sample.
72
+ CREATE INDEX IF NOT EXISTS claims_subject_window ON claims(subject_type, valid_to, valid_from, key);
73
+ `,ur=1;class xt extends Error{constructor(e,r,n){super(e),this.kind=r,this.remedy=n,this.name="StoreError"}kind;remedy}function di(t){const e=t?.code;if(e==="EACCES"||e==="EPERM"||e==="EROFS")return!0;const r=t instanceof Error?t.message:String(t);return/readonly|read-only|attempt to write a readonly database|unable to open database file|permission denied|SQLITE_(READONLY|PERM|CANTOPEN)/i.test(r)}function Rc(t,e){const r=e instanceof Error?e.message:String(e);return new xt(`store ${t} cannot be written: ${r}`,"permission","The store itself looks intact — this is a permissions problem, not a corrupt file. Do NOT delete it. Check that you own the file and its directory and that both are writable (057 needs 0600 on the store and 0700 on its directory), or point O57_STORE at a writable path.")}function nS(t){QA(t);let e;try{e=new Bs(t)}catch(p){throw di(p)?Rc(t,p):new xt(`cannot open the store at ${t}: ${p instanceof Error?p.message:String(p)}`,"unreadable","Check that the path exists and names a file 057 can open, or point O57_STORE elsewhere.")}let r;try{r=Number(e.prepare("PRAGMA user_version").get().user_version)}catch(p){throw e.close(),di(p)?Rc(t,p):new xt(`store ${t} is not a readable database: ${p instanceof Error?p.message:String(p)}`,"unreadable","The file exists but is not a 057 store. Move it aside and 057 will start a new one; `057 reset` does that for you. Back it up first if it might be data you want.")}if(r>ur)throw e.close(),new xt(`store ${t} was written by a newer 057 (schema ${r}, this build understands ${ur})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified.");try{e.exec(rS);const p=new Set(e.prepare("PRAGMA table_info(events)").all().map(h=>String(h.name)));p.has("stratum")||e.exec("ALTER TABLE events ADD COLUMN stratum TEXT"),p.has("provenance")||e.exec("ALTER TABLE events ADD COLUMN provenance TEXT"),r!==ur&&e.exec(`PRAGMA user_version = ${ur}`)}catch(p){e.close();const h=p instanceof Error?p.message:String(p);throw di(p)?Rc(t,p):new xt(`store ${t} could not be prepared: ${h}`,"unreadable","The file may be corrupt. Back it up, then move it aside and 057 will start a new store; `057 reset` does that for you.")}lu(t);const n=1e3,o=new Set,s=new Set;let i=null;const a=(p,h)=>{s.add(p),i??=Date.now(),o.size<n&&o.add(h)},c=p=>Fy(p,a),u=e.prepare(`INSERT OR IGNORE INTO events
68
74
  (id, source_id, source_instance, occurred_at, observed_at, clock, kind,
69
75
  subject_type, subject_id, core, attrs, basis, assumption, stratum, provenance)
70
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),l=e.prepare(`INSERT INTO claims
76
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),d=e.prepare(`INSERT INTO claims
71
77
  (event_id, key, ns, subject_type, subject_id, source_id, valid_from, valid_to)
72
- VALUES (?,?,?,?,?,?,?,?)`),d=dy(e,c),m={path:t,schemaVersion:rr,append(p){let y=0,v=0;e.exec("BEGIN");try{for(const g of p){if(u.run(g.id,g.source.id,g.source.instance,g.occurredAt,g.observedAt,g.clock,g.kind,g.subject.type,g.subject.id,g.core?JSON.stringify(g.core):null,g.attrs?JSON.stringify(g.attrs):null,g.basis,g.assumption??null,g.stratum??null,g.provenance?JSON.stringify(g.provenance):null).changes===0){v++;continue}y++;for(const A of g.claims??[])l.run(g.id,ub(A),A.ns,g.subject.type,g.subject.id,g.source.id,A.validFrom,A.validTo)}e.exec("COMMIT")}catch(g){throw e.exec("ROLLBACK"),g}return{inserted:y,duplicate:v}},query:d.query,claims:d.claims,stats:d.stats,begansFor:d.begansFor,subjectEvents(p,y){return e.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(p,y).map(c)},latestFor(p){return e.prepare("SELECT MAX(occurred_at) hi FROM events WHERE source_id = ?").get(p)?.hi??null},sweep(p=qc,y=Date.now()){const v=p.processDays>0?y-p.processDays*864e5:null,g=p.eventDays>0?y-p.eventDays*864e5:null;if(v===null&&g===null)return{...mc};const C=ee=>SA.includes(ee)?null:Pf.includes(ee)?v:g,A=e.prepare(`SELECT subject_type t, subject_id i, MAX(occurred_at) last
73
- FROM events GROUP BY subject_type, subject_id`).all().map(ee=>{const he=ee;return{type:String(he.t),id:String(he.i),last:Number(he.last)}}),I=(ee,he)=>`${ee}:${he}`,B=new Set,k=new Map;for(const ee of A){const he=C(ee.type);he===null||ee.last>=he?B.add(I(ee.type,ee.id)):k.set(I(ee.type,ee.id),{type:ee.type,id:ee.id})}if(k.size===0)return{...mc,processBefore:v,otherBefore:g};const T=[...kA],S=e.prepare(`SELECT DISTINCT core FROM events
74
- WHERE subject_type = ? AND subject_id = ? AND core IS NOT NULL`),E=new Set(T);let R=[...B].filter(ee=>E.has(ee.slice(0,ee.indexOf(":"))));const j=new Set(R);let M=0;for(let ee=0;ee<4&&R.length>0;ee++){const he=[];for(const $e of R){const Me=$e.indexOf(":");for(const Qt of S.all($e.slice(0,Me),$e.slice(Me+1))){const pe=ei(Qt.core);if(pe)for(const[Z,yt]of[["sessionId","session"],["parentId","session"],["parentId","execution"]]){const jo=pe[Z];if(typeof jo!="string")continue;const me=I(yt,jo);k.has(me)&&(k.delete(me),B.add(me),M++,!j.has(me)&&E.has(yt)&&(j.add(me),he.push(me)))}}}R=he}if(k.size===0)return{...mc,retainedByDependents:M,processBefore:v,otherBefore:g};const J=e.prepare(`DELETE FROM claims WHERE event_id IN
75
- (SELECT id FROM events WHERE subject_type = ? AND subject_id = ?)`),le=e.prepare("DELETE FROM events WHERE subject_type = ? AND subject_id = ?");let re=0,F=0,W=0;e.exec("BEGIN");try{for(const{type:ee,id:he}of k.values()){W+=Number(J.run(ee,he).changes);const $e=Number(le.run(ee,he).changes);Pf.includes(ee)?re+=$e:F+=$e}e.exec("COMMIT")}catch(ee){throw e.exec("ROLLBACK"),ee}return re+F>0&&m.checkpoint(),{processEvents:re,otherEvents:F,claims:W,subjects:k.size,retainedByDependents:M,processBefore:v,otherBefore:g}},checkpoint(){try{e.exec("PRAGMA wal_checkpoint(TRUNCATE)")}catch{}},sizeBytes:()=>fy(t),health(){const p=s.size;return p===0?{ok:!0,malformedRows:0,columns:[],since:null}:{ok:!1,malformedRows:p,columns:[...o].sort(),since:i,remedy:`${p} stored row(s) could not be read as JSON and lost their ${[...o].sort().join("/")} channel. Everything else is being used normally and nothing has been deleted. Run \`057 compact\` to rewrite the store; if the count keeps growing, back the store up and run \`057 reset\` to start a new one.`}},compact(){e.exec("VACUUM"),m.checkpoint(),Gc(t)},close(){m.checkpoint(),e.close()}};return m}function aa(t){if(t===":memory:"||!fe(t))throw new gt(`no 057 store exists at ${t}`,"unreadable","Nothing has been observed there yet. Run 057, or open 057.app, to start observing; reading never creates a store.");let e,r;try{e=new go(t,{readOnly:!0})}catch(s){throw Uf(t,s)}try{e.exec("PRAGMA query_only = ON"),r=Number(e.prepare("PRAGMA user_version").get().user_version)}catch(s){throw e.close(),Uf(t,s)}if(r!==rr)throw e.close(),r>rr?new gt(`store ${t} was written by a newer 057 (schema ${r}, this build understands ${rr})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified."):new gt(`store ${t} has not been prepared by this 057 yet (schema ${r})`,"unreadable","Start 057 or 057.app once so it can prepare the store, then query again. The store was not modified.");const n=dy(e,s=>py(s));return{path:t,schemaVersion:rr,...n,sizeBytes:()=>fy(t),close(){e.close()}}}function Uf(t,e){const r=e instanceof Error?e.message:String(e);return Qo(e)?new gt(`store ${t} cannot be read: ${r}`,"permission","The store itself looks intact — this is a permissions problem, not a corrupt file. Do NOT delete it. Check that you own the file and its directory."):new gt(`store ${t} is not a readable database: ${r}`,"unreadable","The store was not modified. Check that O57_STORE names a 057 store.")}function dy(t,e){const r=t.prepare("SELECT * FROM events WHERE occurred_at >= ? AND occurred_at <= ? ORDER BY occurred_at, id"),n=new Map,s=t.prepare(`SELECT key, ns, subject_type, subject_id, source_id, valid_from, valid_to
76
- FROM claims WHERE valid_from <= ? AND valid_to >= ?`);return{query(o,i,a){if(!a||a.length===0)return r.all(o,i).map(e);const c=[...a].sort().join(",");let u=n.get(c);if(!u){const l=a.map(()=>"?").join(",");u=t.prepare(`SELECT * FROM events
77
- WHERE occurred_at >= ? AND occurred_at <= ? AND subject_type IN (${l})
78
- ORDER BY occurred_at, id`),n.set(c,u)}return u.all(o,i,...a).map(e)},claims(o,i){return s.all(i,o).map(a=>{const c=a;return{key:String(c.key),subjectType:c.subject_type,subjectId:String(c.subject_id),sourceId:String(c.source_id),validFrom:Number(c.valid_from),validTo:Number(c.valid_to)}})},stats(){const o=Number(t.prepare("SELECT COUNT(*) c FROM events").get().c),i=Number(t.prepare("SELECT COUNT(*) c FROM claims").get().c),a=t.prepare("SELECT MIN(occurred_at) lo, MAX(occurred_at) hi FROM events").get(),c=t.prepare(`SELECT source_id s, COUNT(*) c, MIN(occurred_at) lo, MAX(occurred_at) hi
79
- FROM events GROUP BY source_id ORDER BY s`).all().map(u=>{const l=u;return{source:String(l.s),events:Number(l.c),first:Number(l.lo),last:Number(l.hi)}});return{events:o,claims:i,bySource:c,earliest:a.lo,latest:a.hi}},begansFor(o){const i=[],a=t.prepare(`SELECT * FROM events
78
+ VALUES (?,?,?,?,?,?,?,?)`),l=Vy(e,c),m={path:t,schemaVersion:ur,append(p){let h=0,v=0;e.exec("BEGIN");try{for(const g of p){if(u.run(g.id,g.source.id,g.source.instance,g.occurredAt,g.observedAt,g.clock,g.kind,g.subject.type,g.subject.id,g.core?JSON.stringify(g.core):null,g.attrs?JSON.stringify(g.attrs):null,g.basis,g.assumption??null,g.stratum??null,g.provenance?JSON.stringify(g.provenance):null).changes===0){v++;continue}h++;for(const N of g.claims??[])d.run(g.id,Vb(N),N.ns,g.subject.type,g.subject.id,g.source.id,N.validFrom,N.validTo)}e.exec("COMMIT")}catch(g){throw e.exec("ROLLBACK"),g}return{inserted:h,duplicate:v}},query:l.query,claims:l.claims,stats:l.stats,begansFor:l.begansFor,executionCarry:l.executionCarry,subjectEvents(p,h){return e.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(p,h).map(c)},latestFor(p){return e.prepare("SELECT MAX(occurred_at) hi FROM events WHERE source_id = ?").get(p)?.hi??null},sweep(p=du,h=Date.now()){const v=p.processDays>0?h-p.processDays*864e5:null,g=p.eventDays>0?h-p.eventDays*864e5:null;if(v===null&&g===null)return{...Bc};const I=z=>eS.includes(z)?null:up.includes(z)?v:g,N=e.prepare(`SELECT subject_type t, subject_id i, MAX(occurred_at) last
79
+ FROM events GROUP BY subject_type, subject_id`).all().map(z=>{const se=z;return{type:String(se.t),id:String(se.i),last:Number(se.last)}}),S=(z,se)=>`${z}:${se}`,T=new Set,x=new Map;for(const z of N){const se=I(z.type);se===null||z.last>=se?T.add(S(z.type,z.id)):x.set(S(z.type,z.id),{type:z.type,id:z.id})}if(x.size===0)return{...Bc,processBefore:v,otherBefore:g};const D=[...tS],w=e.prepare(`SELECT DISTINCT core FROM events
80
+ WHERE subject_type = ? AND subject_id = ? AND core IS NOT NULL`),$=new Set(D);let E=[...T].filter(z=>$.has(z.slice(0,z.indexOf(":"))));const B=new Set(E);let C=0;for(let z=0;z<4&&E.length>0;z++){const se=[];for(const ve of E){const Ae=ve.indexOf(":");for(const _e of w.all(ve.slice(0,Ae),ve.slice(Ae+1))){const Ie=fi(_e.core);if(Ie)for(const[q,qe]of[["sessionId","session"],["parentId","session"],["parentId","execution"]]){const rt=Ie[q];if(typeof rt!="string")continue;const A=S(qe,rt);x.has(A)&&(x.delete(A),T.add(A),C++,!B.has(A)&&$.has(qe)&&(B.add(A),se.push(A)))}}}E=se}if(x.size===0)return{...Bc,retainedByDependents:C,processBefore:v,otherBefore:g};const P=e.prepare(`DELETE FROM claims WHERE event_id IN
81
+ (SELECT id FROM events WHERE subject_type = ? AND subject_id = ?)`),L=e.prepare("DELETE FROM events WHERE subject_type = ? AND subject_id = ?");let te=0,U=0,V=0;e.exec("BEGIN");try{for(const{type:z,id:se}of x.values()){V+=Number(P.run(z,se).changes);const ve=Number(L.run(z,se).changes);up.includes(z)?te+=ve:U+=ve}e.exec("COMMIT")}catch(z){throw e.exec("ROLLBACK"),z}return te+U>0&&m.checkpoint(),{processEvents:te,otherEvents:U,claims:V,subjects:x.size,retainedByDependents:C,processBefore:v,otherBefore:g}},checkpoint(){try{e.exec("PRAGMA wal_checkpoint(TRUNCATE)")}catch{}},sizeBytes:()=>Hy(t),health(){const p=o.size;return p===0?{ok:!0,malformedRows:0,columns:[],since:null}:{ok:!1,malformedRows:p,columns:[...s].sort(),since:i,remedy:`${p} stored row(s) could not be read as JSON and lost their ${[...s].sort().join("/")} channel. Everything else is being used normally and nothing has been deleted. Run \`057 compact\` to rewrite the store; if the count keeps growing, back the store up and run \`057 reset\` to start a new one.`}},compact(){e.exec("VACUUM"),m.checkpoint(),lu(t)},close(){m.checkpoint(),e.close()}};return m}function wa(t){if(t===":memory:"||!ge(t))throw new xt(`no 057 store exists at ${t}`,"unreadable","Nothing has been observed there yet. Run 057, or open 057.app, to start observing; reading never creates a store.");let e,r;try{e=new Bs(t,{readOnly:!0})}catch(o){throw dp(t,o)}try{e.exec("PRAGMA query_only = ON"),r=Number(e.prepare("PRAGMA user_version").get().user_version)}catch(o){throw e.close(),dp(t,o)}if(r!==ur)throw e.close(),r>ur?new xt(`store ${t} was written by a newer 057 (schema ${r}, this build understands ${ur})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified."):new xt(`store ${t} has not been prepared by this 057 yet (schema ${r})`,"unreadable","Start 057 or 057.app once so it can prepare the store, then query again. The store was not modified.");const n=Vy(e,o=>Fy(o));return{path:t,schemaVersion:ur,...n,sizeBytes:()=>Hy(t),close(){e.close()}}}function dp(t,e){const r=e instanceof Error?e.message:String(e);return di(e)?new xt(`store ${t} cannot be read: ${r}`,"permission","The store itself looks intact — this is a permissions problem, not a corrupt file. Do NOT delete it. Check that you own the file and its directory."):new xt(`store ${t} is not a readable database: ${r}`,"unreadable","The store was not modified. Check that O57_STORE names a 057 store.")}function Vy(t,e){const r=t.prepare("SELECT * FROM events WHERE occurred_at >= ? AND occurred_at <= ? ORDER BY occurred_at, id"),n=new Map,o=t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'events_subject_time'").get()?"INDEXED BY events_subject_time":"",s=t.prepare(`SELECT key, ns, subject_type, subject_id, source_id, valid_from, valid_to
82
+ FROM claims WHERE valid_from <= ? AND valid_to >= ?`),i=new Map,a=t.prepare(`
83
+ SELECT subject_id FROM events WHERE subject_type = 'execution' AND occurred_at >= ? AND occurred_at < ?
84
+ UNION
85
+ SELECT b.subject_id FROM events b WHERE b.subject_type = 'execution' AND b.kind = 'began' AND b.occurred_at < ?
86
+ AND (SELECT z.id FROM events z WHERE z.subject_type = 'execution' AND z.subject_id = b.subject_id
87
+ AND z.kind = 'ended' AND z.occurred_at < ? AND (z.basis = 'measured' OR NOT EXISTS (
88
+ SELECT 1 FROM events n WHERE n.subject_type = 'execution' AND n.subject_id = z.subject_id
89
+ AND n.occurred_at > z.occurred_at AND n.occurred_at < ? AND n.kind IN ('progressed','blocked','resumed')))
90
+ ORDER BY z.occurred_at DESC LIMIT 1) IS NULL`),c=t.prepare(`SELECT * FROM events
91
+ WHERE subject_type = 'execution' AND subject_id = ? AND occurred_at < ? ORDER BY occurred_at, id`);return{executionCarry(u,d){const l=[];for(const m of a.all(u,d,u,u,u)){const p=String(m.subject_id);l.push(...c.all(p,u).map(e))}return l.sort((m,p)=>m.occurredAt-p.occurredAt||m.id.localeCompare(p.id))},subjectEvents(u,d){return t.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(u,d).map(e)},query(u,d,l){if(!l||l.length===0)return r.all(u,d).map(e);const m=[...l].sort().join(",");let p=n.get(m);if(!p){const h=l.map(()=>"?").join(",");p=t.prepare(`SELECT * FROM events ${o}
92
+ WHERE occurred_at >= ? AND occurred_at <= ? AND subject_type IN (${h})
93
+ ORDER BY occurred_at, id`),n.set(m,p)}return p.all(u,d,...l).map(e)},claims(u,d,l){let m;if(l?.length){const p=[...l].sort().join(",");let h=i.get(p);if(!h){const v=l.map(()=>"?").join(",");h=t.prepare(`SELECT key, ns, subject_type, subject_id, source_id, valid_from, valid_to
94
+ FROM claims INDEXED BY claims_key WHERE key IN (
95
+ SELECT key FROM claims WHERE subject_type IN (${v}) AND valid_from <= ? AND valid_to >= ?
96
+ ) AND valid_from <= ? AND valid_to >= ?`),i.set(p,h)}m=h.all(...l,d,u,d,u)}else m=s.all(d,u);return m.map(p=>{const h=p;return{key:String(h.key),subjectType:h.subject_type,subjectId:String(h.subject_id),sourceId:String(h.source_id),validFrom:Number(h.valid_from),validTo:Number(h.valid_to)}})},stats(){const u=Number(t.prepare("SELECT COUNT(*) c FROM events").get().c),d=Number(t.prepare("SELECT COUNT(*) c FROM claims").get().c),l=t.prepare("SELECT MIN(occurred_at) lo, MAX(occurred_at) hi FROM events").get(),m=t.prepare(`SELECT source_id s, COUNT(*) c, MIN(occurred_at) lo, MAX(occurred_at) hi
97
+ FROM events GROUP BY source_id ORDER BY s`).all().map(p=>{const h=p;return{source:String(h.s),events:Number(h.c),first:Number(h.lo),last:Number(h.hi)}});return{events:u,claims:d,bySource:m,earliest:l.lo,latest:l.hi}},begansFor(u){const d=[],l=t.prepare(`SELECT * FROM events
80
98
  WHERE kind = 'began' AND subject_type = ? AND subject_id = ?
81
- ORDER BY occurred_at, id`);for(const c of o){const u=c.indexOf(":");if(u<0)continue;const l=a.all(c.slice(0,u),c.slice(u+1));for(const d of l)i.push(e(d))}return i}}}function fy(t){const[e,r,n]=oa(t).map(IA);return{db:e,wal:r,shm:n,total:e+r+n}}function IA(t){try{return Qi(t).size}catch{return 0}}function ei(t,e,r){if(t!=null)try{const n=JSON.parse(String(t));if(n&&typeof n=="object")return n;e&&r?.(e);return}catch{e&&r?.(e);return}}function py(t,e){const r=t,n=e?s=>e(s,String(r.id)):void 0;return{id:String(r.id),source:{id:String(r.source_id),instance:String(r.source_instance)},occurredAt:Number(r.occurred_at),observedAt:Number(r.observed_at),clock:r.clock,kind:r.kind,subject:{type:r.subject_type,id:String(r.subject_id)},core:ei(r.core,"core",n),attrs:ei(r.attrs,"attrs",n),basis:r.basis,assumption:r.assumption?String(r.assumption):void 0,stratum:r.stratum?r.stratum:void 0,provenance:ei(r.provenance,"provenance",n)}}const Vf={tokens:"unknown",requests:"unknown",toolInteractions:"unknown",toolErrors:"unknown",retries:"unknown",waits:"unknown",model:"unknown",context:"unknown",outcome:"unknown"};function CA(t){const e=new Map;for(const o of t.declarations)o.kind==="began"&&e.set(`${o.subject.type}:${o.subject.id}`,o);const r=[...t.state.executions.values()].map(o=>OA(o,t,e)).sort((o,i)=>o.start.at-i.start.at||o.ref.localeCompare(i.ref)),n=new Set(r.map(o=>o.ref)),s=[...t.state.sessions.values()].map(o=>({ref:Sr("session",o.id),executionRefs:o.executionIds.map(i=>Sr("execution",i)).filter(i=>n.has(i)).sort(),spawnedBy:o.parentId?et({ref:Sr("session",o.parentId)}):Jr("no parent session was reported")})).filter(o=>o.executionRefs.length>0).sort((o,i)=>o.ref.localeCompare(i.ref));return{experimental:!0,window:{from:t.from,to:t.to},executions:r,sessions:s,summary:_A(r,s,t.from,t.to)}}function OA(t,e,r){const n=r.get(`execution:${t.id}`),s=n?.source.id,o=s?e.capabilities.get(s)??Vf:Vf,i=e.state.sessions.get(t.sessionId),a=e.state.machines.get(t.machineId),c=t.status==="completed"||t.status==="failed",u=TA(n?.occurredAt??t.startedAt,n?.basis??t.startBasis),l=e.relationships.filter(y=>y.kind==="ran-as"&&(y.from.type==="execution"&&y.from.id===t.id&&y.to.type==="process"||y.to.type==="execution"&&y.to.id===t.id&&y.from.type==="process")).map(y=>{const v=y.from.type==="process"?y.from:y.to;return{kind:"ran-as",target:{type:"process",ref:Sr("process",v.id)},evidence:NA(y.basis),...y.basis==="inferred"?{qualification:"resolved from overlapping identity claims"}:{}}}).sort((y,v)=>y.target.ref.localeCompare(v.target.ref)),d=i?.context,m=t.model??i?.model,p={current:t.status==="waiting",...t.waitReason?{reason:t.waitReason}:{},count:t.waits.length+(t.waitingSince===void 0?0:1),durationMs:t.waitingMs+(t.waitingSince===void 0?0:Math.max(0,e.to-t.waitingSince))};return{ref:Sr("execution",t.id),observer:s??"unknown-observer",sessionRef:Sr("session",t.sessionId),machine:t.machineId?et({ref:Sr("machine",t.machineId),...a?{kind:a.kind}:{}}):Jr("no machine was reported"),context:d?zc(o.context,{ref:Sr("context",d)},"context"):ti(o.context,"context"),executor:t.executor&&t.executor!=="unknown"?et(t.executor):Jr("no executor was reported"),model:m?zc(o.model,m,"model"):ti(o.model,"model"),start:u,end:t.endedAt===void 0?lr(e.to,"the execution is open; query time is an elapsed wall bound, not a terminal end"):t.endBasis==="inferred"?Zs(t.endedAt,"the terminal bound was inferred by its observer"):et(t.endedAt),lifecycle:BA(t),outcome:$A(t,o.outcome),measures:{tokens:{input:Ar(t,z.tokensInput,o.tokens,c,!1,"token input"),output:Ar(t,z.tokensOutput,o.tokens,c,!1,"token output"),cacheRead:Ar(t,z.tokensCacheRead,o.tokens,c,!1,"cache-read tokens"),reasoning:Ar(t,z.tokensReasoning,o.tokens,c,!1,"reasoning tokens"),total:hy(ur(t.measures),o.tokens,c,!1,"token total")},requests:Ar(t,z.steps,o.requests,c,!0,"requests"),toolInteractions:Ar(t,z.interactions,o.toolInteractions,c,!0,"tool interactions"),toolErrors:Ar(t,z.errors,o.toolErrors,c,!0,"tool errors"),retries:Ar(t,z.retries,o.retries,c,!0,"retries")},wait:RA(p,o.waits,c),failure:t.status==="failed"?et("execution-failed"):c?o.outcome==="supported"?et("none"):ti(o.outcome,"failure state"):Mt("the execution is not terminal"),depth:t.depth,relationships:l}}function Sr(t,e){const r=Qn("sha256").update(`057-activity\0${t}\0${e}`).digest("hex").slice(0,16);return`${t}_${r}`}function NA(t){return t==="inferred"?"inferred":"observed"}function TA(t,e){return e==="inferred"?{at:t,evidence:"inferred",qualification:"the observer inferred this temporal bound"}:e===void 0?{at:t,evidence:"inferred",qualification:"a legacy record did not declare its timing basis"}:{at:t,evidence:"observed"}}function BA(t){return t.status==="waiting"?{state:"waiting",evidence:"observed"}:t.status==="running"?{state:"running",evidence:"observed"}:t.status==="idle"?{state:"idle",evidence:"inferred",qualification:"no activity was observed for the idle threshold"}:{state:"terminal",evidence:t.endBasis==="inferred"?"inferred":"observed",...t.endBasis==="inferred"?{qualification:"the observer inferred the terminal bound"}:{}}}function $A(t,e){if(t.status!=="completed"&&t.status!=="failed")return Mt("the execution is not terminal");const r=t.outcome==="error"?"failed":t.outcome==="interrupted"?"interrupted":t.outcome==="completed"?"completed":void 0;return r?t.endBasis==="inferred"?Zs(r,"the terminal outcome follows an inferred terminal bound"):zc(e,r,"outcome"):ti(e,"outcome")}function Ar(t,e,r,n,s,o){return hy(Ot(t.measures,e),r,n,s,o)}function hy(t,e,r,n,s){return e==="unsupported"?mn(`this observer does not report ${s}`):e==="unknown"?Mt(`coverage for ${s} is not declared`):e==="partial"?lr(t,`this observer reports ${s} only partially`):r?t!==void 0?et(t):n?et(0):Jr(`${s} was not present in this execution`):lr(t,`${s} may still increase while the execution is active`)}function RA(t,e,r){return e==="unsupported"?mn("this observer does not report explicit waits"):e==="unknown"?Mt("wait coverage is not declared"):e==="partial"?lr(t,"this observer reports explicit waits only partially"):!r||t.current?lr(t,"an explicit wait may still be open"):et(t)}function zc(t,e,r){return t==="supported"?et(e):t==="partial"?lr(e,`this observer reports ${r} only partially`):t==="unsupported"?mn(`this observer does not report ${r}`):Mt(`coverage for ${r} is not declared`)}function ti(t,e){return t==="supported"?Jr(`${e} was not present in this execution`):t==="partial"?lr(void 0,`this observer reports ${e} only partially`):t==="unsupported"?mn(`this observer does not report ${e}`):Mt(`coverage for ${e} is not declared`)}function et(t){return{state:"observed",value:t}}function Zs(t,e){return{state:"inferred",value:t,qualification:e}}function lr(t,e){return t===void 0?{state:"partial",qualification:e}:{state:"partial",value:t,qualification:e}}function mn(t){return{state:"unsupported",qualification:t}}function Jr(t){return{state:"not-observed",qualification:t}}function Mt(t){return{state:"unknown",qualification:t}}function _A(t,e,r,n){const s=t.map(d=>({start:Math.max(r,d.start.at),end:Math.min(n,ut(d.end)??n),inferred:d.start.evidence==="inferred"||d.end.state==="inferred",partial:d.end.state!=="observed"&&d.end.state!=="inferred"})),o=Vn(s.map(d=>d.partial?"partial":d.inferred?"inferred":"observed")),i=Wf(s),a=Kf(s),c=t.filter(d=>d.lifecycle.state==="terminal"),u=c.flatMap(d=>{const m=ut(d.end);return m===void 0?[]:[{start:Math.max(r,d.start.at),end:Math.min(n,m),inferred:d.start.evidence==="inferred"||d.end.state==="inferred"}]}),l=Vn(c.map(d=>ut(d.end)===void 0?"unknown":d.start.evidence==="inferred"||d.end.state==="inferred"?"inferred":"observed"));return{executions:t.length,sessions:e.length,openExecutions:t.length-c.length,terminalExecutions:c.length,runningNow:t.filter(d=>d.lifecycle.state==="running").length,waitingNow:On(t.map(MA)),idleNow:t.filter(d=>d.lifecycle.state==="idle").length,completed:bc(c,"completed"),failed:bc(c,"failed"),interrupted:bc(c,"interrupted"),executionWallIntervalMs:nr(i,o),peakExecutionConcurrency:nr(a,o),executionDuration:gc(t.map(d=>{const m=ut(d.end)??n,p=Math.max(0,m-d.start.at);return d.end.state!=="observed"&&d.end.state!=="inferred"?lr(p,"elapsed wall duration for an open execution"):d.start.evidence==="inferred"||d.end.state==="inferred"?Zs(p,"one or more execution bounds were inferred"):et(p)})),terminalExecutionDuration:gc(c.map(d=>{const m=ut(d.end);if(m===void 0)return Mt("the terminal execution has no usable end bound");const p=Math.max(0,m-d.start.at);return d.start.evidence==="inferred"||d.end.state==="inferred"?Zs(p,"one or more execution bounds were inferred"):et(p)})),terminalExecutionIntervalMs:nr(Wf(u),l),overlappingTerminalIntervalMs:nr(PA(u),l),peakTerminalConcurrency:nr(Kf(u),l),sessionExecutionCount:gc(e.map(d=>et(d.executionRefs.length))),tokens:On(t.map(d=>d.measures.tokens.total)),toolInteractions:On(t.map(d=>d.measures.toolInteractions)),toolErrors:On(t.map(d=>d.measures.toolErrors)),waits:jA(t.map(d=>d.wait)),usageByModel:DA(t),executionsWithoutModel:t.filter(d=>ut(d.model)===void 0).length,modelMix:Ff(t,d=>Hf(d.model)),executorMix:Ff(t,d=>Hf(d.executor))}}function ut(t){return"value"in t?t.value:void 0}function Hf(t){return ut(t)??`[${t.state}]`}function Vn(t){const e={records:t.length,observed:0,inferred:0,partial:0,unsupported:0,notObserved:0,unknown:0};for(const r of t)r==="not-observed"?e.notObserved++:e[r]++;return e}function nr(t,e){return e.partial+e.unsupported+e.notObserved+e.unknown>0?{state:"partial",value:t,qualification:"coverage is incomplete",coverage:e}:e.inferred>0?{state:"inferred",value:t,qualification:"one or more bounds were inferred",coverage:e}:{state:"observed",value:t,coverage:e}}function On(t){const e=Vn(t.map(s=>s.state));let r=0,n=0;for(const s of t){const o=ut(s);o!==void 0&&(r+=o,n++)}return n>0?nr(r,e):e.records>0&&e.unsupported===e.records?{...mn("no observer supports this measure"),coverage:e}:e.records>0&&e.notObserved===e.records?{...Jr("no value was observed"),coverage:e}:{...Mt("no usable value was observed"),coverage:e}}function gc(t){const e=Vn(t.map(n=>n.state)),r=t.map(ut).filter(n=>n!==void 0).sort((n,s)=>n-s);return r.length===0?{...Mt("no usable duration samples were observed"),coverage:e}:nr({samples:r.length,minimum:r[0],median:vc(r,.5),p75:vc(r,.75),p90:vc(r,.9),maximum:r[r.length-1]},e)}function vc(t,e){const r=(t.length-1)*e,n=Math.floor(r),s=Math.ceil(r);return n===s?t[n]:t[n]+(t[s]-t[n])*(r-n)}function MA(t){const e=ut(t.wait);return my(t.wait,e?.current?1:0)}function bc(t,e){return t.length===0?nr(0,Vn([])):On(t.map(r=>{const n=ut(r.outcome);return my(r.outcome,n===e?1:0)}))}function my(t,e){switch(t.state){case"observed":return et(e);case"inferred":return Zs(e,t.qualification);case"partial":return lr("value"in t?e:void 0,t.qualification);case"unsupported":return mn(t.qualification);case"not-observed":return Jr(t.qualification);case"unknown":return Mt(t.qualification)}}function jA(t){const e=Vn(t.map(s=>s.state));let r=0;const n={count:0,durationMs:0,openNow:0};for(const s of t){const o=ut(s);o&&(r++,n.count+=o.count,n.durationMs+=o.durationMs,o.current&&n.openNow++)}return r>0?nr(n,e):e.unsupported===e.records?{...mn("no observer reports explicit waits"),coverage:e}:{...Mt("no usable wait value was observed"),coverage:e}}function DA(t){const e=new Map;for(const r of t){const n=ut(r.model);if(!n)continue;const s=e.get(n)??[];s.push(r.measures.tokens.total),e.set(n,s)}return[...e.entries()].map(([r,n])=>({model:r,executions:n.length,tokens:On(n)})).sort((r,n)=>n.executions-r.executions||r.model.localeCompare(n.model))}function Ff(t,e){const r=new Map;for(const n of t){const s=e(n);r.set(s,(r.get(s)??0)+1)}return[...r.entries()].map(([n,s])=>({key:n,executions:s})).sort((n,s)=>s.executions-n.executions||n.key.localeCompare(s.key))}function Wf(t){const e=t.filter(o=>o.end>o.start).map(o=>({start:o.start,end:o.end})).sort((o,i)=>o.start-i.start||o.end-i.end);let r=0,n,s=0;for(const o of e)n===void 0?(n=o.start,s=o.end):o.start<=s?s=Math.max(s,o.end):(r+=s-n,n=o.start,s=o.end);return r+(n===void 0?0:s-n)}function Kf(t){const e=[];for(const o of t)o.end<=o.start||e.push({at:o.start,delta:1},{at:o.end,delta:-1});e.sort((o,i)=>o.at-i.at||o.delta-i.delta);let r=0,n=0,s=null;for(const o of e)r+=o.delta,r>n&&(n=r,s=o.at);return{peak:n,at:s}}function PA(t){const e=[];for(const o of t)o.end<=o.start||e.push({at:o.start,delta:1},{at:o.end,delta:-1});e.sort((o,i)=>o.at-i.at||o.delta-i.delta);let r=0,n,s=0;for(const o of e)n!==void 0&&r>=2&&(s+=o.at-n),r+=o.delta,n=o.at;return s}function Qs(t,e){const r=t.window,n=vt(e.continuity),s=e.continuity.state==="observed"&&n!==void 0&&n.from<=r.from&&n.to>=r.to,o=e.retention.state==="within-retention"||e.retention.state==="retained-indefinitely",i=t.executions.length,a=[];let c,u;o?s?(c="observed",u="comparable"):i>0?(c="partially-observed",u="partially-comparable",a.push("execution records are present, but historical observation continuity is unknown")):(c="unknown",u="not-comparable",a.push("zero execution records cannot distinguish a quiet period from an unobserved period")):(c="not-sufficiently-observed",u="not-comparable",a.push("the requested period is not wholly inside semantic retention"));const l=t.executions.map(g=>g.start.at),d=t.executions.map(g=>vt(g.end)??g.start.at),m=i>0?or({from:Math.min(...l),to:Math.max(...d)}):cr("no execution records establish an observed span"),p=new Map;for(const g of t.executions){const C=p.get(g.observer)??[];C.push(g),p.set(g.observer,C)}const y=[...p.entries()].map(([g,C])=>({source:g,executionRecords:C.length,firstExecutionAt:Math.min(...C.map(A=>A.start.at)),lastExecutionAt:Math.max(...C.map(A=>A.start.at)),capabilities:e.capabilities.get(g)??qA()})).sort((g,C)=>C.executionRecords-g.executionRecords||g.source.localeCompare(C.source)),v=[ps("tokens",t.summary.tokens),ps("tool-interactions",t.summary.toolInteractions),ps("tool-errors",t.summary.toolErrors),ps("waits",t.summary.waits),wc("outcomes",t.executions.map(g=>g.outcome)),ps("bounds",GA(t.executions)),wc("model",t.executions.map(g=>g.model)),wc("executor",t.executions.map(g=>g.executor))];return{experimental:!0,period:r,observation:c,recordPresence:i>0?"present":"none",executionRecords:i,sessionRecords:t.sessions.length,continuity:e.continuity,observationGaps:s?or([]):cr("historical observation gaps are not retained"),unprojectedSourceWork:cr("observers do not currently retain counts for source work omitted before a timed execution could be projected"),retention:e.retention,observedSpan:m,sources:y,measures:v,bounds:{observedStarts:t.executions.filter(g=>g.start.evidence==="observed").length,inferredStarts:t.executions.filter(g=>g.start.evidence==="inferred").length,observedEnds:t.executions.filter(g=>g.end.state==="observed").length,inferredEnds:t.executions.filter(g=>g.end.state==="inferred").length,openEnds:t.executions.filter(g=>g.end.state!=="observed"&&g.end.state!=="inferred").length},comparisonReadiness:u,reasons:a}}function LA(t,e){const r=Qs(t,e),n=r.comparisonReadiness==="not-comparable"?UA(t.summary):t.summary;return{experimental:!0,period:t.window,availability:r,summary:n}}function UA(t){const e=r=>({state:"unknown",qualification:"the period was not sufficiently observed",coverage:r.coverage});return{...t,waitingNow:e(t.waitingNow),completed:e(t.completed),failed:e(t.failed),interrupted:e(t.interrupted),executionWallIntervalMs:e(t.executionWallIntervalMs),peakExecutionConcurrency:e(t.peakExecutionConcurrency),executionDuration:e(t.executionDuration),terminalExecutionDuration:e(t.terminalExecutionDuration),terminalExecutionIntervalMs:e(t.terminalExecutionIntervalMs),overlappingTerminalIntervalMs:e(t.overlappingTerminalIntervalMs),peakTerminalConcurrency:e(t.peakTerminalConcurrency),sessionExecutionCount:e(t.sessionExecutionCount),tokens:e(t.tokens),toolInteractions:e(t.toolInteractions),toolErrors:e(t.toolErrors),waits:e(t.waits),usageByModel:t.usageByModel.map(r=>({...r,tokens:e(r.tokens)}))}}function VA(t,e,r){const n=new Map;for(const o of t.executions){const i=FA(o,r),a=n.get(i)??[];a.push(o),n.set(i,a)}const s=[...n.entries()].map(([o,i])=>WA(o,i)).sort((o,i)=>i.executions-o.executions||o.key.localeCompare(i.key));return{experimental:!0,period:t.window,dimension:r,availability:Qs(t,e),items:s,qualification:r==="model"||r==="executor"?"Observed differences describe grouped records; they do not establish causal performance differences.":"Breakdown counts only privacy-reduced execution records present in this period."}}function HA(t,e,r,n){const s=Qs(t,e),o=Qs(r,n),i=KA(s.comparisonReadiness,o.comparisonReadiness),a=t.window.to-t.window.from===r.window.to-r.window.from,c=a?i:"not-comparable",u=[...s.reasons.map(d=>`period A: ${d}`),...o.reasons.map(d=>`period B: ${d}`),...a?[]:["the requested periods do not have equal duration"]],l=[ys("execution records",Ho(t.executions.length,s),Ho(r.executions.length,o),c),ys("session records",Ho(t.sessions.length,s),Ho(r.sessions.length,o),c),Et("median terminal execution duration",qf(t.summary.terminalExecutionDuration),qf(r.summary.terminalExecutionDuration),c,s,o),Et("terminal execution interval union",t.summary.terminalExecutionIntervalMs,r.summary.terminalExecutionIntervalMs,c,s,o),Et("overlapping terminal interval",t.summary.overlappingTerminalIntervalMs,r.summary.overlappingTerminalIntervalMs,c,s,o),Et("peak terminal concurrency",gs(t.summary.peakTerminalConcurrency,d=>d.peak),gs(r.summary.peakTerminalConcurrency,d=>d.peak),c,s,o),ys("model mix",Nn(or(Fo(t.summary.modelMix)),s),Nn(or(Fo(r.summary.modelMix)),o),c),ys("executor mix",Nn(or(Fo(t.summary.executorMix)),s),Nn(or(Fo(r.summary.executorMix)),o),c),Et("completed executions",t.summary.completed,r.summary.completed,c,s,o),Et("failed executions",t.summary.failed,r.summary.failed,c,s,o),Et("interrupted executions",t.summary.interrupted,r.summary.interrupted,c,s,o),Et("tokens",t.summary.tokens,r.summary.tokens,c,s,o),Et("tool interactions",t.summary.toolInteractions,r.summary.toolInteractions,c,s,o),Et("tool errors",t.summary.toolErrors,r.summary.toolErrors,c,s,o),Et("explicit wait count",gs(t.summary.waits,d=>d.count),gs(r.summary.waits,d=>d.count),c,s,o)];return{experimental:!0,eligibility:c,periodA:t.window,periodB:r.window,availabilityA:s,availabilityB:o,dimensions:l,reasons:u}}function FA(t,e){switch(e){case"model":return vt(t.model)??`[${t.model.state}]`;case"executor":return vt(t.executor)??`[${t.executor.state}]`;case"lifecycle":return t.lifecycle.state;case"outcome":return t.lifecycle.state==="terminal"?vt(t.outcome)??"unknown":"open";case"session":return t.sessionRef;case"duration-band":{if(t.lifecycle.state!=="terminal")return"open";const r=vt(t.end);if(r===void 0)return"[unknown-duration]";const n=Math.max(0,r-t.start.at);return n<6e4?"under-1m":n<3e5?"1m-to-5m":n<18e5?"5m-to-30m":"30m-or-more"}}}function WA(t,e){const r=e.filter(n=>n.lifecycle.state==="terminal");return{key:t,executions:e.length,terminalExecutions:r.length,terminalDuration:YA(r.map(n=>{const s=vt(n.end);if(s===void 0)return cr("the terminal execution has no usable end bound");const o=Math.max(0,s-n.start.at);return n.start.evidence==="inferred"||n.end.state==="inferred"?gy(o,"one or more execution bounds were inferred"):or(o)})),tokens:Wo(e.map(n=>n.measures.tokens.total)),toolInteractions:Wo(e.map(n=>n.measures.toolInteractions)),toolErrors:Wo(e.map(n=>n.measures.toolErrors)),failed:Wo(r.map(n=>zA(n.outcome,"failed")))}}function Ho(t,e){return e.observation==="observed"?or(t):e.executionRecords>0?vy(t,"record count is known, but observation continuity is not"):cr("the period was not sufficiently observed to interpret zero records as zero work")}function Et(t,e,r,n,s,o){return ys(t,Nn(e,s),Nn(r,o),n)}function Nn(t,e){return e.comparisonReadiness==="not-comparable"?cr("the period was not sufficiently observed"):t}function ys(t,e,r,n){const s=vt(e)!==void 0&&vt(r)!==void 0;let o;const i=[];return n==="not-comparable"?(o="not-comparable",i.push("one or both periods are not sufficiently observed")):!s||Gf(e.state)||Gf(r.state)?(o="not-comparable",i.push(`measure states are ${e.state} and ${r.state}`)):n==="partially-comparable"||e.state==="partial"||r.state==="partial"||e.state==="inferred"||r.state==="inferred"?(o="partially-comparable",i.push("the values are present, but period or measure coverage is qualified")):o="comparable",{dimension:t,eligibility:o,periodA:e,periodB:r,reasons:i}}function Gf(t){return t==="unsupported"||t==="not-observed"||t==="unknown"}function KA(t,e){return t==="not-comparable"||e==="not-comparable"?"not-comparable":t==="partially-comparable"||e==="partially-comparable"?"partially-comparable":"comparable"}function qf(t){return gs(t,e=>e.median)}function gs(t,e){switch(t.state){case"observed":return{state:"observed",value:e(t.value),coverage:t.coverage};case"inferred":return{state:"inferred",value:e(t.value),qualification:t.qualification,coverage:t.coverage};case"partial":return"value"in t&&t.value!==void 0?{state:"partial",value:e(t.value),qualification:t.qualification,coverage:t.coverage}:{state:"partial",qualification:t.qualification,coverage:t.coverage};case"unsupported":return{...t};case"not-observed":return{...t};case"unknown":return{...t}}}function Fo(t){return Object.fromEntries(t.map(e=>[e.key,e.executions]))}function ps(t,e){return{dimension:t,state:e.state,coverage:e.coverage,qualification:yy(e.state)}}function wc(t,e){const r=ca(e.map(s=>s.state)),n=XA(r);return{dimension:t,state:n,coverage:r,qualification:yy(n)}}function GA(t){const e=t.map(r=>r.end.state!=="observed"&&r.end.state!=="inferred"?"partial":r.start.evidence==="inferred"||r.end.state==="inferred"?"inferred":"observed");return Hl(e.length,ca(e))}function yy(t){switch(t){case"observed":return"all contributing records are observed for this dimension";case"inferred":return"one or more contributing values were inferred";case"partial":return"a subtotal is available, but one or more records are incomplete";case"unsupported":return"the contributing observers do not support this dimension";case"not-observed":return"the dimension is supported but no value was recorded";case"unknown":return"coverage cannot be established"}}function qA(){return{tokens:"unknown",requests:"unknown",toolInteractions:"unknown",toolErrors:"unknown",retries:"unknown",waits:"unknown",model:"unknown",context:"unknown",outcome:"unknown"}}function zA(t,e){const r=vt(t);return ZA(t,r===e?1:0)}function Wo(t){const e=ca(t.map(n=>n.state)),r=t.map(vt).filter(n=>n!==void 0);return r.length>0?Hl(r.reduce((n,s)=>n+s,0),e):e.records>0&&e.unsupported===e.records?{...by("no observer supports this measure"),coverage:e}:e.records>0&&e.notObserved===e.records?{...wy("no value was observed"),coverage:e}:{...cr("no usable value was observed"),coverage:e}}function YA(t){const e=ca(t.map(n=>n.state)),r=t.map(vt).filter(n=>n!==void 0).sort((n,s)=>n-s);return r.length===0?{...cr("no terminal duration samples were observed"),coverage:e}:Hl({samples:r.length,minimum:r[0],median:Ac(r,.5),p75:Ac(r,.75),p90:Ac(r,.9),maximum:r[r.length-1]},e)}function Ac(t,e){const r=(t.length-1)*e,n=Math.floor(r),s=Math.ceil(r);return n===s?t[n]:t[n]+(t[s]-t[n])*(r-n)}function Hl(t,e){return e.partial+e.unsupported+e.notObserved+e.unknown>0?{state:"partial",value:t,qualification:"coverage is incomplete",coverage:e}:e.inferred>0?{state:"inferred",value:t,qualification:"one or more values were inferred",coverage:e}:{state:"observed",value:t,coverage:e}}function XA(t){return t.records===0?"unknown":t.unsupported===t.records?"unsupported":t.notObserved===t.records?"not-observed":t.unknown===t.records?"unknown":t.partial+t.unsupported+t.notObserved+t.unknown>0?"partial":t.inferred>0?"inferred":"observed"}function ca(t){const e=JA();e.records=t.length;for(const r of t)r==="not-observed"?e.notObserved++:e[r]++;return e}function JA(){return{records:0,observed:0,inferred:0,partial:0,unsupported:0,notObserved:0,unknown:0}}function vt(t){return"value"in t?t.value:void 0}function ZA(t,e){switch(t.state){case"observed":return or(e);case"inferred":return gy(e,t.qualification);case"partial":return vy("value"in t?e:void 0,t.qualification);case"unsupported":return by(t.qualification);case"not-observed":return wy(t.qualification);case"unknown":return cr(t.qualification)}}function or(t){return{state:"observed",value:t}}function gy(t,e){return{state:"inferred",value:t,qualification:e}}function vy(t,e){return t===void 0?{state:"partial",qualification:e}:{state:"partial",value:t,qualification:e}}function by(t){return{state:"unsupported",qualification:t}}function wy(t){return{state:"not-observed",qualification:t}}function cr(t){return{state:"unknown",qualification:t}}const Hr="os",QA=(t,e)=>`os:${t}:${e.pid}:${e.startedAt}`;function eS(t,e){const r=/^os:[^:]+:(\d+):(\d+)$/.exec(t);return r?`os:${e}:${r[1]}:${r[2]}`:void 0}const tS=t=>`The process was present in one ${Math.round(t/1e3)}s snapshot and absent from the next, so it exited somewhere in that window. The recorded instant is the last moment it was observed alive — a lower bound on the true exit. A process that started and exited entirely within one interval is never observed at all.`,rS=250,nS=8*1024*1024;function sS(t,e,r){const n={source:{id:Hr,instance:r.host},observedAt:r.observedAt,clock:"wall",stratum:"machine"},s=[],o=new Map;for(const i of e){const a=QA(r.host,i);o.set(a,i);const c={ns:"os.process",parts:[r.host,i.pid],validFrom:i.startedAt,validTo:r.observedAt};if(!t.has(a)){s.push({...n,occurredAt:i.startedAt,kind:"began",subject:{type:"process",id:a},claims:[c],basis:"measured",core:{machineId:r.machineId,label:oS(i.command),executor:i.command,measures:{[z.cpuMs]:i.cpuMs}},attrs:{"os.pid":i.pid,"os.ppid":i.ppid,"os.command":i.command,"os.rssBytes":i.rssBytes}});continue}const u=t.get(a),l=i.cpuMs-u.cpuMs>=rS,d=Math.abs(i.rssBytes-u.rssBytes)>=nS;(l||d)&&s.push({...n,occurredAt:r.observedAt,seq:`obs:${r.observedAt}`,kind:"observed",subject:{type:"process",id:a},claims:[c],basis:"measured",core:{measures:{[z.cpuMs]:i.cpuMs}},attrs:{"os.rssBytes":i.rssBytes}})}for(const[i,a]of t)o.has(i)||s.push({...n,occurredAt:r.observedAt-r.intervalMs,kind:"ended",subject:{type:"process",id:i},basis:"inferred",assumption:tS(r.intervalMs),core:{outcome:"completed",measures:{[z.cpuMs]:a.cpuMs}},attrs:{"os.pid":a.pid}});return{envelopes:s,next:o}}function oS(t){return(t.split("/").pop()??t).toUpperCase()}const iS=9e4;function zf(t,e){if(t.waitingSince===void 0)return;const r=t.waitingSince,n=Math.max(r,e);t.waitingMs+=n-r,t.waits.push({start:r,end:n})}function aS(t,e){const r=`${e.source.id}:${e.source.instance}`;let n=t.sources.get(r);n||(n={id:e.source.id,instance:e.source.instance,origin:e.source.instance,firstSeenAt:e.occurredAt,lastSeenAt:e.occurredAt,events:0,strata:{}},t.sources.set(r,n)),n.events++,e.occurredAt<n.firstSeenAt&&(n.firstSeenAt=e.occurredAt),e.occurredAt>n.lastSeenAt&&(n.lastSeenAt=e.occurredAt),e.stratum&&(n.strata[e.stratum]=(n.strata[e.stratum]??0)+1);const s=e.provenance?.sourceVersion;s&&(n.sourceVersions?n.sourceVersions.includes(s)||n.sourceVersions.push(s):n.sourceVersions=[s])}function cS(t,e){if(t.seen.has(e.id))return;t.seen.add(e.id),e.occurredAt>t.now&&(t.now=e.occurredAt),aS(t,e);const r=e.core??{},n=e.occurredAt;switch(e.subject.type){case"machine":{if(t.machines.has(e.subject.id))break;const s={id:e.subject.id,name:r.machineName??e.subject.id,kind:r.machineKind??"laptop",parentId:r.parentId,firstSeenAt:n};t.machines.set(s.id,s);break}case"session":{if(e.kind==="began"){const s=t.sessions.get(e.subject.id);if(s){s.parentId===void 0&&r.parentId&&(s.parentId=r.parentId),s.projectLabel===void 0&&r.projectLabel&&(s.projectLabel=r.projectLabel),s.taskLabel===void 0&&r.taskLabel&&(s.taskLabel=r.taskLabel);break}const o={id:e.subject.id,machineId:r.machineId??"",label:r.label,projectLabel:r.projectLabel,taskLabel:r.taskLabel,context:e.attrs?.context??r.label??"",executor:r.executor,model:r.model,startedAt:n,executionIds:[],parentId:r.parentId};t.sessions.set(o.id,o)}else if(e.kind==="ended"){const s=t.sessions.get(e.subject.id);s&&(s.endedAt=n)}break}case"execution":uS(t,e,n);break;case"process":lS(t,e,n);break;case"artifact":{if(t.artifacts.has(e.subject.id))break;t.artifacts.set(e.subject.id,{id:e.subject.id,kind:"file",path:r.label??e.subject.id,firstSeenAt:n});break}}}function uS(t,e,r){const n=e.core??{},s=e.subject.id;if(e.kind==="began"){if(t.executions.has(s))return;const i={id:s,sessionId:n.sessionId??n.parentId??"",machineId:n.machineId??"",label:n.label??s,executor:n.executor??"unknown",model:n.model,status:"running",startedAt:r,lastActivityAt:r,measures:{},waitingMs:0,waits:[],parentId:n.parentId,depth:n.depth??0,startBasis:e.basis,boundsAssumption:e.assumption};n.measures&&fi(i.measures,n.measures),t.executions.set(s,i),t.active.add(s),t.sessions.get(i.sessionId)?.executionIds.push(s);return}const o=t.executions.get(s);if(o)switch(e.kind){case"progressed":{n.measures&&fi(o.measures,n.measures),o.lastActivityAt=r,o.status==="idle"&&(o.status="running",t.active.add(s));break}case"blocked":{if(!Dm(o.status))break;o.status="waiting",o.waitingSince=r,o.waitReason=n.blockedOn??"input",o.lastActivityAt=r;break}case"resumed":{zf(o,r),o.status="running",o.waitingSince=void 0,o.waitReason=void 0,o.lastActivityAt=r,t.active.add(s);break}case"ended":{const i=n.outcome==="error";o.status=i?"failed":"completed",o.endedAt=r,o.endBasis=e.basis,e.assumption&&!o.boundsAssumption&&(o.boundsAssumption=e.assumption),o.lastActivityAt=r,o.outcome=n.outcome??"completed",i&&(o.failure={code:n.failureCode??"ERROR",message:n.failureMessage??"Execution failed"}),zf(o,r),o.waitingSince=void 0,o.waitReason=void 0,t.active.delete(s);break}case"observed":o.lastActivityAt=Math.max(o.lastActivityAt,r);break}}function lS(t,e,r){const n=e.core??{},s=e.subject.id,o=Number(e.attrs?.["os.pid"]??0);if(e.kind==="began"){if(t.processes.has(s))return;const a={id:s,machineId:n.machineId??"",pid:o,ppid:typeof e.attrs?.["os.ppid"]=="number"?e.attrs["os.ppid"]:void 0,command:n.label??n.executor??String(o),startedAt:r,lastSeenAt:r,status:"running",measures:{}};n.measures&&fi(a.measures,n.measures),t.processes.set(s,a);return}const i=t.processes.get(s);if(i)if(e.kind==="observed"||e.kind==="progressed"){if(i.lastSeenAt=Math.max(i.lastSeenAt,r),n.measures){const a=n.measures[z.cpuMs];typeof a=="number"&&(i.measures[z.cpuMs]=a);const{[z.cpuMs]:c,...u}=n.measures;fi(i.measures,u)}}else e.kind==="ended"&&(i.endedAt=r,i.lastSeenAt=Math.max(i.lastSeenAt,r),i.status="exited",i.endInferred=e.basis==="inferred")}function dS(t,e){for(let r=0;r<e.length;r++)cS(t,e[r])}function fS(t,e){e>t.now&&(t.now=e),e=t.now;for(const r of t.active){const n=t.executions.get(r);if(!n){t.active.delete(r);continue}n.status==="running"&&e-n.lastActivityAt>iS&&(n.status="idle")}}function Ay(t,e,r,n,s){const o=s?pS(s):void 0,i=o?Xf(t.query(e,r,n),o):t.query(e,r,n),a=new Set,c=new Set,u=new Map,l=p=>{const y=`${p.subject.type}:${p.subject.id}`;p.kind==="began"?(a.add(y),u.set(y,p)):c.add(y),p.core?.sessionId&&c.add(`session:${p.core.sessionId}`),p.core?.machineId&&c.add(`machine:${p.core.machineId}`)};for(const p of i)l(p);const d=[];for(let p=0;p<4;p++){const y=[...c].filter(g=>!a.has(g));if(y.length===0)break;const v=o?Xf(t.begansFor(y),o):t.begansFor(y);if(v.length===0)break;for(const g of v)u.set(`${g.subject.type}:${g.subject.id}`,g),d.push(g.occurredAt<e?{...g,occurredAt:e}:g),l(g),a.add(`${g.subject.type}:${g.subject.id}`)}return{events:[...d,...i].sort((p,y)=>p.occurredAt-y.occurredAt||Jf(p)-Jf(y)),declarations:[...u.values()],relationships:gb(t.claims(e,r)).relationships}}function Sy(t,e,r,n,s){const o=performance.now(),{events:i,declarations:a,relationships:c}=Ay(t,e,r,s,n),u=performance.now()-o,l=performance.now(),d=Pm(e,r);dS(d,i),fS(d,r);const m=performance.now()-l;return{state:d,events:i,declarations:a,relationships:c,meta:{events:i.length,readMs:Math.round(u*10)/10,deriveMs:Math.round(m*10)/10}}}function Yf(t,e,r,n){const s=Sy(t,e,r,n),o=performance.now();return{world:K0(s.state,s.relationships),state:s.state,declarations:s.declarations,meta:{...s.meta,serializeMs:Math.round((performance.now()-o)*10)/10}}}function pS(t){const e=Ob(t);return r=>{if(r.subject.type==="machine")return r.subject.id!==t&&Qd(r.subject.id)?null:r;const n=r.core?.machineId;if(!n||n===t||!Qd(n))return r;const s=r.subject.type==="process"&&e?eS(r.subject.id,e):void 0;return{...r,...s?{subject:{...r.subject,id:s}}:{},core:{...r.core,machineId:t}}}}function Xf(t,e){const r=[];for(const n of t){const s=e(n);s&&r.push(s)}return r}function Jf(t){if(t.kind==="ended")return 5;switch(t.subject.type){case"machine":return 0;case"session":return 1;case"execution":case"process":return t.kind==="began"?2:3;default:return 4}}const hS=[[Ol,Ab],[li,Mb],[Kr,qb],[Ds,o0],[Pn,A0],[Ls,T0]],Fl=new Map(hS);function mS(t,e,r,n){const s=Sy(t,e,r,n,["machine","session","execution"]);return CA({state:s.state,declarations:s.declarations,relationships:s.relationships,capabilities:Fl,from:e,to:r})}function ky(t,e,r,n=Date.now()){const s=new Map,o=a=>{const c=`${a.from}:${a.to}`,u=s.get(c);if(u)return u;const l=mS(t,a.from,a.to,r);return s.set(c,l),l},i=a=>yS(a,e,n);return{summary(a){return LA(o(a),i(a))},availability(a){return Qs(o(a),i(a))},compare(a,c){return HA(o(a),i(a),o(c),i(c))},breakdown(a,c){return VA(o(a),i(a),c)}}}function yS(t,e,r){const n=e.eventDays===0?null:r-e.eventDays*864e5,s=n===null?"retained-indefinitely":t.to<n?"outside-retention":t.from<n?"partially-within-retention":"within-retention";return{capabilities:Fl,continuity:{state:"unknown",qualification:"057 does not retain historical source-health continuity for this period"},retention:{state:s,semanticFrom:n,qualification:n===null?"semantic history is configured to be retained indefinitely":s==="within-retention"?"the requested period is inside the configured semantic retention window":s==="partially-within-retention"?"the requested period crosses the configured semantic retention boundary":"the requested period precedes the configured semantic retention window"}}}const gS=3e4;function vS(t,e,r){const n=aa(t.path);try{const s=t.now?.()??Date.now(),o=ky(n,t.retention,t.machineId,s);return tA(o,e,s,r)}finally{n.close()}}function bS(t,e){return JSON.stringify([t.query,t.scope,t.focus,t.by,e.view,e.timeZone])}function xy(t){const e=new Map;return{async read(r,n){const s=t.now?.()??Date.now(),o=bS(r,n),i=e.get(o);if(i&&s-i.at<gS)return i.reading;const a=vS(t,r,n);return e.set(o,{at:s,reading:a}),a},close(){e.clear()}}}function wS(t,e){let r=null,n=1;const s=new Map,o=a=>{for(const c of s.values())c.reject(a);s.clear()},i=()=>{const a={o57:"activity-reader",path:e.path,retention:e.retention,machineId:e.machineId},c=new mm(new URL(t),{workerData:a,execArgv:["--disable-warning=ExperimentalWarning"]});return c.unref(),c.on("message",u=>{const l=s.get(u.id);l&&(s.delete(u.id),u.reading?l.resolve(u.reading):l.reject(new Error(u.error??"the reading failed")))}),c.on("error",u=>{r=null,o(u instanceof Error?u:new Error(String(u)))}),c.on("exit",u=>{r===c&&(r=null),s.size>0&&o(new Error(`the reading worker stopped (${u})`))}),c};return{read(a,c){r??=i();const u=n++,l={id:u,request:a,context:c};return new Promise((d,m)=>{s.set(u,{resolve:d,reject:m}),r?.postMessage(l)})},close(){o(new Error("the Core is stopping")),r?.terminate(),r=null}}}function AS(t){const e=xy(t);Bn?.on("message",r=>{e.read(r.request,r.context).then(n=>Bn?.postMessage({id:r.id,reading:n}),n=>Bn?.postMessage({id:r.id,error:String(n instanceof Error?n.message:n)}))})}!hm&&ai?.o57==="activity-reader"&&AS(ai);const Wl={[hi]:qs};function Kl(t){return`${t}.core.json`}function Ey(t){const e=Kl(t);if(!fe(e))return null;try{const r=JSON.parse(Cl(e,"utf8"));return typeof r.pid!="number"||typeof r.url!="string"?null:r}catch{return null}}function SS(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function kS(t,e=1500){const r=Ey(t);if(!r||r.pid===process.pid||!SS(r.pid))return null;try{const n=await fetch(`${r.url}/api/health`,{signal:AbortSignal.timeout(e)});return n.ok&&(await n.json()).pid===r.pid?r:null}catch{return null}}function xS(t,e){if(t===":memory:")return;const r=Kl(t),n=`${r}.${process.pid}.tmp`;El(n,`${JSON.stringify(e,null,1)}
82
- `,{mode:384}),Il(n,r)}function ES(t,e=process.pid){if(t===":memory:")return;const r=Ey(t);r&&r.pid===e&&fm(Kl(t),{force:!0})}class Gl extends Error{constructor(e){super(`057 is already observing ${e.store} at ${e.url} (pid ${e.pid})`),this.record=e}record}const IS=ab(ib);function CS(){return gm()}function OS(t){const e=[];for(const r of t.split(`
83
- `)){const n=r.trim();if(!n)continue;const s=n.match(/^(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+[\d:]+\s+\d{4})\s+([\d:.]+)\s+(\d+)\s+(.*)$/);if(!s)continue;const[,o,i,a,c,u,l]=s,d=Date.parse(a);Number.isFinite(d)&&e.push({pid:Number(o),ppid:Number(i),startedAt:d,cpuMs:NS(c),rssBytes:Number(u)*1024,command:l.trim()})}return e}function NS(t){const[e,r]=t.includes("-")?t.split("-"):["0",t],n=r.split(":").map(Number);let s=0;for(const o of n)s=s*60+(Number.isFinite(o)?o:0);return Math.round((s+Number(e)*86400)*1e3)}async function TS(){const{stdout:t}=await IS("ps",["-Ao","pid=,ppid=,lstart=,time=,rss=,comm="],{maxBuffer:8388608});return OS(t)}const Zf=5e3;function BS(t,e){const r=CS();let n=new Map,s=null,o=0,i=null,a,c=!1;async function u(){if(c)return[];c=!0;try{const l=await TS(),d=Date.now(),{envelopes:m,next:p}=sS(n,l,{machineId:e,host:r,observedAt:d,intervalMs:Zf}),y=m.map(Wt);return t.append(y),n=p,o++,i=d,a=void 0,y}catch(l){return a=l instanceof Error?l.message:String(l),[]}finally{c=!1}}return{sample:u,start(){s||(u(),s=setInterval(()=>{u()},Zf),s.unref?.())},stop(){s&&clearInterval(s),s=null},get running(){return s!==null},stats(){return{samples:o,tracked:n.size,lastSampleAt:i,lastError:a}}}}const Iy={info:t=>console.log(t),warn:t=>console.warn(t),error:t=>console.error(t)},$S=36e5,RS=15e3,_S=3;function Cy(t={}){const e=t.log??Iy,r=t.path??sa(),n=t.retention??ly(),s=EA(r),o=s.stats();e.info(o.events>0?`[057] store ${r}: opened with ${o.events} events`:`[057] store ${r}: NEW EMPTY STORE — if history existed before, it was lost, not carried`);const i=uy();i&&e.warn(`[057] a store from a previous layout exists at ${i} and is NOT in use. Run 057 with O57_STORE=${i} to keep using it, or move it to ${r}.`);const a=_r();s.append([Wt({source:{id:"host",instance:a.id},occurredAt:0,observedAt:Date.now(),clock:"wall",kind:"began",stratum:"machine",subject:{type:"machine",id:a.id},basis:"measured",core:{machineName:a.name,machineKind:a.kind},seq:"host"})]);const c=BS(s,a.id),u=new Map;function l(A){for(const I of A){const B=u.get(I.id)??{consecutiveFailures:0,totalFailures:0,failing:!1};I.ok?(B.consecutiveFailures=0,B.failing=!1,B.failingSince=void 0,B.lastSuccessAt=Date.now()):(B.consecutiveFailures===0&&(B.failingSince=Date.now()),B.consecutiveFailures++,B.totalFailures++,B.lastFailureAt=Date.now(),B.lastError=I.error,B.consecutiveFailures>=_S&&!B.failing&&(B.failing=!0,e.warn(`[057] source ${I.id} has failed ${B.consecutiveFailures} collection rounds in a row: ${I.error??"unknown error"}`))),u.set(I.id,B)}}const d=Qf(r);let m=null;function p(A){return m||(m=A,e.error(`[057] ${A.message} — ${A.remedy}`),c.stop()),m}function y(){if(m)return m;if(r===":memory:")return null;if(!fe(r))return p({kind:"unlinked",message:`the store at ${r} no longer exists on disk; captured events are going to an orphaned file and will be lost`,remedy:"Stop 057 and start it again. It will open a new store at the same path.",since:Date.now()});const A=Qf(r);return d!==null&&A!==null&&A!==d?p({kind:"replaced",message:`the store at ${r} was replaced by a different file while 057 was running; captured events are going to the old one`,remedy:"Stop 057 and start it again so it opens the file that is actually there.",since:Date.now()}):null}t.observe!==!1&&c.start();const v=s.sweep(n);v.processEvents+v.otherEvents>0&&e.info(`[057] retention: removed ${v.processEvents} process and ${v.otherEvents} semantic events (${ia(n)})`);const g=setInterval(()=>{if(!m)try{s.sweep(n),Gc(r)}catch(A){e.warn(`[057] retention sweep failed: ${String(A)}`)}},$S);g.unref?.();const C=setInterval(()=>{y()},RS);return C.unref?.(),{store:s,machine:a,os:c,path:r,retention:n,fault:()=>m,sweep:A=>s.sweep(n,A),checkStore:y,recordCollection:l,collectionHealth:()=>Object.fromEntries(u),stop(){clearInterval(g),clearInterval(C),c.stop(),s.close()}}}function Qf(t){try{return Qi(t).ino}catch{return null}}function MS(t,e){const r=new Map;for(const s of e)s.kind==="began"&&s.subject.type==="execution"&&r.set(s.subject.id,s.source.id);let n=0;for(const s of t.executions.keys()){const o=r.get(s),i=o?Fl.get(o)?.waits:void 0;(i==="supported"||i==="partial")&&n++}return{reported:n,runs:t.executions.size}}function Oy(t,e,r){let n={from:r.from,to:r.to},s=r.label,o=Yf(t,n.from,n.to,e);if(r.widenFrom!==void 0&&o.world.executions.length===0&&o.world.sessions.length===0){const i=Yf(t,r.widenFrom,r.to,e);(i.world.executions.length>0||i.world.sessions.length>0)&&(n={from:r.widenFrom,to:r.to},s=r.widenedLabel??s,o=i)}return{...n,label:s,world:o.world,meta:o.meta,waits:MS(o.state,o.declarations)}}function jS(t,e){return{async read(r){return Oy(t,e,r)},close(){}}}function DS(t,e){let r=null,n=1,s=null;const o=new Map,i=c=>{for(const u of o.values())u.reject(c);o.clear()},a=()=>{const c={o57:"landscape-reader",...e},u=new mm(new URL(t),{workerData:c,execArgv:["--disable-warning=ExperimentalWarning"]});return u.unref(),u.on("message",l=>{const d=o.get(l.id);d&&(o.delete(l.id),l.snapshot?d.resolve(l.snapshot):d.reject(new Error(l.error??"the landscape read failed")))}),u.on("error",l=>{r=null,i(l instanceof Error?l:new Error(String(l)))}),u.on("exit",l=>{r===u&&(r=null),o.size>0&&i(new Error(`the landscape worker stopped (${l})`))}),u};return{read(c){if(c.label==="TODAY"&&s)return s;r??=a();const u=n++,l=new Promise((d,m)=>{o.set(u,{resolve:d,reject:m}),r?.postMessage({id:u,request:c})});return c.label!=="TODAY"?l:(s=l.finally(()=>{s=null}),s)},close(){i(new Error("the Core is stopping")),r?.terminate(),r=null,s=null}}}function PS(t){const e=aa(t.path);Bn?.on("message",r=>{try{Bn?.postMessage({id:r.id,snapshot:Oy(e,t.machineId,r.request)})}catch(n){Bn?.postMessage({id:r.id,error:String(n instanceof Error?n.message:n)})}})}!hm&&ai?.o57==="landscape-reader"&&PS(ai);const Yc=[{id:Ol,collect:(t,e)=>_b(t,e)},{id:li,collect:(t,e)=>Gb(t,e)},{id:Kr,collect:(t,e)=>s0(t,e)},{id:Ds,collect:(t,e)=>w0(t,e)},{id:Pn,collect:(t,e)=>N0(t,e)},{id:Ls,collect:(t,e)=>V0(t,e)}],ep=[...Yc.map(t=>t.id),Hr],tp=10*365*24*36e5,Ko=2e5,LS=24*36e5,rp=72*36e5;function np(t){const e=new Date(t);return e.setHours(0,0,0,0),{from:e.getTime(),to:t}}function sp(t){const e=t.collectionHealth(),r=Object.entries(e).filter(([,a])=>a.failing).map(([a])=>a),n=t.store.health(),s=t.os.stats(),o=t.fault();let i=null;for(const a of Object.values(e))a.lastSuccessAt&&(i===null||a.lastSuccessAt>i)&&(i=a.lastSuccessAt);return{ok:r.length===0&&n.ok&&!o&&!s.lastError,fault:o??void 0,failingSources:r,errors:Object.fromEntries(Object.entries(e).filter(([,a])=>a.failing).map(([a,c])=>[a,c.lastError??"failing"])),failing:Object.fromEntries(Object.entries(e).filter(([,a])=>a.failing).map(([a,c])=>[a,{since:c.failingSince??null,rounds:c.consecutiveFailures}])),store:{ok:n.ok,remedy:n.remedy},os:{running:t.os.running,lastSampleAt:s.lastSampleAt,lastError:s.lastError},lastCollectionAt:i,sources:{total:ep.length,reported:ep.filter(a=>e[a]!==void 0).length}}}function US(t,e,r){const n=e.startsWith("/api/");if(r){const a=(t.headers.host??"").toLowerCase(),c=a.startsWith("[")?a.slice(0,a.indexOf("]")+1):a.split(":")[0];if(!r.includes(c))return`refusing a request for host "${a}"; 057 answers only on ${r.join(", ")}`}const s=t.headers.origin;if(typeof s=="string"&&s!=="null"){const a=(t.headers.host??"").toLowerCase();let c="";try{c=new URL(s).host.toLowerCase()}catch{return"refusing a request with an unparseable Origin"}if(c!==a)return`refusing a cross-origin request from ${s}`}const o=t.headers["sec-fetch-site"],i=String(t.headers["sec-fetch-dest"]??"");if(HS.has(i))return`refusing to be embedded as ${i}`;if(typeof o=="string"&&o!==""){if(o!=="same-origin"&&o!=="none")return`refusing a ${o} request`;if(o==="none"&&n)return"refusing a directly-navigated API request"}else if(n&&e==="/api/collect"&&!t.headers[VS])return"refusing a state-changing request that carries no fetch metadata";return null}const VS="x-057-client",HS=new Set(["iframe","frame","embed","object","fencedframe"]);function ql(t){t.setHeader("x-frame-options","DENY"),t.setHeader("content-security-policy","frame-ancestors 'none'")}function FS(t,e){const r=(o,i)=>{const a=t.get(o);if(a===null||a==="")return i;const c=Number(a);return Number.isSafeInteger(c)?c:null},n=r("from",e-864e5),s=r("to",e);return n===null||s===null?{error:"from and to must be integer epoch millis"}:s<n?{error:"to must not precede from"}:s>e+LS?{error:"to is too far in the future"}:s-n>tp?{error:`window must not exceed ${tp} ms`}:{from:n,to:s}}function Ee(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.setHeader("cache-control","no-store"),t.setHeader("x-content-type-options","nosniff"),ql(t),t.end(JSON.stringify(r))}function WS(t){const e=t.problems.filter(r=>r.path.includes("/sessions/")).length;return{identity:t.identityAvailable?e===0?"available":t.registryEntries>0?"partial":"failed":"unavailable","stored-semantics":t.storedAvailable?t.transcriptsFailed===0?"available":t.transcriptsRead>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function Sc(t){return{"stored-semantics":t.storedAvailable?t.failed===0?"available":t.read>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function KS(t){return t.error?"failed":t.available?"observing":t.present?"installed-no-data":"not-installed"}function GS(t){const e=t.home??t.globalStorage;if(typeof e=="string")return e;const r=t.roots;return Array.isArray(r)?r.join(", "):void 0}function Ur(t){return{available:t.available,present:t.present??!1,presence:KS(t),origin:GS(t),error:t.error}}function qS(t){const{runtime:e,log:r}=t,n=t.activity??xy({path:e.path,retention:e.retention,machineId:e.machine.id}),s=t.landscape??jS(e.store,e.machine.id);let o=null;async function i(a){if(!o||a-o.at>6e4){const c=np(a),u=await s.read({...c,label:"TODAY",widenFrom:a-rp,widenedLabel:"LAST 72H"}),l=yf(u.world);o={at:a,label:u.label,world:l,landscape:Cf(l),waits:u.waits}}return o}return async function(c,u){const l=c.url??"";if(!l.startsWith("/api/"))return!1;const d=new URL(l,"http://localhost"),m=US(c,d.pathname,t.allowedHosts);if(m)return r.warn(`[057] ${m}`),Ee(u,403,{error:m}),!0;const p=e.store,y=Date.now(),v=FS(d.searchParams,y);if("error"in v)return Ee(u,400,{error:v.error}),!0;const{from:g,to:C}=v;try{if(d.pathname==="/api/state"){const[A,I,B,k,T,S]=await Promise.all([tf().catch(pe=>({available:!1,error:String(pe)})),of().catch(pe=>({available:!1,error:String(pe)})),cf().catch(pe=>({available:!1,error:String(pe)})),uf().catch(pe=>({available:!1,error:String(pe)})),pf().catch(pe=>({available:!1,error:String(pe)})),mf().catch(pe=>({available:!1,error:String(pe)}))]),[E,R,j,M]=await Promise.all([Im(g,C).catch(()=>null),Nm(g,C).catch(()=>null),$m(g,C).catch(()=>null),jm(g,C).catch(()=>null)]),J={strata:{"stored-semantics":"failed"}},le={"claude-code":E?{strata:WS(E),registryEntries:E.registryEntries,transcriptsRead:E.transcriptsRead,transcriptsFailed:E.transcriptsFailed,problems:E.problems.slice(0,20)}:{strata:{identity:"failed"}},codex:R?{strata:Sc({storedAvailable:R.storedAvailable,read:R.rolloutsRead,failed:R.rolloutsFailed}),rolloutsRead:R.rolloutsRead,rolloutsFailed:R.rolloutsFailed,problems:R.problems.slice(0,20)}:J,cursor:j?{strata:Sc({storedAvailable:j.storedAvailable,read:j.composersRead,failed:j.composersFailed}),composersRead:j.composersRead,composersFailed:j.composersFailed,problems:j.problems.slice(0,20)}:J,gemini:M?{strata:Sc({storedAvailable:M.storedAvailable,read:M.sessionsRead,failed:M.sessionsFailed}),sessionsRead:M.sessionsRead,sessionsFailed:M.sessionsFailed,problems:M.problems.slice(0,20)}:J},re={deepseek:Ur(A),"0x2f":Ur(I),"claude-code":Ur(B),codex:Ur(k),cursor:Ur(T),gemini:Ur(S)},F=e.collectionHealth();for(const[pe,Z]of Object.entries(re)){const yt=F[pe];yt?.failing&&(Z.presence="failed",Z.error??=yt.lastError)}const W=e.os.stats(),he=Object.values(re).filter(pe=>pe.available).length>0?"observing":W.samples>0?"os-only":"empty",$e=Object.entries(F).filter(([,pe])=>pe.failing).map(([pe])=>pe),Me=p.health(),Qt={ok:$e.length===0&&Me.ok&&!e.fault()&&!W.lastError,failingSources:$e,collection:F,store:Me,os:W.lastError?{failing:!0,lastError:W.lastError}:{failing:!1}};return Ee(u,200,{machine:e.machine,mode:he,fault:e.fault()??void 0,health:Qt,store:{...p.stats(),path:p.path,schemaVersion:p.schemaVersion,bytes:p.sizeBytes(),retention:{...e.retention,description:ia(e.retention)}},os:{...W,running:e.os.running,source:Hr},sources:re,observation:le}),!0}if(d.pathname==="/api/collect"){const A=e.checkStore();if(A)return Ee(u,503,{error:A.message,fault:A}),!0;const I=await vb(p,Yc,g,C,k=>e.recordCollection([k])),B=await e.os.sample();return e.recordCollection([{id:Hr,ok:!e.os.stats().lastError,error:e.os.stats().lastError}]),Ee(u,200,{...I,sources:[...I.sources,{id:Hr,ok:!e.os.stats().lastError,collected:B.length,inserted:B.length,duplicate:0,error:e.os.stats().lastError,ms:0}]}),!0}if(d.pathname==="/api/world"){const A=await s.read({from:g,to:C,label:"WINDOW"});return Ee(u,200,{from:g,to:C,now:y,world:A.world,meta:A.meta,waits:A.waits}),!0}if(d.pathname==="/api/health")return Ee(u,200,{pid:process.pid,version:t.version??"dev",contract:Wl,store:e.path,health:sp(e)}),!0;if(d.pathname==="/api/landscape"){const A=d.searchParams.get("window")==="live",I=A?np(y):{from:g,to:C},B=await s.read({...I,label:A?"TODAY":"WINDOW",...A?{widenFrom:y-rp,widenedLabel:"LAST 72H"}:{}}),k=yf(B.world),T=Cf(k);return A&&(o={at:y,label:B.label,world:k,landscape:T,waits:B.waits}),Ee(u,200,{from:B.from,to:B.to,now:y,window:B.label,meta:B.meta,health:sp(e),...ow(T)}),!0}if(d.pathname==="/api/today"||d.pathname==="/api/log"){const A=await i(y);return Ee(u,200,d.pathname==="/api/today"?{window:A.label,...Cw(A.world,A.waits)}:{window:A.label,...Ow(A.world,A.landscape)}),!0}if(d.pathname==="/api/inspect"){const A=d.searchParams.get("kind")??"",I=d.searchParams.get("id")??"";if(!["disturbance","stratum","mass","coupling"].includes(A)||!I||I.length>512)return Ee(u,400,{error:"inspect needs kind=disturbance|stratum|mass|coupling and an id"}),!0;if(await i(y),!o)return!0;const B=(T,S)=>{for(const E of p.subjectEvents(T,S))if(E.provenance?.path)return E.provenance.path},k=aw(o.world,o.landscape,A,I,B);return k?(Ee(u,200,k),!0):(Ee(u,404,{error:"not in the current world"}),!0)}if(d.pathname==="/api/activity"){const A=d.searchParams,I=Zw({query:A.get("query"),scope:A.get("scope"),focus:A.get("focus"),by:A.get("by")});if("error"in I)return Ee(u,400,I),!0;const B=A.get("view")==="live"?o?.label??(await i(y)).label:void 0;return Ee(u,200,await n.read(I,B?{view:B}:{})),!0}if(d.pathname==="/api/sources"){const A=await Promise.all([tf().catch(T=>({available:!1,error:String(T)})),of().catch(T=>({available:!1,error:String(T)})),cf().catch(T=>({available:!1,error:String(T)})),uf().catch(T=>({available:!1,error:String(T)})),pf().catch(T=>({available:!1,error:String(T)})),mf().catch(T=>({available:!1,error:String(T)}))]),I=e.collectionHealth(),B=e.os.stats(),k=Yc.map((T,S)=>{const E=Ur(A[S]),R=I[T.id];return{id:T.id,presence:R?.failing?"failed":E.presence,origin:E.origin,error:R?.failing?R.lastError??E.error:E.error,consecutiveFailures:R?.consecutiveFailures??0,lastSuccessAt:R?.lastSuccessAt}});return k.push({id:Hr,presence:B.lastError?"failed":B.samples>0?"observing":"installed-no-data",origin:void 0,error:B.lastError,consecutiveFailures:I[Hr]?.consecutiveFailures??0,lastSuccessAt:B.lastSampleAt??void 0}),Ee(u,200,{sources:k}),!0}if(d.pathname==="/api/detail"){const A=d.searchParams.get("type")??"",I=d.searchParams.get("id")??"";if(!Yd.includes(A)||!I)return Ee(u,400,{error:"detail needs type=<entity type> and id"}),!0;if(I.length>512)return Ee(u,400,{error:"id is too long"}),!0;const B=p.subjectEvents(A,I);return Ee(u,200,{type:A,id:I,events:B.slice(0,Ko),truncated:B.length>Ko}),!0}if(d.pathname==="/api/events"){const A=d.searchParams.get("subject"),I=A?A.split(",").filter(k=>Yd.includes(k)):void 0,B=Ay(p,g,C,I,e.machine.id);return Ee(u,200,{from:g,to:C,now:y,events:B.events.slice(0,Ko),truncated:B.events.length>Ko,relationships:B.relationships}),!0}return Ee(u,404,{error:"unknown endpoint"}),!0}catch(A){return r.error(`[057] ${String(A)}`),Ee(u,500,{error:String(A)}),!0}}}var op=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ip={};var ap;function zS(){if(ap)return ip;ap=1;var t;return(function(e){(function(r){var n=typeof globalThis=="object"?globalThis:typeof op=="object"?op:typeof self=="object"?self:typeof this=="object"?this:c(),s=o(e);typeof n.Reflect<"u"&&(s=o(n.Reflect,s)),r(s,n),typeof n.Reflect>"u"&&(n.Reflect=e);function o(u,l){return function(d,m){Object.defineProperty(u,d,{configurable:!0,writable:!0,value:m}),l&&l(d,m)}}function i(){try{return Function("return this;")()}catch{}}function a(){try{return(0,eval)("(function() { return this; })()")}catch{}}function c(){return i()||a()}})(function(r,n){var s=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",i=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",a=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",c=typeof Object.create=="function",u={__proto__:[]}instanceof Array,l=!c&&!u,d={create:c?function(){return ac(Object.create(null))}:u?function(){return ac({__proto__:null})}:function(){return ac({})},has:l?function(w,x){return s.call(w,x)}:function(w,x){return x in w},get:l?function(w,x){return s.call(w,x)?w[x]:void 0}:function(w,x){return w[x]}},m=Object.getPrototypeOf(Function),p=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Wv(),y=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Kv(),v=typeof WeakMap=="function"?WeakMap:Gv(),g=o?Symbol.for("@reflect-metadata:registry"):void 0,C=Vv(),A=Hv(C);function I(w,x,N,P){if(Z(N)){if(!Vd(w))throw new TypeError;if(!Hd(x))throw new TypeError;return le(w,x)}else{if(!Vd(w))throw new TypeError;if(!me(x))throw new TypeError;if(!me(P)&&!Z(P)&&!yt(P))throw new TypeError;return yt(P)&&(P=void 0),N=Dt(N),re(w,x,N,P)}}r("decorate",I);function B(w,x){function N(P,Q){if(!me(P))throw new TypeError;if(!Z(Q)&&!Lv(Q))throw new TypeError;$e(w,x,P,Q)}return N}r("metadata",B);function k(w,x,N,P){if(!me(N))throw new TypeError;return Z(P)||(P=Dt(P)),$e(w,x,N,P)}r("defineMetadata",k);function T(w,x,N){if(!me(x))throw new TypeError;return Z(N)||(N=Dt(N)),F(w,x,N)}r("hasMetadata",T);function S(w,x,N){if(!me(x))throw new TypeError;return Z(N)||(N=Dt(N)),W(w,x,N)}r("hasOwnMetadata",S);function E(w,x,N){if(!me(x))throw new TypeError;return Z(N)||(N=Dt(N)),ee(w,x,N)}r("getMetadata",E);function R(w,x,N){if(!me(x))throw new TypeError;return Z(N)||(N=Dt(N)),he(w,x,N)}r("getOwnMetadata",R);function j(w,x){if(!me(w))throw new TypeError;return Z(x)||(x=Dt(x)),Me(w,x)}r("getMetadataKeys",j);function M(w,x){if(!me(w))throw new TypeError;return Z(x)||(x=Dt(x)),Qt(w,x)}r("getOwnMetadataKeys",M);function J(w,x,N){if(!me(x))throw new TypeError;if(Z(N)||(N=Dt(N)),!me(x))throw new TypeError;Z(N)||(N=Dt(N));var P=fs(x,N,!1);return Z(P)?!1:P.OrdinaryDeleteMetadata(w,x,N)}r("deleteMetadata",J);function le(w,x){for(var N=w.length-1;N>=0;--N){var P=w[N],Q=P(x);if(!Z(Q)&&!yt(Q)){if(!Hd(Q))throw new TypeError;x=Q}}return x}function re(w,x,N,P){for(var Q=w.length-1;Q>=0;--Q){var Re=w[Q],Ne=Re(x,N,P);if(!Z(Ne)&&!yt(Ne)){if(!me(Ne))throw new TypeError;P=Ne}}return P}function F(w,x,N){var P=W(w,x,N);if(P)return!0;var Q=ic(x);return yt(Q)?!1:F(w,Q,N)}function W(w,x,N){var P=fs(x,N,!1);return Z(P)?!1:Ud(P.OrdinaryHasOwnMetadata(w,x,N))}function ee(w,x,N){var P=W(w,x,N);if(P)return he(w,x,N);var Q=ic(x);if(!yt(Q))return ee(w,Q,N)}function he(w,x,N){var P=fs(x,N,!1);if(!Z(P))return P.OrdinaryGetOwnMetadata(w,x,N)}function $e(w,x,N,P){var Q=fs(N,P,!0);Q.OrdinaryDefineOwnMetadata(w,x,N,P)}function Me(w,x){var N=Qt(w,x),P=ic(w);if(P===null)return N;var Q=Me(P,x);if(Q.length<=0)return N;if(N.length<=0)return Q;for(var Re=new y,Ne=[],oe=0,V=N;oe<V.length;oe++){var K=V[oe],q=Re.has(K);q||(Re.add(K),Ne.push(K))}for(var X=0,ae=Q;X<ae.length;X++){var K=ae[X],q=Re.has(K);q||(Re.add(K),Ne.push(K))}return Ne}function Qt(w,x){var N=fs(w,x,!1);return N?N.OrdinaryOwnMetadataKeys(w,x):[]}function pe(w){if(w===null)return 1;switch(typeof w){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return w===null?1:6;default:return 6}}function Z(w){return w===void 0}function yt(w){return w===null}function jo(w){return typeof w=="symbol"}function me(w){return typeof w=="object"?w!==null:typeof w=="function"}function jv(w,x){switch(pe(w)){case 0:return w;case 1:return w;case 2:return w;case 3:return w;case 4:return w;case 5:return w}var N="string",P=Fd(w,i);if(P!==void 0){var Q=P.call(w,N);if(me(Q))throw new TypeError;return Q}return Dv(w)}function Dv(w,x){var N,P;{var Q=w.toString;if(Do(Q)){var P=Q.call(w);if(!me(P))return P}var N=w.valueOf;if(Do(N)){var P=N.call(w);if(!me(P))return P}}throw new TypeError}function Ud(w){return!!w}function Pv(w){return""+w}function Dt(w){var x=jv(w);return jo(x)?x:Pv(x)}function Vd(w){return Array.isArray?Array.isArray(w):w instanceof Object?w instanceof Array:Object.prototype.toString.call(w)==="[object Array]"}function Do(w){return typeof w=="function"}function Hd(w){return typeof w=="function"}function Lv(w){switch(pe(w)){case 3:return!0;case 4:return!0;default:return!1}}function oc(w,x){return w===x||w!==w&&x!==x}function Fd(w,x){var N=w[x];if(N!=null){if(!Do(N))throw new TypeError;return N}}function Wd(w){var x=Fd(w,a);if(!Do(x))throw new TypeError;var N=x.call(w);if(!me(N))throw new TypeError;return N}function Kd(w){return w.value}function Gd(w){var x=w.next();return x.done?!1:x}function qd(w){var x=w.return;x&&x.call(w)}function ic(w){var x=Object.getPrototypeOf(w);if(typeof w!="function"||w===m||x!==m)return x;var N=w.prototype,P=N&&Object.getPrototypeOf(N);if(P==null||P===Object.prototype)return x;var Q=P.constructor;return typeof Q!="function"||Q===w?x:Q}function Uv(){var w;!Z(g)&&typeof n.Reflect<"u"&&!(g in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(w=Fv(n.Reflect));var x,N,P,Q=new v,Re={registerProvider:Ne,getProvider:V,setProvider:q};return Re;function Ne(X){if(!Object.isExtensible(Re))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case w===X:break;case Z(x):x=X;break;case x===X:break;case Z(N):N=X;break;case N===X:break;default:P===void 0&&(P=new y),P.add(X);break}}function oe(X,ae){if(!Z(x)){if(x.isProviderFor(X,ae))return x;if(!Z(N)){if(N.isProviderFor(X,ae))return x;if(!Z(P))for(var ve=Wd(P);;){var xe=Gd(ve);if(!xe)return;var kt=Kd(xe);if(kt.isProviderFor(X,ae))return qd(ve),kt}}}if(!Z(w)&&w.isProviderFor(X,ae))return w}function V(X,ae){var ve=Q.get(X),xe;return Z(ve)||(xe=ve.get(ae)),Z(xe)&&(xe=oe(X,ae),Z(xe)||(Z(ve)&&(ve=new p,Q.set(X,ve)),ve.set(ae,xe))),xe}function K(X){if(Z(X))throw new TypeError;return x===X||N===X||!Z(P)&&P.has(X)}function q(X,ae,ve){if(!K(ve))throw new Error("Metadata provider not registered.");var xe=V(X,ae);if(xe!==ve){if(!Z(xe))return!1;var kt=Q.get(X);Z(kt)&&(kt=new p,Q.set(X,kt)),kt.set(ae,ve)}return!0}}function Vv(){var w;return!Z(g)&&me(n.Reflect)&&Object.isExtensible(n.Reflect)&&(w=n.Reflect[g]),Z(w)&&(w=Uv()),!Z(g)&&me(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,g,{enumerable:!1,configurable:!1,writable:!1,value:w}),w}function Hv(w){var x=new v,N={isProviderFor:function(K,q){var X=x.get(K);return Z(X)?!1:X.has(q)},OrdinaryDefineOwnMetadata:Ne,OrdinaryHasOwnMetadata:Q,OrdinaryGetOwnMetadata:Re,OrdinaryOwnMetadataKeys:oe,OrdinaryDeleteMetadata:V};return C.registerProvider(N),N;function P(K,q,X){var ae=x.get(K),ve=!1;if(Z(ae)){if(!X)return;ae=new p,x.set(K,ae),ve=!0}var xe=ae.get(q);if(Z(xe)){if(!X)return;if(xe=new p,ae.set(q,xe),!w.setProvider(K,q,N))throw ae.delete(q),ve&&x.delete(K),new Error("Wrong provider for target.")}return xe}function Q(K,q,X){var ae=P(q,X,!1);return Z(ae)?!1:Ud(ae.has(K))}function Re(K,q,X){var ae=P(q,X,!1);if(!Z(ae))return ae.get(K)}function Ne(K,q,X,ae){var ve=P(X,ae,!0);ve.set(K,q)}function oe(K,q){var X=[],ae=P(K,q,!1);if(Z(ae))return X;for(var ve=ae.keys(),xe=Wd(ve),kt=0;;){var zd=Gd(xe);if(!zd)return X.length=kt,X;var qv=Kd(zd);try{X[kt]=qv}catch(zv){try{qd(xe)}finally{throw zv}}kt++}}function V(K,q,X){var ae=P(q,X,!1);if(Z(ae)||!ae.delete(K))return!1;if(ae.size===0){var ve=x.get(q);Z(ve)||(ve.delete(X),ve.size===0&&x.delete(ve))}return!0}}function Fv(w){var x=w.defineMetadata,N=w.hasOwnMetadata,P=w.getOwnMetadata,Q=w.getOwnMetadataKeys,Re=w.deleteMetadata,Ne=new v,oe={isProviderFor:function(V,K){var q=Ne.get(V);return!Z(q)&&q.has(K)?!0:Q(V,K).length?(Z(q)&&(q=new y,Ne.set(V,q)),q.add(K),!0):!1},OrdinaryDefineOwnMetadata:x,OrdinaryHasOwnMetadata:N,OrdinaryGetOwnMetadata:P,OrdinaryOwnMetadataKeys:Q,OrdinaryDeleteMetadata:Re};return oe}function fs(w,x,N){var P=C.getProvider(w,x);if(!Z(P))return P;if(N){if(C.setProvider(w,x,A))return A;throw new Error("Illegal state.")}}function Wv(){var w={},x=[],N=(function(){function oe(V,K,q){this._index=0,this._keys=V,this._values=K,this._selector=q}return oe.prototype["@@iterator"]=function(){return this},oe.prototype[a]=function(){return this},oe.prototype.next=function(){var V=this._index;if(V>=0&&V<this._keys.length){var K=this._selector(this._keys[V],this._values[V]);return V+1>=this._keys.length?(this._index=-1,this._keys=x,this._values=x):this._index++,{value:K,done:!1}}return{value:void 0,done:!0}},oe.prototype.throw=function(V){throw this._index>=0&&(this._index=-1,this._keys=x,this._values=x),V},oe.prototype.return=function(V){return this._index>=0&&(this._index=-1,this._keys=x,this._values=x),{value:V,done:!0}},oe})(),P=(function(){function oe(){this._keys=[],this._values=[],this._cacheKey=w,this._cacheIndex=-2}return Object.defineProperty(oe.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),oe.prototype.has=function(V){return this._find(V,!1)>=0},oe.prototype.get=function(V){var K=this._find(V,!1);return K>=0?this._values[K]:void 0},oe.prototype.set=function(V,K){var q=this._find(V,!0);return this._values[q]=K,this},oe.prototype.delete=function(V){var K=this._find(V,!1);if(K>=0){for(var q=this._keys.length,X=K+1;X<q;X++)this._keys[X-1]=this._keys[X],this._values[X-1]=this._values[X];return this._keys.length--,this._values.length--,oc(V,this._cacheKey)&&(this._cacheKey=w,this._cacheIndex=-2),!0}return!1},oe.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=w,this._cacheIndex=-2},oe.prototype.keys=function(){return new N(this._keys,this._values,Q)},oe.prototype.values=function(){return new N(this._keys,this._values,Re)},oe.prototype.entries=function(){return new N(this._keys,this._values,Ne)},oe.prototype["@@iterator"]=function(){return this.entries()},oe.prototype[a]=function(){return this.entries()},oe.prototype._find=function(V,K){if(!oc(this._cacheKey,V)){this._cacheIndex=-1;for(var q=0;q<this._keys.length;q++)if(oc(this._keys[q],V)){this._cacheIndex=q;break}}return this._cacheIndex<0&&K&&(this._cacheIndex=this._keys.length,this._keys.push(V),this._values.push(void 0)),this._cacheIndex},oe})();return P;function Q(oe,V){return oe}function Re(oe,V){return V}function Ne(oe,V){return[oe,V]}}function Kv(){var w=(function(){function x(){this._map=new p}return Object.defineProperty(x.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),x.prototype.has=function(N){return this._map.has(N)},x.prototype.add=function(N){return this._map.set(N,N),this},x.prototype.delete=function(N){return this._map.delete(N)},x.prototype.clear=function(){this._map.clear()},x.prototype.keys=function(){return this._map.keys()},x.prototype.values=function(){return this._map.keys()},x.prototype.entries=function(){return this._map.entries()},x.prototype["@@iterator"]=function(){return this.keys()},x.prototype[a]=function(){return this.keys()},x})();return w}function Gv(){var w=16,x=d.create(),N=P();return(function(){function V(){this._key=P()}return V.prototype.has=function(K){var q=Q(K,!1);return q!==void 0?d.has(q,this._key):!1},V.prototype.get=function(K){var q=Q(K,!1);return q!==void 0?d.get(q,this._key):void 0},V.prototype.set=function(K,q){var X=Q(K,!0);return X[this._key]=q,this},V.prototype.delete=function(K){var q=Q(K,!1);return q!==void 0?delete q[this._key]:!1},V.prototype.clear=function(){this._key=P()},V})();function P(){var V;do V="@@WeakMap@@"+oe();while(d.has(x,V));return x[V]=!0,V}function Q(V,K){if(!s.call(V,N)){if(!K)return;Object.defineProperty(V,N,{value:d.create()})}return V[N]}function Re(V,K){for(var q=0;q<K;++q)V[q]=Math.random()*255|0;return V}function Ne(V){if(typeof Uint8Array=="function"){var K=new Uint8Array(V);return typeof crypto<"u"?crypto.getRandomValues(K):typeof msCrypto<"u"?msCrypto.getRandomValues(K):Re(K,V),K}return Re(new Array(V),V)}function oe(){var V=Ne(w);V[6]=V[6]&79|64,V[8]=V[8]&191|128;for(var K="",q=0;q<w;++q){var X=V[q];(q===4||q===6||q===8)&&(K+="-"),X<16&&(K+="0"),K+=X.toString(16).toLowerCase()}return K}}function ac(w){return w.__=void 0,delete w.__,w}})})(t||(t={})),ip}zS();const YS="[object ArrayBuffer]";class U{static isArrayBuffer(e){return Object.prototype.toString.call(e)===YS}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,r){if(e.constructor===r)return e;if(this.isArrayBuffer(e))return new r(e);if(this.isArrayBufferView(e))return new r(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,r){const n=U.toUint8Array(e),s=U.toUint8Array(r);if(n.length!==s.byteLength)return!1;for(let o=0;o<n.length;o++)if(n[o]!==s[o])return!1;return!0}static concat(...e){let r;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?r=e[0]:e[e.length-1]instanceof Function?r=e.slice(0,e.length-1):r=e;let n=0;for(const i of r)n+=i.byteLength;const s=new Uint8Array(n);let o=0;for(const i of r){const a=this.toUint8Array(i);s.set(a,o),o+=a.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}}const kc="string",XS=/^[0-9a-f\s]+$/i,JS=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ZS=/^[a-zA-Z0-9-_]+$/;class cp{static fromString(e){const r=unescape(encodeURIComponent(e)),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n.buffer}static toString(e){const r=U.toUint8Array(e);let n="";for(let o=0;o<r.length;o++)n+=String.fromCharCode(r[o]);return decodeURIComponent(escape(n))}}class Pt{static toString(e,r=!1){const n=U.toArrayBuffer(e),s=new DataView(n);let o="";for(let i=0;i<n.byteLength;i+=2){const a=s.getUint16(i,r);o+=String.fromCharCode(a)}return o}static fromString(e,r=!1){const n=new ArrayBuffer(e.length*2),s=new DataView(n);for(let o=0;o<e.length;o++)s.setUint16(o*2,e.charCodeAt(o),r);return n}}class Y{static isHex(e){return typeof e===kc&&XS.test(e)}static isBase64(e){return typeof e===kc&&JS.test(e)}static isBase64Url(e){return typeof e===kc&&ZS.test(e)}static ToString(e,r="utf8"){const n=U.toUint8Array(e);switch(r.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Pt.toString(n,!0);case"utf16":case"utf16be":return Pt.toString(n);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromString(e,r="utf8"){if(!e)return new ArrayBuffer(0);switch(r.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Pt.fromString(e,!0);case"utf16":case"utf16be":return Pt.fromString(e);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToBase64(e){const r=U.toUint8Array(e);if(typeof btoa<"u"){const n=this.ToString(r,"binary");return btoa(n)}else return Buffer.from(r).toString("base64")}static FromBase64(e){const r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!Y.isBase64(r))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(r)):new Uint8Array(Buffer.from(r,"base64")).buffer}static FromBase64Url(e){const r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!Y.isBase64Url(r))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(r.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,r=Y.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.FromBinary(e);case"utf8":return cp.fromString(e);case"utf16":case"utf16be":return Pt.fromString(e);case"utf16le":case"usc2":return Pt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToUtf8String(e,r=Y.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.ToBinary(e);case"utf8":return cp.toString(e);case"utf16":case"utf16be":return Pt.toString(e);case"utf16le":case"usc2":return Pt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromBinary(e){const r=e.length,n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e.charCodeAt(s);return n.buffer}static ToBinary(e){const r=U.toUint8Array(e);let n="";for(let s=0;s<r.length;s++)n+=String.fromCharCode(r[s]);return n}static ToHex(e){const r=U.toUint8Array(e);let n="";const s=r.length;for(let o=0;o<s;o++){const i=r[o];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!Y.isHex(r))throw new TypeError("Argument 'hexString' is not HEX encoded");r.length%2&&(r=`0${r}`);const n=new Uint8Array(r.length/2);for(let s=0;s<r.length;s=s+2){const o=r.slice(s,s+2);n[s/2]=parseInt(o,16)}return n.buffer}static ToUtf16String(e,r=!1){return Pt.toString(e,r)}static FromUtf16String(e,r=!1){return Pt.fromString(e,r)}static Base64Padding(e){const r=4-e.length%4;if(r<4)for(let n=0;n<r;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}}Y.DEFAULT_UTF8_ENCODING="utf8";function QS(...t){const e=t.map(s=>s.byteLength).reduce((s,o)=>s+o),r=new Uint8Array(e);let n=0;return t.map(s=>new Uint8Array(s)).forEach(s=>{for(const o of s)r[n++]=o}),r.buffer}function ek(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;const r=new Uint8Array(t),n=new Uint8Array(e);for(let s=0;s<t.byteLength;s++)if(r[s]!==n[s])return!1;return!0}function Hn(t,e){let r=0;if(t.length===1)return t[0];for(let n=t.length-1;n>=0;n--)r+=t[t.length-1-n]*Math.pow(2,e*n);return r}function Zr(t,e,r=-1){const n=r;let s=t,o=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(t<i){let c;if(n<0)c=new ArrayBuffer(a),o=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),o=n}const u=new Uint8Array(c);for(let l=a-1;l>=0;l--){const d=Math.pow(2,l*e);u[o-l-1]=Math.floor(s/d),s-=u[o-l-1]*d}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function Xc(...t){let e=0,r=0;for(const o of t)e+=o.length;const n=new ArrayBuffer(e),s=new Uint8Array(n);for(const o of t)s.set(o,r),r+=o.length;return s}function Ny(){const t=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const a=t[0]===255&&t[1]&128,c=t[0]===0&&(t[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}const e=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)r[a]=0;r[0]=t[0]&128;const n=Hn(r,8),s=new ArrayBuffer(this.valueHex.byteLength),o=new Uint8Array(s);for(let a=0;a<this.valueHex.byteLength;a++)o[a]=t[a];return o[0]&=127,Hn(o,8)-n}function tk(t){const e=t<0?t*-1:t;let r=128;for(let n=1;n<8;n++){if(e<=r){if(t<0){const i=r-e,a=Zr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let s=Zr(e,8,n),o=new Uint8Array(s);if(o[0]&128){const i=s.slice(0),a=new Uint8Array(i);s=new ArrayBuffer(s.byteLength+1),o=new Uint8Array(s);for(let c=0;c<i.byteLength;c++)o[c+1]=a[c];o[0]=0}return s}r*=Math.pow(2,8)}return new ArrayBuffer(0)}function rk(t,e){if(t.byteLength!==e.byteLength)return!1;const r=new Uint8Array(t),n=new Uint8Array(e);for(let s=0;s<r.length;s++)if(r[s]!==n[s])return!1;return!0}function ct(t,e){const r=t.toString(10);if(e<r.length)return"";const n=e-r.length,s=Array.from({length:n});for(let i=0;i<n;i++)s[i]="0";return s.join("").concat(r)}function vi(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function zl(t){let e=0,r=0;for(let s=0;s<t.length;s++){const o=t[s];e+=o.byteLength}const n=new Uint8Array(e);for(let s=0;s<t.length;s++){const o=t[s];n.set(new Uint8Array(o),r),r+=o.byteLength}return n.buffer}function gr(t,e,r,n){return e instanceof Uint8Array?e.byteLength?r<0?(t.error="Wrong parameter: inputOffset less than zero",!1):n<0?(t.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-r-n<0?(t.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(t.error="Wrong parameter: inputBuffer has zero length",!1):(t.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class ua{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return zl(this.items)}}const hs=[new Uint8Array([1])],up="0123456789",xc="name",lp="valueHexView",nk="isHexOnly",sk="idBlock",ok="tagClass",ik="tagNumber",ak="isConstructed",ck="fromBER",uk="toBER",lk="local",Je="",Yt=new ArrayBuffer(0),la=new Uint8Array(0),eo="EndOfContent",Ty="OCTET STRING",By="BIT STRING";function Xt(t){var e;return e=class extends t{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var s;super(...n);const o=n[0]||{};this.isHexOnly=(s=o.isHexOnly)!==null&&s!==void 0?s:!1,this.valueHexView=o.valueHex?U.toUint8Array(o.valueHex):la}fromBER(n,s,o,i){const a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!gr(this,a,s,o))return-1;const c=s+o;return this.valueHexView=a.subarray(s,c),this.valueHexView.length?(this.blockLength=o,c):(this.warnings.push("Zero buffer length"),s)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Yt)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Y.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}class yn{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:r=Je,warnings:n=[],valueBeforeDecode:s=la}={}){this.blockLength=e,this.error=r,this.warnings=n,this.valueBeforeDecodeView=U.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Y.ToHex(this.valueBeforeDecodeView)}}}yn.NAME="baseBlock";class Fe extends yn{fromBER(e,r,n,s){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Fe.NAME="valueBlock";class $y extends Xt(yn){constructor({idBlock:e={}}={}){var r,n,s,o;super(),e?(this.isHexOnly=(r=e.isHexOnly)!==null&&r!==void 0?r:!1,this.valueHexView=e.valueHex?U.toUint8Array(e.valueHex):la,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(s=e.tagNumber)!==null&&s!==void 0?s:-1,this.isConstructed=(o=e.isConstructed)!==null&&o!==void 0?o:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let r=0;switch(this.tagClass){case 1:r|=0;break;case 2:r|=64;break;case 3:r|=128;break;case 4:r|=192;break;default:return this.error="Unknown tag class",Yt}if(this.isConstructed&&(r|=32),this.tagNumber<31&&!this.isHexOnly){const s=new Uint8Array(1);if(!e){let o=this.tagNumber;o&=31,r|=o,s[0]=r}return s.buffer}if(!this.isHexOnly){const s=Zr(this.tagNumber,7),o=new Uint8Array(s),i=s.byteLength,a=new Uint8Array(i+1);if(a[0]=r|31,!e){for(let c=0;c<i-1;c++)a[c+1]=o[c]|128;a[i]=o[i-1]}return a.buffer}const n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=r|31,!e){const s=this.valueHexView;for(let o=0;o<s.length-1;o++)n[o+1]=s[o]|128;n[this.valueHexView.byteLength]=s[s.length-1]}return n.buffer}fromBER(e,r,n){const s=U.toUint8Array(e);if(!gr(this,s,r,n))return-1;const o=s.subarray(r,r+n);if(o.length===0)return this.error="Zero buffer length",-1;switch(o[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(o[0]&32)===32,this.isHexOnly=!1;const a=o[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){const l=c+1;if(l>=o.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(o[l]&128)===0)break}this.blockLength=c+1;const u=this.valueHexView=new Uint8Array(c);for(let l=0;l<c;l++)u[l]=o[l+1]&127;this.blockLength<=9?this.tagNumber=Hn(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return r+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}$y.NAME="identificationBlock";class Ry extends yn{constructor({lenBlock:e={}}={}){var r,n,s;super(),this.isIndefiniteForm=(r=e.isIndefiniteForm)!==null&&r!==void 0?r:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(s=e.length)!==null&&s!==void 0?s:0}fromBER(e,r,n){const s=U.toUint8Array(e);if(!gr(this,s,r,n))return-1;const o=s.subarray(r,r+n);if(o.length===0)return this.error="Zero buffer length",-1;if(o[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=o[0]===128,this.isIndefiniteForm)return this.blockLength=1,r+this.blockLength;if(this.longFormUsed=!!(o[0]&128),this.longFormUsed===!1)return this.length=o[0],this.blockLength=1,r+this.blockLength;const i=o[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>o.length)return this.error="End of input reached before message was fully decoded",-1;const a=r+1,c=s.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Hn(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,r+this.blockLength}toBER(e=!1){let r,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return r=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(r),n[0]=128),r;if(this.longFormUsed){const s=Zr(this.length,8);if(s.byteLength>127)return this.error="Too big length",Yt;if(r=new ArrayBuffer(s.byteLength+1),e)return r;const o=new Uint8Array(s);n=new Uint8Array(r),n[0]=s.byteLength|128;for(let i=0;i<s.byteLength;i++)n[i+1]=o[i];return r}return r=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(r),n[0]=this.length),r}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}Ry.NAME="lengthBlock";const H={};class _e extends yn{constructor({name:e=Je,optional:r=!1,primitiveSchema:n,...s}={},o){super(s),this.name=e,this.optional=r,n&&(this.primitiveSchema=n),this.idBlock=new $y(s),this.lenBlock=new Ry(s),this.valueBlock=o?new o(s):new Fe(s)}fromBER(e,r,n,s){const o=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,s);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,r){const n=r||new ua;r||_y(this);const s=this.idBlock.toBER(e);if(n.write(s),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{const o=this.valueBlock.toBER(e);this.lenBlock.length=o.byteLength;const i=this.lenBlock.toBER(e);n.write(i),n.write(o)}return r?Yt:n.final()}toJSON(){const e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():Y.ToHex(this.toBER())}onAsciiEncoding(){const e=this.constructor.NAME,r=Y.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${r}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;const r=this.toBER(),n=e.toBER();return rk(r,n)}}_e.NAME="BaseBlock";function _y(t){var e;if(t instanceof H.Constructed)for(const r of t.valueBlock.value)_y(r)&&(t.lenBlock.isIndefiniteForm=!0);return!!(!((e=t.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}class Yl extends _e{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Je,...r}={},n){super(r,n),e&&this.fromString(e)}fromBER(e,r,n){const s=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return s===-1?(this.error=this.valueBlock.error,s):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}Yl.NAME="BaseStringBlock";class My extends Xt(Fe){constructor({isHexOnly:e=!0,...r}={}){super(r),this.isHexOnly=e}}My.NAME="PrimitiveValueBlock";var jy;class vo extends _e{constructor(e={}){super(e,My),this.idBlock.isConstructed=!1}}jy=vo;H.Primitive=jy;vo.NAME="PRIMITIVE";const Dy=100,Py=1e4,Ly=16*1024*1024,dk="Maximum ASN.1 nesting depth exceeded",fk="Maximum ASN.1 node count exceeded",pk="Maximum ASN.1 content length exceeded";function bo(t={}){var e,r,n;return{depth:0,maxDepth:(e=t.maxDepth)!==null&&e!==void 0?e:Dy,nodesCount:0,maxNodes:(r=t.maxNodes)!==null&&r!==void 0?r:Py,maxContentLength:(n=t.maxContentLength)!==null&&n!==void 0?n:Ly}}function hk(t){const e=new _e({},Fe);return e.error=t,{offset:-1,result:e}}function mk(t){if(t.nodesCount+=1,t.nodesCount>t.maxNodes)return fk}function yk(t,e){if(t>e.maxContentLength)return pk}function Xl(t,e,r,n){const s=n.depth+1;if(s>n.maxDepth)return hk(dk);n.depth=s;try{return da(t,e,r,n)}finally{n.depth-=1}}function gk(t,e){if(t instanceof e)return t;const r=new e;return r.idBlock=t.idBlock,r.lenBlock=t.lenBlock,r.warnings=t.warnings,r.valueBeforeDecodeView=t.valueBeforeDecodeView,r}function da(t,e=0,r=t.length,n=bo()){const s=e;let o=new _e({},Fe);const i=new yn;if(!gr(i,t,e,r))return o.error=i.error,{offset:-1,result:o};if(!t.subarray(e,e+r).length)return o.error="Zero buffer length",{offset:-1,result:o};const c=mk(n);if(c)return o.error=c,{offset:-1,result:o};let u=o.idBlock.fromBER(t,e,r);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),u===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=u,r-=o.idBlock.blockLength,u=o.lenBlock.fromBER(t,e,r),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),u===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};e=u,r-=o.lenBlock.blockLength;const l=o.lenBlock.isIndefiniteForm?r:o.lenBlock.length,d=yk(l,n);if(d)return o.error=d,{offset:-1,result:o};if(!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let m=_e;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};m=H.EndOfContent;break;case 1:m=H.Boolean;break;case 2:m=H.Integer;break;case 3:m=H.BitString;break;case 4:m=H.OctetString;break;case 5:m=H.Null;break;case 6:m=H.ObjectIdentifier;break;case 10:m=H.Enumerated;break;case 12:m=H.Utf8String;break;case 13:m=H.RelativeObjectIdentifier;break;case 14:m=H.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:m=H.Sequence;break;case 17:m=H.Set;break;case 18:m=H.NumericString;break;case 19:m=H.PrintableString;break;case 20:m=H.TeletexString;break;case 21:m=H.VideotexString;break;case 22:m=H.IA5String;break;case 23:m=H.UTCTime;break;case 24:m=H.GeneralizedTime;break;case 25:m=H.GraphicString;break;case 26:m=H.VisibleString;break;case 27:m=H.GeneralString;break;case 28:m=H.UniversalString;break;case 29:m=H.CharacterString;break;case 30:m=H.BmpString;break;case 31:m=H.DATE;break;case 32:m=H.TimeOfDay;break;case 33:m=H.DateTime;break;case 34:m=H.Duration;break;default:{const p=o.idBlock.isConstructed?new H.Constructed:new H.Primitive;p.idBlock=o.idBlock,p.lenBlock=o.lenBlock,p.warnings=o.warnings,o=p}}break;default:m=o.idBlock.isConstructed?H.Constructed:H.Primitive}return o=gk(o,m),u=o.fromBER(t,e,l,n),o.valueBeforeDecodeView=t.subarray(s,s+o.blockLength),{offset:u,result:o}}function _n(t,e={}){if(!t.byteLength){const r=new _e({},Fe);return r.error="Input buffer has zero length",{offset:-1,result:r}}return da(U.toUint8Array(t).slice(),0,t.byteLength,bo(e))}function vk(t,e){return t?1:e}class Cr extends Fe{constructor({value:e=[],isIndefiniteForm:r=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=r}fromBER(e,r,n,s){const o=U.toUint8Array(e),i=s??bo();if(!gr(this,o,r,n))return-1;if(this.valueBeforeDecodeView=o.subarray(r,r+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),r;let a=r;for(;vk(this.isIndefiniteForm,n)>0;){const c=Xl(o,a,n,i);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===eo)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===eo?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,r){const n=r||new ua;for(let s=0;s<this.value.length;s++)this.value[s].toBER(e,n);return r?Yt:n.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const r of this.value)e.value.push(r.toJSON());return e}}Cr.NAME="ConstructedValueBlock";var Uy;class ze extends _e{constructor(e={}){super(e,Cr),this.idBlock.isConstructed=!0}fromBER(e,r,n,s){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const o=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,s);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){const e=[];for(const n of this.valueBlock.value)e.push(n.toString("ascii").split(`
84
- `).map(s=>` ${s}`).join(`
99
+ ORDER BY occurred_at, id`);for(const m of u){const p=m.indexOf(":");if(p<0)continue;const h=l.all(m.slice(0,p),m.slice(p+1));for(const v of h)d.push(e(v))}return d}}}function Hy(t){const[e,r,n]=va(t).map(oS);return{db:e,wal:r,shm:n,total:e+r+n}}function oS(t){try{return fa(t).size}catch{return 0}}function fi(t,e,r){if(t!=null)try{const n=JSON.parse(String(t));if(n&&typeof n=="object")return n;e&&r?.(e);return}catch{e&&r?.(e);return}}function Fy(t,e){const r=t,n=e?o=>e(o,String(r.id)):void 0;return{id:String(r.id),source:{id:String(r.source_id),instance:String(r.source_instance)},occurredAt:Number(r.occurred_at),observedAt:Number(r.observed_at),clock:r.clock,kind:r.kind,subject:{type:r.subject_type,id:String(r.subject_id)},core:fi(r.core,"core",n),attrs:fi(r.attrs,"attrs",n),basis:r.basis,assumption:r.assumption?String(r.assumption):void 0,stratum:r.stratum?r.stratum:void 0,provenance:fi(r.provenance,"provenance",n)}}const fp={tokens:"unknown",requests:"unknown",toolInteractions:"unknown",toolErrors:"unknown",retries:"unknown",waits:"unknown",model:"unknown",context:"unknown",outcome:"unknown"};function Wy(t){const e=new Map;for(const s of t.declarations)s.kind==="began"&&e.set(`${s.subject.type}:${s.subject.id}`,s);const r=[...t.state.executions.values()].map(s=>sS(s,t,e)).sort((s,i)=>s.start.at-i.start.at||s.ref.localeCompare(i.ref)),n=new Set(r.map(s=>s.ref)),o=[...t.state.sessions.values()].map(s=>({ref:Cr("session",s.id),executionRefs:s.executionIds.map(i=>Cr("execution",i)).filter(i=>n.has(i)).sort(),spawnedBy:s.parentId?it({ref:Cr("session",s.parentId)}):un("no parent session was reported")})).filter(s=>s.executionRefs.length>0).sort((s,i)=>s.ref.localeCompare(i.ref));return{experimental:!0,window:{from:t.from,to:t.to},executions:r,sessions:o,summary:dS(r,o,t.from,t.to,rd(t.state))}}function sS(t,e,r){const n=r.get(`execution:${t.id}`),o=n?.source.id,s=o?e.capabilities.get(o)??fp:fp,i=e.state.sessions.get(t.sessionId),a=e.state.machines.get(t.machineId),c=t.status==="completed"||t.status==="failed",u=aS(n?.occurredAt??t.startedAt,n?.basis??t.startBasis),d=e.relationships.filter(h=>h.kind==="ran-as"&&(h.from.type==="execution"&&h.from.id===t.id&&h.to.type==="process"||h.to.type==="execution"&&h.to.id===t.id&&h.from.type==="process")).map(h=>{const v=h.from.type==="process"?h.from:h.to;return{kind:"ran-as",target:{type:"process",ref:Cr("process",v.id)},evidence:iS(h.basis),...h.basis==="inferred"?{qualification:"resolved from overlapping identity claims"}:{}}}).sort((h,v)=>h.target.ref.localeCompare(v.target.ref)),l=i?.context,m=t.model??i?.model,p={current:t.status==="waiting",...t.waitReason?{reason:t.waitReason}:{},count:t.waits.length+(t.waitingSince===void 0?0:1),durationMs:t.waitingMs+(t.waitingSince===void 0?0:Math.max(0,e.to-t.waitingSince))};return{ref:Cr("execution",t.id),observer:o??"unknown-observer",sessionRef:Cr("session",t.sessionId),machine:t.machineId?it({ref:Cr("machine",t.machineId),...a?{kind:a.kind}:{}}):un("no machine was reported"),context:l?fu(s.context,{ref:Cr("context",l)},"context"):pi(s.context,"context"),executor:t.executor&&t.executor!=="unknown"?it(t.executor):un("no executor was reported"),model:m?fu(s.model,m,"model"):pi(s.model,"model"),start:u,end:t.endedAt===void 0?mr(e.to,"the execution is open; query time is an elapsed wall bound, not a terminal end"):t.endBasis==="inferred"?hs(t.endedAt,"the terminal bound was inferred by its observer"):it(t.endedAt),lifecycle:cS(t),outcome:uS(t,s.outcome),measures:{tokens:{input:Or(t,Z.tokensInput,s.tokens,c,!1,"token input"),output:Or(t,Z.tokensOutput,s.tokens,c,!1,"token output"),cacheRead:Or(t,Z.tokensCacheRead,s.tokens,c,!1,"cache-read tokens"),reasoning:Or(t,Z.tokensReasoning,s.tokens,c,!1,"reasoning tokens"),total:Ky(jr(t.measures),s.tokens,c,!1,"token total")},requests:Or(t,Z.steps,s.requests,c,!0,"requests"),toolInteractions:Or(t,Z.interactions,s.toolInteractions,c,!0,"tool interactions"),toolErrors:Or(t,Z.errors,s.toolErrors,c,!0,"tool errors"),retries:Or(t,Z.retries,s.retries,c,!0,"retries")},wait:lS(p,s.waits,c),failure:t.status==="failed"?it("execution-failed"):c?s.outcome==="supported"?it("none"):pi(s.outcome,"failure state"):Ht("the execution is not terminal"),depth:t.depth,relationships:d}}function Cr(t,e){const r=fo("sha256").update(`057-activity\0${t}\0${e}`).digest("hex").slice(0,16);return`${t}_${r}`}function iS(t){return t==="inferred"?"inferred":"observed"}function aS(t,e){return e==="inferred"?{at:t,evidence:"inferred",qualification:"the observer inferred this temporal bound"}:e===void 0?{at:t,evidence:"inferred",qualification:"a legacy record did not declare its timing basis"}:{at:t,evidence:"observed"}}function cS(t){return t.status==="waiting"?{state:"waiting",evidence:"observed"}:t.status==="running"?{state:"running",evidence:"observed"}:t.status==="idle"?{state:"idle",evidence:"inferred",qualification:"no activity was observed for the idle threshold"}:{state:"terminal",evidence:t.endBasis==="inferred"?"inferred":"observed",...t.endBasis==="inferred"?{qualification:"the observer inferred the terminal bound"}:{}}}function uS(t,e){if(t.status!=="completed"&&t.status!=="failed")return Ht("the execution is not terminal");const r=t.outcome==="error"?"failed":t.outcome==="interrupted"?"interrupted":t.outcome==="completed"?"completed":void 0;return r?t.endBasis==="inferred"?hs(r,"the terminal outcome follows an inferred terminal bound"):fu(e,r,"outcome"):pi(e,"outcome")}function Or(t,e,r,n,o,s){return Ky(vt(t.measures,e),r,n,o,s)}function Ky(t,e,r,n,o){return e==="unsupported"?In(`this observer does not report ${o}`):e==="unknown"?Ht(`coverage for ${o} is not declared`):e==="partial"?mr(t,`this observer reports ${o} only partially`):r?t!==void 0?it(t):n?it(0):un(`${o} was not present in this execution`):mr(t,`${o} may still increase while the execution is active`)}function lS(t,e,r){return e==="unsupported"?In("this observer does not report explicit waits"):e==="unknown"?Ht("wait coverage is not declared"):e==="partial"?mr(t,"this observer reports explicit waits only partially"):!r||t.current?mr(t,"an explicit wait may still be open"):it(t)}function fu(t,e,r){return t==="supported"?it(e):t==="partial"?mr(e,`this observer reports ${r} only partially`):t==="unsupported"?In(`this observer does not report ${r}`):Ht(`coverage for ${r} is not declared`)}function pi(t,e){return t==="supported"?un(`${e} was not present in this execution`):t==="partial"?mr(void 0,`this observer reports ${e} only partially`):t==="unsupported"?In(`this observer does not report ${e}`):Ht(`coverage for ${e} is not declared`)}function it(t){return{state:"observed",value:t}}function hs(t,e){return{state:"inferred",value:t,qualification:e}}function mr(t,e){return t===void 0?{state:"partial",qualification:e}:{state:"partial",value:t,qualification:e}}function In(t){return{state:"unsupported",qualification:t}}function un(t){return{state:"not-observed",qualification:t}}function Ht(t){return{state:"unknown",qualification:t}}function dS(t,e,r,n,o){const s=t.map(h=>({start:Math.max(r,h.start.at),end:Math.min(n,yt(h.end)??n),inferred:h.start.evidence==="inferred"||h.end.state==="inferred",partial:h.end.state!=="observed"&&h.end.state!=="inferred"})),i=rn(s.map(h=>h.partial?"partial":h.inferred?"inferred":"observed")),a=mp(s),c=yp(s),u=t.filter(h=>h.lifecycle.state==="terminal"),d=u.flatMap(h=>{const v=yt(h.end);return v===void 0?[]:[{start:Math.max(r,h.start.at),end:Math.min(n,v),inferred:h.start.evidence==="inferred"||h.end.state==="inferred"}]}),l=rn(u.map(h=>yt(h.end)===void 0?"unknown":h.start.evidence==="inferred"||h.end.state==="inferred"?"inferred":"observed")),m=mp(d),p=rn(t.map(h=>h.lifecycle.state==="terminal"?"inferred":"partial"));return{executions:t.length,sessions:e.length,openExecutions:t.length-u.length,terminalExecutions:u.length,runningNow:t.filter(h=>h.lifecycle.state==="running").length,waitingNow:Pn(t.map(fS)),idleNow:t.filter(h=>h.lifecycle.state==="idle").length,completed:jc(u,"completed"),failed:jc(u,"failed"),interrupted:jc(u,"interrupted"),inFlight:{totalMs:pt(o.timeInFlight.value,p),openContributionMs:pt(Math.max(0,o.timeInFlight.value-m),p),parallelMs:pt(o.parallelTime.value,p),peak:pt({peak:o.peakConcurrency.value,at:o.peakConcurrency.value>0?o.peakConcurrencyAt.value:null},p),assumption:my},executionWallIntervalMs:pt(a,i),peakExecutionConcurrency:pt(c,i),executionDuration:Mc(t.map(h=>{const v=yt(h.end)??n,g=Math.max(0,v-h.start.at);return h.end.state!=="observed"&&h.end.state!=="inferred"?mr(g,"elapsed wall duration for an open execution"):h.start.evidence==="inferred"||h.end.state==="inferred"?hs(g,"one or more execution bounds were inferred"):it(g)})),terminalExecutionDuration:Mc(u.map(h=>{const v=yt(h.end);if(v===void 0)return Ht("the terminal execution has no usable end bound");const g=Math.max(0,v-h.start.at);return h.start.evidence==="inferred"||h.end.state==="inferred"?hs(g,"one or more execution bounds were inferred"):it(g)})),terminalExecutionIntervalMs:pt(m,l),overlappingTerminalIntervalMs:pt(mS(d),l),peakTerminalConcurrency:pt(yp(d),l),sessionExecutionCount:Mc(e.map(h=>it(h.executionRefs.length))),tokens:Pn(t.map(h=>h.measures.tokens.total)),toolInteractions:Pn(t.map(h=>h.measures.toolInteractions)),toolErrors:Pn(t.map(h=>h.measures.toolErrors)),waits:pS(t.map(h=>h.wait)),usageByModel:hS(t),executionsWithoutModel:t.filter(h=>yt(h.model)===void 0).length,modelMix:hp(t,h=>pp(h.model)),executorMix:hp(t,h=>pp(h.executor))}}function yt(t){return"value"in t?t.value:void 0}function pp(t){return yt(t)??`[${t.state}]`}function rn(t){const e={records:t.length,observed:0,inferred:0,partial:0,unsupported:0,notObserved:0,unknown:0};for(const r of t)r==="not-observed"?e.notObserved++:e[r]++;return e}function pt(t,e){return e.partial+e.unsupported+e.notObserved+e.unknown>0?{state:"partial",value:t,qualification:"coverage is incomplete",coverage:e}:e.inferred>0?{state:"inferred",value:t,qualification:"one or more bounds were inferred",coverage:e}:{state:"observed",value:t,coverage:e}}function Pn(t){const e=rn(t.map(o=>o.state));let r=0,n=0;for(const o of t){const s=yt(o);s!==void 0&&(r+=s,n++)}return n>0?pt(r,e):e.records>0&&e.unsupported===e.records?{...In("no observer supports this measure"),coverage:e}:e.records>0&&e.notObserved===e.records?{...un("no value was observed"),coverage:e}:{...Ht("no usable value was observed"),coverage:e}}function Mc(t){const e=rn(t.map(n=>n.state)),r=t.map(yt).filter(n=>n!==void 0).sort((n,o)=>n-o);return r.length===0?{...Ht("no usable duration samples were observed"),coverage:e}:pt({samples:r.length,minimum:r[0],median:_c(r,.5),p75:_c(r,.75),p90:_c(r,.9),maximum:r[r.length-1]},e)}function _c(t,e){const r=(t.length-1)*e,n=Math.floor(r),o=Math.ceil(r);return n===o?t[n]:t[n]+(t[o]-t[n])*(r-n)}function fS(t){const e=yt(t.wait);return Gy(t.wait,e?.current?1:0)}function jc(t,e){return t.length===0?pt(0,rn([])):Pn(t.map(r=>{const n=yt(r.outcome);return Gy(r.outcome,n===e?1:0)}))}function Gy(t,e){switch(t.state){case"observed":return it(e);case"inferred":return hs(e,t.qualification);case"partial":return mr("value"in t?e:void 0,t.qualification);case"unsupported":return In(t.qualification);case"not-observed":return un(t.qualification);case"unknown":return Ht(t.qualification)}}function pS(t){const e=rn(t.map(o=>o.state));let r=0;const n={count:0,durationMs:0,openNow:0};for(const o of t){const s=yt(o);s&&(r++,n.count+=s.count,n.durationMs+=s.durationMs,s.current&&n.openNow++)}return r>0?pt(n,e):e.unsupported===e.records?{...In("no observer reports explicit waits"),coverage:e}:{...Ht("no usable wait value was observed"),coverage:e}}function hS(t){const e=new Map;for(const r of t){const n=yt(r.model);if(!n)continue;const o=e.get(n)??[];o.push(r.measures.tokens.total),e.set(n,o)}return[...e.entries()].map(([r,n])=>({model:r,executions:n.length,tokens:Pn(n)})).sort((r,n)=>n.executions-r.executions||r.model.localeCompare(n.model))}function hp(t,e){const r=new Map;for(const n of t){const o=e(n);r.set(o,(r.get(o)??0)+1)}return[...r.entries()].map(([n,o])=>({key:n,executions:o})).sort((n,o)=>o.executions-n.executions||n.key.localeCompare(o.key))}function mp(t){const e=t.filter(s=>s.end>s.start).map(s=>({start:s.start,end:s.end})).sort((s,i)=>s.start-i.start||s.end-i.end);let r=0,n,o=0;for(const s of e)n===void 0?(n=s.start,o=s.end):s.start<=o?o=Math.max(o,s.end):(r+=o-n,n=s.start,o=s.end);return r+(n===void 0?0:o-n)}function yp(t){const e=[];for(const s of t)s.end<=s.start||e.push({at:s.start,delta:1},{at:s.end,delta:-1});e.sort((s,i)=>s.at-i.at||s.delta-i.delta);let r=0,n=0,o=null;for(const s of e)r+=s.delta,r>n&&(n=r,o=s.at);return{peak:n,at:o}}function mS(t){const e=[];for(const s of t)s.end<=s.start||e.push({at:s.start,delta:1},{at:s.end,delta:-1});e.sort((s,i)=>s.at-i.at||s.delta-i.delta);let r=0,n,o=0;for(const s of e)n!==void 0&&r>=2&&(o+=s.at-n),r+=s.delta,n=s.at;return o}function ms(t,e){const r=t.window,n=It(e.continuity),o=e.continuity.state==="observed"&&n!==void 0&&n.from<=r.from&&n.to>=r.to,s=e.retention.state==="within-retention"||e.retention.state==="retained-indefinitely",i=t.executions.length,a=[];let c,u;s?o?(c="observed",u="comparable"):i>0?(c="partially-observed",u="partially-comparable",a.push("execution records are present, but historical observation continuity is unknown")):(c="unknown",u="not-comparable",a.push("zero execution records cannot distinguish a quiet period from an unobserved period")):(c="not-sufficiently-observed",u="not-comparable",a.push("the requested period is not wholly inside semantic retention"));const d=t.executions.map(g=>g.start.at),l=t.executions.map(g=>It(g.end)??g.start.at),m=i>0?dr({from:Math.min(...d),to:Math.max(...l)}):hr("no execution records establish an observed span"),p=new Map;for(const g of t.executions){const I=p.get(g.observer)??[];I.push(g),p.set(g.observer,I)}const h=[...p.entries()].map(([g,I])=>({source:g,executionRecords:I.length,firstExecutionAt:Math.min(...I.map(N=>N.start.at)),lastExecutionAt:Math.max(...I.map(N=>N.start.at)),capabilities:e.capabilities.get(g)??kS()})).sort((g,I)=>I.executionRecords-g.executionRecords||g.source.localeCompare(I.source)),v=[Co("tokens",t.summary.tokens),Co("tool-interactions",t.summary.toolInteractions),Co("tool-errors",t.summary.toolErrors),Co("waits",t.summary.waits),Dc("outcomes",t.executions.map(g=>g.outcome)),Co("bounds",SS(t.executions)),Dc("model",t.executions.map(g=>g.model)),Dc("executor",t.executions.map(g=>g.executor))];return{experimental:!0,period:r,observation:c,recordPresence:i>0?"present":"none",executionRecords:i,sessionRecords:t.sessions.length,continuity:e.continuity,observationGaps:o?dr([]):hr("historical observation gaps are not retained"),unprojectedSourceWork:hr("observers do not currently retain counts for source work omitted before a timed execution could be projected"),retention:e.retention,observedSpan:m,sources:h,measures:v,bounds:{observedStarts:t.executions.filter(g=>g.start.evidence==="observed").length,inferredStarts:t.executions.filter(g=>g.start.evidence==="inferred").length,observedEnds:t.executions.filter(g=>g.end.state==="observed").length,inferredEnds:t.executions.filter(g=>g.end.state==="inferred").length,openEnds:t.executions.filter(g=>g.end.state!=="observed"&&g.end.state!=="inferred").length},comparisonReadiness:u,reasons:a}}function yS(t,e){const r=ms(t,e),n=r.comparisonReadiness==="not-comparable"?gS(t.summary):t.summary;return{experimental:!0,period:t.window,availability:r,summary:n}}function gS(t){const e=r=>({state:"unknown",qualification:"the period was not sufficiently observed",coverage:r.coverage});return{...t,waitingNow:e(t.waitingNow),completed:e(t.completed),failed:e(t.failed),interrupted:e(t.interrupted),inFlight:{...t.inFlight,totalMs:e(t.inFlight.totalMs),openContributionMs:e(t.inFlight.openContributionMs),parallelMs:e(t.inFlight.parallelMs),peak:e(t.inFlight.peak)},executionWallIntervalMs:e(t.executionWallIntervalMs),peakExecutionConcurrency:e(t.peakExecutionConcurrency),executionDuration:e(t.executionDuration),terminalExecutionDuration:e(t.terminalExecutionDuration),terminalExecutionIntervalMs:e(t.terminalExecutionIntervalMs),overlappingTerminalIntervalMs:e(t.overlappingTerminalIntervalMs),peakTerminalConcurrency:e(t.peakTerminalConcurrency),sessionExecutionCount:e(t.sessionExecutionCount),tokens:e(t.tokens),toolInteractions:e(t.toolInteractions),toolErrors:e(t.toolErrors),waits:e(t.waits),usageByModel:t.usageByModel.map(r=>({...r,tokens:e(r.tokens)}))}}function vS(t,e,r){const n=new Map;for(const s of t.executions){const i=bS(s,r),a=n.get(i)??[];a.push(s),n.set(i,a)}const o=[...n.entries()].map(([s,i])=>wS(s,i)).sort((s,i)=>i.executions-s.executions||s.key.localeCompare(i.key));return{experimental:!0,period:t.window,dimension:r,availability:ms(t,e),items:o,qualification:r==="model"||r==="executor"?"Observed differences describe grouped records; they do not establish causal performance differences.":"Breakdown counts only privacy-reduced execution records present in this period."}}function qy(t,e,r,n){const o=ms(t,e),s=ms(r,n),i=AS(o.comparisonReadiness,s.comparisonReadiness),a=t.window.to-t.window.from===r.window.to-r.window.from,c=a?i:"not-comparable",u=[...o.reasons.map(l=>`period A: ${l}`),...s.reasons.map(l=>`period B: ${l}`),...a?[]:["the requested periods do not have equal duration"]],d=[$o("execution records",ei(t.executions.length,o),ei(r.executions.length,s),c),$o("session records",ei(t.sessions.length,o),ei(r.sessions.length,s),c),Rt("median terminal execution duration",vp(t.summary.terminalExecutionDuration),vp(r.summary.terminalExecutionDuration),c,o,s),Rt("terminal execution interval union",t.summary.terminalExecutionIntervalMs,r.summary.terminalExecutionIntervalMs,c,o,s),Rt("overlapping terminal interval",t.summary.overlappingTerminalIntervalMs,r.summary.overlappingTerminalIntervalMs,c,o,s),Rt("peak terminal concurrency",Bo(t.summary.peakTerminalConcurrency,l=>l.peak),Bo(r.summary.peakTerminalConcurrency,l=>l.peak),c,o,s),$o("model mix",Un(dr(ti(t.summary.modelMix)),o),Un(dr(ti(r.summary.modelMix)),s),c),$o("executor mix",Un(dr(ti(t.summary.executorMix)),o),Un(dr(ti(r.summary.executorMix)),s),c),Rt("completed executions",t.summary.completed,r.summary.completed,c,o,s),Rt("failed executions",t.summary.failed,r.summary.failed,c,o,s),Rt("interrupted executions",t.summary.interrupted,r.summary.interrupted,c,o,s),Rt("tokens",t.summary.tokens,r.summary.tokens,c,o,s),Rt("tool interactions",t.summary.toolInteractions,r.summary.toolInteractions,c,o,s),Rt("tool errors",t.summary.toolErrors,r.summary.toolErrors,c,o,s),Rt("explicit wait count",Bo(t.summary.waits,l=>l.count),Bo(r.summary.waits,l=>l.count),c,o,s)];return{experimental:!0,eligibility:c,periodA:t.window,periodB:r.window,availabilityA:o,availabilityB:s,dimensions:d,reasons:u}}function bS(t,e){switch(e){case"model":return It(t.model)??`[${t.model.state}]`;case"executor":return It(t.executor)??`[${t.executor.state}]`;case"lifecycle":return t.lifecycle.state;case"outcome":return t.lifecycle.state==="terminal"?It(t.outcome)??"unknown":"open";case"session":return t.sessionRef;case"duration-band":{if(t.lifecycle.state!=="terminal")return"open";const r=It(t.end);if(r===void 0)return"[unknown-duration]";const n=Math.max(0,r-t.start.at);return n<6e4?"under-1m":n<3e5?"1m-to-5m":n<18e5?"5m-to-30m":"30m-or-more"}}}function wS(t,e){const r=e.filter(n=>n.lifecycle.state==="terminal");return{key:t,executions:e.length,terminalExecutions:r.length,terminalDuration:xS(r.map(n=>{const o=It(n.end);if(o===void 0)return hr("the terminal execution has no usable end bound");const s=Math.max(0,o-n.start.at);return n.start.evidence==="inferred"||n.end.state==="inferred"?Yy(s,"one or more execution bounds were inferred"):dr(s)})),tokens:ri(e.map(n=>n.measures.tokens.total)),toolInteractions:ri(e.map(n=>n.measures.toolInteractions)),toolErrors:ri(e.map(n=>n.measures.toolErrors)),failed:ri(r.map(n=>ES(n.outcome,"failed")))}}function ei(t,e){return e.observation==="observed"?dr(t):e.executionRecords>0?Xy(t,"record count is known, but observation continuity is not"):hr("the period was not sufficiently observed to interpret zero records as zero work")}function Rt(t,e,r,n,o,s){return $o(t,Un(e,o),Un(r,s),n)}function Un(t,e){return e.comparisonReadiness==="not-comparable"?hr("the period was not sufficiently observed"):t}function $o(t,e,r,n){const o=It(e)!==void 0&&It(r)!==void 0;let s;const i=[];return n==="not-comparable"?(s="not-comparable",i.push("one or both periods are not sufficiently observed")):!o||gp(e.state)||gp(r.state)?(s="not-comparable",i.push(`measure states are ${e.state} and ${r.state}`)):n==="partially-comparable"||e.state==="partial"||r.state==="partial"||e.state==="inferred"||r.state==="inferred"?(s="partially-comparable",i.push("the values are present, but period or measure coverage is qualified")):s="comparable",{dimension:t,eligibility:s,periodA:e,periodB:r,reasons:i}}function gp(t){return t==="unsupported"||t==="not-observed"||t==="unknown"}function AS(t,e){return t==="not-comparable"||e==="not-comparable"?"not-comparable":t==="partially-comparable"||e==="partially-comparable"?"partially-comparable":"comparable"}function vp(t){return Bo(t,e=>e.median)}function Bo(t,e){switch(t.state){case"observed":return{state:"observed",value:e(t.value),coverage:t.coverage};case"inferred":return{state:"inferred",value:e(t.value),qualification:t.qualification,coverage:t.coverage};case"partial":return"value"in t&&t.value!==void 0?{state:"partial",value:e(t.value),qualification:t.qualification,coverage:t.coverage}:{state:"partial",qualification:t.qualification,coverage:t.coverage};case"unsupported":return{...t};case"not-observed":return{...t};case"unknown":return{...t}}}function ti(t){return Object.fromEntries(t.map(e=>[e.key,e.executions]))}function Co(t,e){return{dimension:t,state:e.state,coverage:e.coverage,qualification:zy(e.state)}}function Dc(t,e){const r=Aa(e.map(o=>o.state)),n=IS(r);return{dimension:t,state:n,coverage:r,qualification:zy(n)}}function SS(t){const e=t.map(r=>r.end.state!=="observed"&&r.end.state!=="inferred"?"partial":r.start.evidence==="inferred"||r.end.state==="inferred"?"inferred":"observed");return fd(e.length,Aa(e))}function zy(t){switch(t){case"observed":return"all contributing records are observed for this dimension";case"inferred":return"one or more contributing values were inferred";case"partial":return"a subtotal is available, but one or more records are incomplete";case"unsupported":return"the contributing observers do not support this dimension";case"not-observed":return"the dimension is supported but no value was recorded";case"unknown":return"coverage cannot be established"}}function kS(){return{tokens:"unknown",requests:"unknown",toolInteractions:"unknown",toolErrors:"unknown",retries:"unknown",waits:"unknown",model:"unknown",context:"unknown",outcome:"unknown"}}function ES(t,e){const r=It(t);return CS(t,r===e?1:0)}function ri(t){const e=Aa(t.map(n=>n.state)),r=t.map(It).filter(n=>n!==void 0);return r.length>0?fd(r.reduce((n,o)=>n+o,0),e):e.records>0&&e.unsupported===e.records?{...Jy("no observer supports this measure"),coverage:e}:e.records>0&&e.notObserved===e.records?{...Zy("no value was observed"),coverage:e}:{...hr("no usable value was observed"),coverage:e}}function xS(t){const e=Aa(t.map(n=>n.state)),r=t.map(It).filter(n=>n!==void 0).sort((n,o)=>n-o);return r.length===0?{...hr("no terminal duration samples were observed"),coverage:e}:fd({samples:r.length,minimum:r[0],median:Lc(r,.5),p75:Lc(r,.75),p90:Lc(r,.9),maximum:r[r.length-1]},e)}function Lc(t,e){const r=(t.length-1)*e,n=Math.floor(r),o=Math.ceil(r);return n===o?t[n]:t[n]+(t[o]-t[n])*(r-n)}function fd(t,e){return e.partial+e.unsupported+e.notObserved+e.unknown>0?{state:"partial",value:t,qualification:"coverage is incomplete",coverage:e}:e.inferred>0?{state:"inferred",value:t,qualification:"one or more values were inferred",coverage:e}:{state:"observed",value:t,coverage:e}}function IS(t){return t.records===0?"unknown":t.unsupported===t.records?"unsupported":t.notObserved===t.records?"not-observed":t.unknown===t.records?"unknown":t.partial+t.unsupported+t.notObserved+t.unknown>0?"partial":t.inferred>0?"inferred":"observed"}function Aa(t){const e=OS();e.records=t.length;for(const r of t)r==="not-observed"?e.notObserved++:e[r]++;return e}function OS(){return{records:0,observed:0,inferred:0,partial:0,unsupported:0,notObserved:0,unknown:0}}function It(t){return"value"in t?t.value:void 0}function CS(t,e){switch(t.state){case"observed":return dr(e);case"inferred":return Yy(e,t.qualification);case"partial":return Xy("value"in t?e:void 0,t.qualification);case"unsupported":return Jy(t.qualification);case"not-observed":return Zy(t.qualification);case"unknown":return hr(t.qualification)}}function dr(t){return{state:"observed",value:t}}function Yy(t,e){return{state:"inferred",value:t,qualification:e}}function Xy(t,e){return t===void 0?{state:"partial",qualification:e}:{state:"partial",value:t,qualification:e}}function Jy(t){return{state:"unsupported",qualification:t}}function Zy(t){return{state:"not-observed",qualification:t}}function hr(t){return{state:"unknown",qualification:t}}const Jr="os",NS=(t,e)=>`os:${t}:${e.pid}:${e.startedAt}`;function TS(t,e){const r=/^os:[^:]+:(\d+):(\d+)$/.exec(t);return r?`os:${e}:${r[1]}:${r[2]}`:void 0}const $S=t=>`The process was present in one ${Math.round(t/1e3)}s snapshot and absent from the next, so it exited somewhere in that window. The recorded instant is the last moment it was observed alive — a lower bound on the true exit. A process that started and exited entirely within one interval is never observed at all.`,BS=250,RS=8*1024*1024;function MS(t,e,r){const n={source:{id:Jr,instance:r.host},observedAt:r.observedAt,clock:"wall",stratum:"machine"},o=[],s=new Map;for(const i of e){const a=NS(r.host,i);s.set(a,i);const c={ns:"os.process",parts:[r.host,i.pid],validFrom:i.startedAt,validTo:r.observedAt};if(!t.has(a)){o.push({...n,occurredAt:i.startedAt,kind:"began",subject:{type:"process",id:a},claims:[c],basis:"measured",core:{machineId:r.machineId,label:_S(i.command),executor:i.command,measures:{[Z.cpuMs]:i.cpuMs}},attrs:{"os.pid":i.pid,"os.ppid":i.ppid,"os.command":i.command,"os.rssBytes":i.rssBytes}});continue}const u=t.get(a),d=i.cpuMs-u.cpuMs>=BS,l=Math.abs(i.rssBytes-u.rssBytes)>=RS;(d||l)&&o.push({...n,occurredAt:r.observedAt,seq:`obs:${r.observedAt}`,kind:"observed",subject:{type:"process",id:a},claims:[c],basis:"measured",core:{measures:{[Z.cpuMs]:i.cpuMs}},attrs:{"os.rssBytes":i.rssBytes}})}for(const[i,a]of t)s.has(i)||o.push({...n,occurredAt:r.observedAt-r.intervalMs,kind:"ended",subject:{type:"process",id:i},basis:"inferred",assumption:$S(r.intervalMs),core:{outcome:"completed",measures:{[Z.cpuMs]:a.cpuMs}},attrs:{"os.pid":a.pid}});return{envelopes:o,next:s}}function _S(t){return(t.split("/").pop()??t).toUpperCase()}function Qy(t,e,r,n,o){const s=o?tg(o):void 0,i=t.query(e,r,n),a=i.filter(S=>S.occurredAt<r),c=i.filter(S=>S.occurredAt===r&&S.subject.type==="execution"&&S.kind==="ended"),u=s?Vn(a,s):a,d=!n||n.includes("execution")?t.executionCarry(e,r):[],l=s?Vn(d,s):d,m=new Set,p=new Set,h=new Map,v=S=>{const T=`${S.subject.type}:${S.subject.id}`;S.kind==="began"?(m.add(T),h.set(T,S)):p.add(T),S.core?.sessionId&&p.add(`session:${S.core.sessionId}`),S.core?.machineId&&p.add(`machine:${S.core.machineId}`)};for(const S of[...l,...u,...c])v(S);const g=[];for(let S=0;S<4;S++){const T=[...p].filter(w=>!m.has(w));if(T.length===0)break;const x=t.begansFor(T).filter(w=>w.occurredAt<=r),D=s?Vn(x,s):x;if(D.length===0)break;for(const w of D)h.set(`${w.subject.type}:${w.subject.id}`,w),g.push(w),v(w),m.add(`${w.subject.type}:${w.subject.id}`)}const I=S=>S.occurredAt<e?{...S,occurredAt:e}:S;return{events:[...g.map(I),...l.filter(S=>S.kind==="began").map(I),...u].sort((S,T)=>S.occurredAt-T.occurredAt||Qn(S)-Qn(T)),inWindow:u,history:[...g.filter(S=>S.occurredAt<e),...l],rightBounds:s?Vn(c,s):c,declarations:[...h.values()],relationships:Yb(t.claims(e,r,n)).relationships}}function eg(t,e,r,n,o){const s=performance.now(),{events:i,inWindow:a,history:c,rightBounds:u,declarations:d,relationships:l}=Qy(t,e,r,o,n),m=performance.now()-s,p=performance.now(),h=Ql(e,r);py(h,[...c,...i,...u].sort((T,x)=>T.occurredAt-x.occurredAt||Qn(T)-Qn(x))),hy(h,r);const v=new Set(a.filter(T=>T.subject.type==="execution").map(T=>T.subject.id)),g=new Map;for(const T of a){if(T.subject.type!=="execution"||!T.core?.measures)continue;const x=g.get(T.subject.id)??{};cs(x,T.core.measures),g.set(T.subject.id,x)}const I=new Map;for(const T of h.executions.values()){if(!v.has(T.id)&&T.status!=="waiting"&&T.status!=="running"&&T.endedAt!==r||T.startedAt>=r)continue;const x=T.waits.map(D=>({start:Math.max(e,D.start),end:Math.min(r,D.end)})).filter(D=>D.end>D.start);I.set(T.id,{...T,measures:g.get(T.id)??{},waits:x,waitingMs:x.reduce((D,w)=>D+w.end-w.start,0),waitingSince:T.waitingSince===void 0?void 0:Math.max(e,T.waitingSince)})}h.executions=I,h.active=new Set([...h.active].filter(T=>I.has(T)));const N=new Set(a.flatMap(T=>T.subject.type==="session"?[T.subject.id]:T.core?.sessionId?[T.core.sessionId]:[]));for(const T of h.sessions.values())T.executionIds=T.executionIds.filter(x=>I.has(x)),T.executionIds.length===0&&!N.has(T.id)&&h.sessions.delete(T.id);const S=performance.now()-p;return{state:h,events:i,declarations:d,relationships:l,meta:{events:i.length,readMs:Math.round(m*10)/10,deriveMs:Math.round(S*10)/10}}}function jS(t,e,r,n){const o=n?tg(n):void 0,s=t.subjectEvents("execution",e).filter(d=>d.occurredAt<=r),i=o?Vn(s,o):s,a=new Set;for(const d of i)d.core?.sessionId&&a.add(`session:${d.core.sessionId}`),d.core?.machineId&&a.add(`machine:${d.core.machineId}`);let c=t.begansFor([...a]).filter(d=>d.occurredAt<=r);o&&(c=Vn(c,o));const u=Ql(i[0]?.occurredAt??r,r);return py(u,[...c,...i].sort((d,l)=>d.occurredAt-l.occurredAt||Qn(d)-Qn(l))),hy(u,r),u}function bp(t,e,r,n,o){const s=eg(t,e,r,n,o),i=performance.now();return{world:k0(s.state,s.relationships),state:s.state,declarations:s.declarations,relationships:s.relationships,meta:{...s.meta,serializeMs:Math.round((performance.now()-i)*10)/10}}}function tg(t){const e=iw(t);return r=>{if(r.subject.type==="machine")return r.subject.id!==t&&Sf(r.subject.id)?null:r;const n=r.core?.machineId;if(!n||n===t||!Sf(n))return r;const o=r.subject.type==="process"&&e?TS(r.subject.id,e):void 0;return{...r,...o?{subject:{...r.subject,id:o}}:{},core:{...r.core,machineId:t}}}}function Vn(t,e){const r=[];for(const n of t){const o=e(n);o&&r.push(o)}return r}function Qn(t){if(t.kind==="ended")return 5;switch(t.subject.type){case"machine":return 0;case"session":return 1;case"execution":case"process":return t.kind==="began"?2:3;default:return 4}}const DS=[[ql,Qb],[ki,pw],[en,xw],[Zo,Dw],[Xn,Qw],[es,c0]],Sa=new Map(DS);function rg(t,e,r,n,o){const s=eg(t,e,r,n,["machine","session","execution"]);return Wy({state:ls(s.state,o),declarations:s.declarations,relationships:s.relationships,capabilities:Sa,from:e,to:r})}function ng(t,e,r,n=Date.now(),o){const s=new Map,i=c=>{const u=`${c.from}:${c.to}`,d=s.get(u);if(d)return d;const l=rg(t,c.from,c.to,r,o);return s.set(u,l),l},a=c=>pu(c,e,n);return{summary(c){return yS(i(c),a(c))},availability(c){return ms(i(c),a(c))},compare(c,u){return qy(i(c),a(c),i(u),a(u))},breakdown(c,u){return vS(i(c),a(c),u)}}}function pu(t,e,r){const n=e.eventDays===0?null:r-e.eventDays*864e5,o=n===null?"retained-indefinitely":t.to<n?"outside-retention":t.from<n?"partially-within-retention":"within-retention";return{capabilities:Sa,continuity:{state:"unknown",qualification:"057 does not retain historical source-health continuity for this period"},retention:{state:o,semanticFrom:n,qualification:n===null?"semantic history is configured to be retained indefinitely":o==="within-retention"?"the requested period is inside the configured semantic retention window":o==="partially-within-retention"?"the requested period crosses the configured semantic retention boundary":"the requested period precedes the configured semantic retention window"}}}const LS=3e4;function PS(t,e,r){const n=wa(t.path);try{const o=r.at??t.now?.()??Date.now(),s=ng(n,t.retention,t.machineId,o,r.projectKey);return RA(s,e,o,r)}finally{n.close()}}function US(t,e){return JSON.stringify([t.query,t.scope,t.focus,t.by,e.view,e.timeZone,e.projectKey,e.at,e.period])}function og(t){const e=new Map;return{async read(r,n){const o=t.now?.()??Date.now(),s=US(r,n),i=e.get(s);if(i&&o-i.at<LS)return i.reading;const a=PS(t,r,n);if(e.set(s,{at:o,reading:a}),e.size>32){const c=e.keys().next().value;c!==void 0&&e.delete(c)}return a},close(){e.clear()}}}function VS(t,e){let r=null,n=1;const o=new Map,s=a=>{for(const c of o.values())c.reject(a);o.clear()},i=()=>{const a={o57:"activity-reader",path:e.path,retention:e.retention,machineId:e.machineId},c=new Um(new URL(t),{workerData:a,execArgv:["--disable-warning=ExperimentalWarning"]});return c.unref(),c.on("message",u=>{const d=o.get(u.id);d&&(o.delete(u.id),u.reading?d.resolve(u.reading):d.reject(new Error(u.error??"the reading failed")))}),c.on("error",u=>{r=null,s(u instanceof Error?u:new Error(String(u)))}),c.on("exit",u=>{r===c&&(r=null),o.size>0&&s(new Error(`the reading worker stopped (${u})`))}),c};return{read(a,c){r??=i();const u=n++,d={id:u,request:a,context:c};return new Promise((l,m)=>{o.set(u,{resolve:l,reject:m}),r?.postMessage(d)})},close(){s(new Error("the Core is stopping")),r?.terminate(),r=null}}}function HS(t){const e=og(t);Fn?.on("message",r=>{e.read(r.request,r.context).then(n=>Fn?.postMessage({id:r.id,reading:n}),n=>Fn?.postMessage({id:r.id,error:String(n instanceof Error?n.message:n)}))})}!Pm&&bi?.o57==="activity-reader"&&HS(bi);const pd={[Oi]:us};function hd(t){return`${t}.core.json`}function sg(t){const e=hd(t);if(!ge(e))return null;try{const r=JSON.parse(Gl(e,"utf8"));return typeof r.pid!="number"||typeof r.url!="string"?null:r}catch{return null}}function FS(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function WS(t,e=1500){const r=sg(t);if(!r||r.pid===process.pid||!FS(r.pid))return null;try{const n=await fetch(`${r.url}/api/health`,{signal:AbortSignal.timeout(e)});return n.ok&&(await n.json()).pid===r.pid?r:null}catch{return null}}function KS(t,e){if(t===":memory:")return;const r=hd(t),n=`${r}.${process.pid}.tmp`;Wl(n,`${JSON.stringify(e,null,1)}
100
+ `,{mode:384}),Kl(n,r)}function GS(t,e=process.pid){if(t===":memory:")return;const r=sg(t);r&&r.pid===e&&Dm(hd(t),{force:!0})}class md extends Error{constructor(e){super(`057 is already observing ${e.store} at ${e.url} (pid ${e.pid})`),this.record=e}record}const qS=Lb(Db);function zS(){return Hm()}function YS(t){const e=[];for(const r of t.split(`
101
+ `)){const n=r.trim();if(!n)continue;const o=n.match(/^(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+[\d:]+\s+\d{4})\s+([\d:.]+)\s+(\d+)\s+(.*)$/);if(!o)continue;const[,s,i,a,c,u,d]=o,l=Date.parse(a);Number.isFinite(l)&&e.push({pid:Number(s),ppid:Number(i),startedAt:l,cpuMs:XS(c),rssBytes:Number(u)*1024,command:d.trim()})}return e}function XS(t){const[e,r]=t.includes("-")?t.split("-"):["0",t],n=r.split(":").map(Number);let o=0;for(const s of n)o=o*60+(Number.isFinite(s)?s:0);return Math.round((o+Number(e)*86400)*1e3)}async function JS(){const{stdout:t}=await qS("ps",["-Ao","pid=,ppid=,lstart=,time=,rss=,comm="],{maxBuffer:8388608});return YS(t)}const wp=5e3;function ZS(t,e){const r=zS();let n=new Map,o=null,s=0,i=null,a,c=!1;async function u(){if(c)return[];c=!0;try{const d=await JS(),l=Date.now(),{envelopes:m,next:p}=MS(n,d,{machineId:e,host:r,observedAt:l,intervalMs:wp}),h=m.map(Zt);return t.append(h),n=p,s++,i=l,a=void 0,h}catch(d){return a=d instanceof Error?d.message:String(d),[]}finally{c=!1}}return{sample:u,start(){o||(u(),o=setInterval(()=>{u()},wp),o.unref?.())},stop(){o&&clearInterval(o),o=null},get running(){return o!==null},stats(){return{samples:s,tracked:n.size,lastSampleAt:i,lastError:a}}}}const ig={info:t=>console.log(t),warn:t=>console.warn(t),error:t=>console.error(t)},QS=36e5,ek=15e3,tk=3;function ag(t={}){const e=t.log??ig,r=t.path??ga(),n=t.retention??Uy(),o=nS(r),s=o.stats();e.info(s.events>0?`[057] store ${r}: opened with ${s.events} events`:`[057] store ${r}: NEW EMPTY STORE — if history existed before, it was lost, not carried`);const i=Py();i&&e.warn(`[057] a store from a previous layout exists at ${i} and is NOT in use. Run 057 with O57_STORE=${i} to keep using it, or move it to ${r}.`);const a=Vr();o.append([Zt({source:{id:"host",instance:a.id},occurredAt:0,observedAt:Date.now(),clock:"wall",kind:"began",stratum:"machine",subject:{type:"machine",id:a.id},basis:"measured",core:{machineName:a.name,machineKind:a.kind},seq:"host"})]);const c=ZS(o,a.id),u=new Map;function d(N){for(const S of N){const T=u.get(S.id)??{consecutiveFailures:0,totalFailures:0,failing:!1};S.ok?(T.consecutiveFailures=0,T.failing=!1,T.failingSince=void 0,T.lastSuccessAt=Date.now()):(T.consecutiveFailures===0&&(T.failingSince=Date.now()),T.consecutiveFailures++,T.totalFailures++,T.lastFailureAt=Date.now(),T.lastError=S.error,T.consecutiveFailures>=tk&&!T.failing&&(T.failing=!0,e.warn(`[057] source ${S.id} has failed ${T.consecutiveFailures} collection rounds in a row: ${S.error??"unknown error"}`))),u.set(S.id,T)}}const l=Ap(r);let m=null;function p(N){return m||(m=N,e.error(`[057] ${N.message} — ${N.remedy}`),c.stop()),m}function h(){if(m)return m;if(r===":memory:")return null;if(!ge(r))return p({kind:"unlinked",message:`the store at ${r} no longer exists on disk; captured events are going to an orphaned file and will be lost`,remedy:"Stop 057 and start it again. It will open a new store at the same path.",since:Date.now()});const N=Ap(r);return l!==null&&N!==null&&N!==l?p({kind:"replaced",message:`the store at ${r} was replaced by a different file while 057 was running; captured events are going to the old one`,remedy:"Stop 057 and start it again so it opens the file that is actually there.",since:Date.now()}):null}t.observe!==!1&&c.start();const v=o.sweep(n);v.processEvents+v.otherEvents>0&&e.info(`[057] retention: removed ${v.processEvents} process and ${v.otherEvents} semantic events (${ba(n)})`);const g=setInterval(()=>{if(!m)try{o.sweep(n),lu(r)}catch(N){e.warn(`[057] retention sweep failed: ${String(N)}`)}},QS);g.unref?.();const I=setInterval(()=>{h()},ek);return I.unref?.(),{store:o,machine:a,os:c,path:r,retention:n,fault:()=>m,sweep:N=>o.sweep(n,N),checkStore:h,recordCollection:d,collectionHealth:()=>Object.fromEntries(u),stop(){clearInterval(g),clearInterval(I),c.stop(),o.close()}}}function Ap(t){try{return fa(t).ino}catch{return null}}function cg(t,e){const r=new Map;for(const o of e)o.kind==="began"&&o.subject.type==="execution"&&r.set(o.subject.id,o.source.id);const n=[];for(const o of t.executions.keys()){const s=r.get(o),i=s?Sa.get(s)?.waits:void 0;(i==="supported"||i==="partial")&&n.push(o)}return n}function rk(t,e){return{reported:cg(t,e).length,runs:t.executions.size}}function ug(t,e,r){let n={from:r.from,to:r.to},o=r.label,s=bp(t,n.from,n.to,e,r.subjectTypes);if(r.widenFrom!==void 0&&s.world.executions.length===0&&s.world.sessions.length===0){const a=bp(t,r.widenFrom,r.to,e,r.subjectTypes);(a.world.executions.length>0||a.world.sessions.length>0)&&(n={from:r.widenFrom,to:r.to},o=r.widenedLabel??o,s=a)}let i;if(r.comparison){const{projectKey:a,scope:c,retention:u,evaluatedAt:d}=r.comparison,l=ls(s.state,a),m=Wy({state:l,declarations:s.declarations,relationships:s.relationships,capabilities:Sa,...n}),p=r.comparison.basis==="calendar"?Iy(n,c==="today"?1:7):ld(n),h=rg(t,p.from,p.to,e,a),v=qy(m,pu(n,u,d),h,pu(p,u,d));i=Oy({query:"compare",scope:c},{comparison:v},{projectKey:a,period:n})}return{...n,label:o,comparison:i,world:s.world,meta:s.meta,waits:rk(s.state,s.declarations),executionStarts:Object.fromEntries(s.declarations.filter(a=>a.subject.type==="execution"&&a.kind==="began").map(a=>[a.subject.id,{at:a.occurredAt,basis:a.basis,assumption:a.assumption}])),waitReportedIds:cg(s.state,s.declarations)}}function Sp(t,e){return{async read(r,n){if(n?.aborted)throw new Error("analytical read cancelled");return ug(t,e,r)},close(){}}}function kp(t,e){let r=null,n=1,o=null,s=null;const i=new Map,a=d=>{for(const l of i.values())l.detach(),l.reject(d);i.clear(),s=null},c=()=>{const d={o57:"landscape-reader",...e},l=new Um(new URL(t),{workerData:d,execArgv:["--disable-warning=ExperimentalWarning"]});return l.unref(),l.on("message",m=>{if(r!==l)return;const p=i.get(m.id);i.delete(m.id),s===m.id&&(s=null),p&&(p.detach(),m.snapshot?p.resolve(m.snapshot):p.reject(new Error(m.error??"the landscape read failed"))),u()}),l.on("error",m=>{r===l&&(r=null,a(m instanceof Error?m:new Error(String(m))))}),l.on("exit",m=>{r===l&&(r=null,a(new Error(`the landscape worker stopped (${m})`)))}),l},u=()=>{if(s!==null)return;const d=i.entries().next().value;if(!d)return;const[l,m]=d;r??=c(),s=l,r.postMessage({id:l,request:m.request})};return{read(d,l){if(d.label==="TODAY"&&o)return o;if(l?.aborted)return Promise.reject(new Error("analytical read cancelled"));if(i.size>=32)return Promise.reject(new Error("Too many analytical reads; retry the selected window."));const m=n++,p=new Promise((h,v)=>{const g=()=>{i.delete(m),l?.removeEventListener("abort",g),v(new Error("analytical read cancelled"))};i.set(m,{request:d,resolve:h,reject:v,detach:()=>l?.removeEventListener("abort",g)}),l?.addEventListener("abort",g,{once:!0}),u()});return d.label!=="TODAY"?p:(o=p.finally(()=>{o=null}),o)},close(){a(new Error("the Core is stopping")),r?.terminate(),r=null,o=null}}}function nk(t){const e=wa(t.path);Fn?.on("message",r=>{try{Fn?.postMessage({id:r.id,snapshot:ug(e,t.machineId,r.request)})}catch(n){Fn?.postMessage({id:r.id,error:String(n instanceof Error?n.message:n)})}})}!Pm&&bi?.o57==="landscape-reader"&&nk(bi);const hu=[{id:ql,collect:(t,e)=>fw(t,e)},{id:ki,collect:(t,e)=>Ew(t,e)},{id:en,collect:(t,e)=>jw(t,e)},{id:Zo,collect:(t,e)=>Zw(t,e)},{id:Xn,collect:(t,e)=>a0(t,e)},{id:es,collect:(t,e)=>b0(t,e)}],Ep=[...hu.map(t=>t.id),Jr],xp=10*365*24*36e5,ni=2e5,ok=24*36e5;function Ip(t){const e=new AbortController;return t.once("close",()=>{t.writableEnded||e.abort()}),e.signal}const Op=72*36e5;function Cp(t){const e=new Date(t);return e.setHours(0,0,0,0),{from:e.getTime(),to:t}}function Np(t){const e=t.collectionHealth(),r=Object.entries(e).filter(([,a])=>a.failing).map(([a])=>a),n=t.store.health(),o=t.os.stats(),s=t.fault();let i=null;for(const a of Object.values(e))a.lastSuccessAt&&(i===null||a.lastSuccessAt>i)&&(i=a.lastSuccessAt);return{ok:r.length===0&&n.ok&&!s&&!o.lastError,fault:s??void 0,failingSources:r,errors:Object.fromEntries(Object.entries(e).filter(([,a])=>a.failing).map(([a,c])=>[a,c.lastError??"failing"])),failing:Object.fromEntries(Object.entries(e).filter(([,a])=>a.failing).map(([a,c])=>[a,{since:c.failingSince??null,rounds:c.consecutiveFailures}])),store:{ok:n.ok,remedy:n.remedy},os:{running:t.os.running,lastSampleAt:o.lastSampleAt,lastError:o.lastError},lastCollectionAt:i,sources:{total:Ep.length,reported:Ep.filter(a=>e[a]!==void 0).length}}}function sk(t,e,r){const n=e.startsWith("/api/");if(r){const a=(t.headers.host??"").toLowerCase(),c=a.startsWith("[")?a.slice(0,a.indexOf("]")+1):a.split(":")[0];if(!r.includes(c))return`refusing a request for host "${a}"; 057 answers only on ${r.join(", ")}`}const o=t.headers.origin;if(typeof o=="string"&&o!=="null"){const a=(t.headers.host??"").toLowerCase();let c="";try{c=new URL(o).host.toLowerCase()}catch{return"refusing a request with an unparseable Origin"}if(c!==a)return`refusing a cross-origin request from ${o}`}const s=t.headers["sec-fetch-site"],i=String(t.headers["sec-fetch-dest"]??"");if(ak.has(i))return`refusing to be embedded as ${i}`;if(typeof s=="string"&&s!==""){if(s!=="same-origin"&&s!=="none")return`refusing a ${s} request`;if(s==="none"&&n)return"refusing a directly-navigated API request"}else if(n&&e==="/api/collect"&&!t.headers[ik])return"refusing a state-changing request that carries no fetch metadata";return null}const ik="x-057-client",ak=new Set(["iframe","frame","embed","object","fencedframe"]);function yd(t){t.setHeader("x-frame-options","DENY"),t.setHeader("content-security-policy","frame-ancestors 'none'")}function ck(t,e){const r=(s,i)=>{const a=t.get(s);if(a===null||a==="")return i;const c=Number(a);return Number.isSafeInteger(c)?c:null},n=r("from",e-864e5),o=r("to",e);return n===null||o===null?{error:"from and to must be integer epoch millis"}:o<n?{error:"to must not precede from"}:o>e+ok?{error:"to is too far in the future"}:o-n>xp?{error:`window must not exceed ${xp} ms`}:{from:n,to:o}}function be(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.setHeader("cache-control","no-store"),t.setHeader("x-content-type-options","nosniff"),yd(t),t.end(JSON.stringify(r))}function uk(t){const e=t.problems.filter(r=>r.path.includes("/sessions/")).length;return{identity:t.identityAvailable?e===0?"available":t.registryEntries>0?"partial":"failed":"unavailable","stored-semantics":t.storedAvailable?t.transcriptsFailed===0?"available":t.transcriptsRead>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function Pc(t){return{"stored-semantics":t.storedAvailable?t.failed===0?"available":t.read>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function lk(t){return t.error?"failed":t.available?"observing":t.present?"installed-no-data":"not-installed"}function dk(t){const e=t.home??t.globalStorage;if(typeof e=="string")return e;const r=t.roots;return Array.isArray(r)?r.join(", "):void 0}function zr(t){return{available:t.available,present:t.present??!1,presence:lk(t),origin:dk(t),error:t.error}}function fk(t){const{runtime:e,log:r}=t,n=t.activity??og({path:e.path,retention:e.retention,machineId:e.machine.id}),o=t.landscape??Sp(e.store,e.machine.id),s=t.analytics??Sp(e.store,e.machine.id);let i=null;const a=new Map,c=new Map,u=new Map;async function d(m,p,h,v,g,I="previous"){const N=g??uu(m,p),S=JSON.stringify([m,g??(m==="today"?N.from:null),h??null,h!==void 0,I]),T=a.get(S);if(T&&p>=T.asOf&&p-T.asOf<(m==="today"?5e3:6e4)&&(m!=="today"||T.period.from===N.from))return T;const x=u.get(S);if(x&&!x.controller.signal.aborted)return yf(x,v);const D=Ub(async $=>{const E=g?"SELECTED PERIOD":m==="today"?"TODAY":"LAST 7 DAYS",B=await s.read({...N,label:`ANALYTICS · ${E}`,subjectTypes:["machine","session","execution"],comparison:h===void 0?void 0:{scope:m,projectKey:h??void 0,retention:e.retention,evaluatedAt:p,basis:I}},$);if($.aborted)throw new Error("analytical read cancelled");const C=xc(B.world),P={period:{scope:m,label:E,...N,fixed:g!==void 0},asOf:p,world:C,landscape:Oc(C),waits:B.waits,waitReportedIds:B.waitReportedIds,executionStarts:B.executionStarts,comparison:B.comparison};if(a.set(S,P),c.set(JSON.stringify([m,N.from,N.to,p]),P),c.size>16){const L=c.keys().next().value;L!==void 0&&c.delete(L)}if(a.size>16){const L=a.keys().next().value;L!==void 0&&a.delete(L)}return P});u.set(S,D);const w=()=>{u.get(S)===D&&u.delete(S)};return D.promise.then(w,w),yf(D,v)}async function l(m){if(!i||m-i.at>6e4){const p=Cp(m),h=await o.read({...p,label:"TODAY",widenFrom:m-Op,widenedLabel:"LAST 72H"}),v=xc(h.world);i={at:m,label:h.label,world:v,landscape:Oc(v),waits:h.waits}}return i}return async function(p,h){const v=p.url??"";if(!v.startsWith("/api/"))return!1;const g=new URL(v,"http://localhost"),I=sk(p,g.pathname,t.allowedHosts);if(I)return r.warn(`[057] ${I}`),be(h,403,{error:I}),!0;const N=e.store,S=Date.now(),T=ck(g.searchParams,S);if("error"in T)return be(h,400,{error:T.error}),!0;const{from:x,to:D}=T,w=g.searchParams.has("from")||g.searchParams.has("to"),$=w?{from:x,to:D}:void 0;if(["/api/analytics","/api/activity","/api/inspect"].includes(g.pathname)&&w&&(!/^\d+$/.test(g.searchParams.get("from")??"")||!/^\d+$/.test(g.searchParams.get("to")??"")||D<=x||D>S||D-x>31*864e5))return be(h,400,{error:"analytical bounds need from < to, no future end, and at most 31 days"}),!0;try{if(g.pathname==="/api/state"){const[E,B,C,P,L,te]=await Promise.all([Ef().catch(we=>({available:!1,error:String(we)})),Cf().catch(we=>({available:!1,error:String(we)})),Tf().catch(we=>({available:!1,error:String(we)})),$f().catch(we=>({available:!1,error:String(we)})),_f().catch(we=>({available:!1,error:String(we)})),Df().catch(we=>({available:!1,error:String(we)}))]),[U,V,z,se]=await Promise.all([Jm(x,D).catch(()=>null),ey(x,D).catch(()=>null),ny(x,D).catch(()=>null),ay(x,D).catch(()=>null)]),ve={strata:{"stored-semantics":"failed"}},Ae={"claude-code":U?{strata:uk(U),registryEntries:U.registryEntries,transcriptsRead:U.transcriptsRead,transcriptsFailed:U.transcriptsFailed,problems:U.problems.slice(0,20)}:{strata:{identity:"failed"}},codex:V?{strata:Pc({storedAvailable:V.storedAvailable,read:V.rolloutsRead,failed:V.rolloutsFailed}),rolloutsRead:V.rolloutsRead,rolloutsFailed:V.rolloutsFailed,problems:V.problems.slice(0,20)}:ve,cursor:z?{strata:Pc({storedAvailable:z.storedAvailable,read:z.composersRead,failed:z.composersFailed}),composersRead:z.composersRead,composersFailed:z.composersFailed,problems:z.problems.slice(0,20)}:ve,gemini:se?{strata:Pc({storedAvailable:se.storedAvailable,read:se.sessionsRead,failed:se.sessionsFailed}),sessionsRead:se.sessionsRead,sessionsFailed:se.sessionsFailed,problems:se.problems.slice(0,20)}:ve},_e={deepseek:zr(E),"0x2f":zr(B),"claude-code":zr(C),codex:zr(P),cursor:zr(L),gemini:zr(te)},Ie=e.collectionHealth();for(const[we,Wt]of Object.entries(_e)){const He=Ie[we];He?.failing&&(Wt.presence="failed",Wt.error??=He.lastError)}const q=e.os.stats(),rt=Object.values(_e).filter(we=>we.available).length>0?"observing":q.samples>0?"os-only":"empty",A=Object.entries(Ie).filter(([,we])=>we.failing).map(([we])=>we),ae=N.health(),ye={ok:A.length===0&&ae.ok&&!e.fault()&&!q.lastError,failingSources:A,collection:Ie,store:ae,os:q.lastError?{failing:!0,lastError:q.lastError}:{failing:!1}};return be(h,200,{machine:e.machine,mode:rt,fault:e.fault()??void 0,health:ye,store:{...N.stats(),path:N.path,schemaVersion:N.schemaVersion,bytes:N.sizeBytes(),retention:{...e.retention,description:ba(e.retention)}},os:{...q,running:e.os.running,source:Jr},sources:_e,observation:Ae}),!0}if(g.pathname==="/api/collect"){const E=e.checkStore();if(E)return be(h,503,{error:E.message,fault:E}),!0;const B=await Xb(N,hu,x,D,P=>e.recordCollection([P])),C=await e.os.sample();return e.recordCollection([{id:Jr,ok:!e.os.stats().lastError,error:e.os.stats().lastError}]),be(h,200,{...B,sources:[...B.sources,{id:Jr,ok:!e.os.stats().lastError,collected:C.length,inserted:C.length,duplicate:0,error:e.os.stats().lastError,ms:0}]}),!0}if(g.pathname==="/api/world"){const E=await o.read({from:x,to:D,label:"WINDOW"});return be(h,200,{from:x,to:D,now:S,world:E.world,meta:E.meta,waits:E.waits}),!0}if(g.pathname==="/api/health")return be(h,200,{pid:process.pid,version:t.version??"dev",contract:pd,store:e.path,health:Np(e)}),!0;if(g.pathname==="/api/landscape"){const E=g.searchParams.get("window")==="live",B=E?Cp(S):{from:x,to:D},C=await o.read({...B,label:E?"TODAY":"WINDOW",...E?{widenFrom:S-Op,widenedLabel:"LAST 72H"}:{}}),P=xc(C.world),L=Oc(P);return E&&(i={at:S,label:C.label,world:P,landscape:L,waits:C.waits}),be(h,200,{from:C.from,to:C.to,now:S,window:C.label,meta:C.meta,health:Np(e),...D0(L)}),!0}if(g.pathname==="/api/analytics"){const E=g.searchParams.get("scope")??"today";if(E!=="today"&&E!=="last-7d")return be(h,400,{error:"analytics needs scope=today|last-7d"}),!0;const B=g.searchParams.get("project")??void 0;if(B!==void 0&&!li(B))return be(h,400,{error:"invalid project key"}),!0;const C=g.searchParams.get("comparison");if(C!==null&&C!=="previous"&&C!=="calendar")return be(h,400,{error:"comparison must be previous|calendar"}),!0;const P=C==="calendar"?"calendar":"previous",L=await d(E,S,C?B??null:void 0,Ip(h),$,P),te=ls(L.world,B),U={runs:te.executions.size,reported:L.waitReportedIds.filter(_e=>te.executions.has(_e)).length},V=i?.landscape??{disturbances:[],strata:[]},z=Qf(te,U,$?D-x<=25*36e5?"today":"last-7d":E),se=cA(L.world,B),ve=P==="calendar"?E==="today"?"same local hours one day earlier":"same local bounds one week earlier":`previous ${fe(L.period.to-L.period.from)}`,Ae={period:L.period,asOf:L.asOf,project:se,today:z,comparison:L.comparison,comparisonLabel:ve};return be(h,200,{summaryText:ep(Ae),privateSummaryText:ep(Ae,!0),period:L.period,asOf:L.asOf,comparisonPeriod:C?P==="calendar"?Iy(L.period,E==="today"?1:7):ld(L.period):void 0,comparisonLabel:ve,comparisonBasis:P,projects:aA(L.world),project:se,projectKey:B??null,comparison:L.comparison,today:{window:L.period.label,...z},log:{window:L.period.label,...Tc(te,V,{starts:L.executionStarts,waitReportedIds:L.waitReportedIds})}}),!0}if(g.pathname==="/api/today"||g.pathname==="/api/log"){const E=await l(S);return be(h,200,g.pathname==="/api/today"?{window:E.label,...Qf(E.world,E.waits)}:{window:E.label,...Tc(E.world,E.landscape)}),!0}if(g.pathname==="/api/inspect"){const E=g.searchParams.get("kind")??"",B=g.searchParams.get("id")??"";if(!["disturbance","stratum","mass","coupling"].includes(E)||!B||B.length>512)return be(h,400,{error:"inspect needs kind=disturbance|stratum|mass|coupling and an id"}),!0;const C=g.searchParams.get("scope");if(C!==null&&C!=="today"&&C!=="last-7d")return be(h,400,{error:"inspect needs scope=today|last-7d"}),!0;const P=g.searchParams.get("project")??void 0;if(P!==void 0&&(!C||!li(P)))return be(h,400,{error:"project inspection needs a scope and a valid project key"}),!0;const L=g.searchParams.get("at"),te=L===null?S:Number(L);if(!Number.isSafeInteger(te)||te>S||te<S-6e5)return be(h,400,{error:"refresh the analytical snapshot before inspecting it"}),!0;const U=C?$??uu(C,te):void 0,z=(C&&L!==null&&U?c.get(JSON.stringify([C,U.from,U.to,te])):void 0)??(C?await d(C,te,void 0,Ip(h),$):await l(S)),se=(_e,Ie)=>{for(const q of N.subjectEvents(_e,Ie))if(q.provenance?.path)return q.provenance.path},ve=ls(z.world,P);let Ae=Jf(ve,z.landscape,E,B,se,C&&"executionStarts"in z?z.executionStarts:void 0);if(C&&Ae&&ve.executions.has(B)){const _e=jS(N,B,ve.now,e.machine.id),Ie=Jf(_e,z.landscape,E,B,se),q=Tc(ve,z.landscape).rows.find(qe=>qe.id===B);if(Ie&&q){for(const qe of Ie.groups)for(const rt of qe.rows)rt.key==="ELAPSED"&&(rt.note=[rt.note,`Full retained record as of ${new Date(ve.now).toISOString()}; may include time outside the selected period.`].filter(Boolean).join(" "));Ae={...Ie,groups:[{title:"IN SELECTED PERIOD",metadata:!0,rows:[{key:"RUN TIME",value:fe(q.durationMs),note:"Clipped to the selected period; trailing idle silence excluded. Parallel runs add together."},{key:"TOKENS",value:q.tokens===null?"not reported":ze(q.tokens),note:"Only accounting events recorded in the selected period."},{key:"TOOL CALLS",value:q.tools===null?"not reported":String(q.tools)},{key:"WAITING",value:"waitReportedIds"in z&&z.waitReportedIds.includes(B)?fe(q.waitedMs):"not reported",note:"Includes an explicit wait still open at the snapshot."}]},...Ie.groups]}}}return Ae?(be(h,200,Ae),!0):(be(h,404,{error:"not in the current world"}),!0)}if(g.pathname==="/api/activity"){const E=g.searchParams,B=BA({query:E.get("query"),scope:E.get("scope"),focus:E.get("focus"),by:E.get("by")});if("error"in B)return be(h,400,B),!0;const C=E.get("project")??void 0,P=E.get("at"),L=P===null?void 0:Number(P);if(C!==void 0&&!li(C))return be(h,400,{error:"invalid project key"}),!0;if(L!==void 0&&(!P?.match(/^\d+$/)||!Number.isSafeInteger(L)||L>S||L<S-6e5))return be(h,400,{error:"reading snapshot must be within the last ten minutes; refresh the analytical view"}),!0;const te=E.get("view")==="live"?i?.label??(await l(S)).label:void 0;return be(h,200,await n.read(B,{...te?{view:te}:{},projectKey:C,at:L,period:$})),!0}if(g.pathname==="/api/sources"){const E=await Promise.all([Ef().catch(L=>({available:!1,error:String(L)})),Cf().catch(L=>({available:!1,error:String(L)})),Tf().catch(L=>({available:!1,error:String(L)})),$f().catch(L=>({available:!1,error:String(L)})),_f().catch(L=>({available:!1,error:String(L)})),Df().catch(L=>({available:!1,error:String(L)}))]),B=e.collectionHealth(),C=e.os.stats(),P=hu.map((L,te)=>{const U=zr(E[te]),V=B[L.id];return{id:L.id,presence:V?.failing?"failed":U.presence,origin:U.origin,error:V?.failing?V.lastError??U.error:U.error,consecutiveFailures:V?.consecutiveFailures??0,lastSuccessAt:V?.lastSuccessAt}});return P.push({id:Jr,presence:C.lastError?"failed":C.samples>0?"observing":"installed-no-data",origin:void 0,error:C.lastError,consecutiveFailures:B[Jr]?.consecutiveFailures??0,lastSuccessAt:C.lastSampleAt??void 0}),be(h,200,{sources:P}),!0}if(g.pathname==="/api/detail"){const E=g.searchParams.get("type")??"",B=g.searchParams.get("id")??"";if(!gf.includes(E)||!B)return be(h,400,{error:"detail needs type=<entity type> and id"}),!0;if(B.length>512)return be(h,400,{error:"id is too long"}),!0;const C=N.subjectEvents(E,B);return be(h,200,{type:E,id:B,events:C.slice(0,ni),truncated:C.length>ni}),!0}if(g.pathname==="/api/events"){const E=g.searchParams.get("subject"),B=E?E.split(",").filter(P=>gf.includes(P)):void 0,C=Qy(N,x,D,B,e.machine.id);return be(h,200,{from:x,to:D,now:S,events:C.events.slice(0,ni),truncated:C.events.length>ni,relationships:C.relationships}),!0}return be(h,404,{error:"unknown endpoint"}),!0}catch(E){return h.destroyed||(r.error(`[057] ${String(E)}`),be(h,500,{error:String(E)})),!0}}}var Tp=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},$p={};var Bp;function pk(){if(Bp)return $p;Bp=1;var t;return(function(e){(function(r){var n=typeof globalThis=="object"?globalThis:typeof Tp=="object"?Tp:typeof self=="object"?self:typeof this=="object"?this:c(),o=s(e);typeof n.Reflect<"u"&&(o=s(n.Reflect,o)),r(o,n),typeof n.Reflect>"u"&&(n.Reflect=e);function s(u,d){return function(l,m){Object.defineProperty(u,l,{configurable:!0,writable:!0,value:m}),d&&d(l,m)}}function i(){try{return Function("return this;")()}catch{}}function a(){try{return(0,eval)("(function() { return this; })()")}catch{}}function c(){return i()||a()}})(function(r,n){var o=Object.prototype.hasOwnProperty,s=typeof Symbol=="function",i=s&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",a=s&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",c=typeof Object.create=="function",u={__proto__:[]}instanceof Array,d=!c&&!u,l={create:c?function(){return Ac(Object.create(null))}:u?function(){return Ac({__proto__:null})}:function(){return Ac({})},has:d?function(k,O){return o.call(k,O)}:function(k,O){return O in k},get:d?function(k,O){return o.call(k,O)?k[O]:void 0}:function(k,O){return k[O]}},m=Object.getPrototypeOf(Function),p=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Ab(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Sb(),v=typeof WeakMap=="function"?WeakMap:kb(),g=s?Symbol.for("@reflect-metadata:registry"):void 0,I=vb(),N=bb(I);function S(k,O,M,F){if(q(M)){if(!$n(k))throw new TypeError;if(!Kt(O))throw new TypeError;return L(k,O)}else{if(!$n(k))throw new TypeError;if(!A(O))throw new TypeError;if(!A(F)&&!q(F)&&!qe(F))throw new TypeError;return qe(F)&&(F=void 0),M=He(M),te(k,O,M,F)}}r("decorate",S);function T(k,O){function M(F,ne){if(!A(F))throw new TypeError;if(!q(ne)&&!Ir(ne))throw new TypeError;ve(k,O,F,ne)}return M}r("metadata",T);function x(k,O,M,F){if(!A(M))throw new TypeError;return q(F)||(F=He(F)),ve(k,O,M,F)}r("defineMetadata",x);function D(k,O,M){if(!A(O))throw new TypeError;return q(M)||(M=He(M)),U(k,O,M)}r("hasMetadata",D);function w(k,O,M){if(!A(O))throw new TypeError;return q(M)||(M=He(M)),V(k,O,M)}r("hasOwnMetadata",w);function $(k,O,M){if(!A(O))throw new TypeError;return q(M)||(M=He(M)),z(k,O,M)}r("getMetadata",$);function E(k,O,M){if(!A(O))throw new TypeError;return q(M)||(M=He(M)),se(k,O,M)}r("getOwnMetadata",E);function B(k,O){if(!A(k))throw new TypeError;return q(O)||(O=He(O)),Ae(k,O)}r("getMetadataKeys",B);function C(k,O){if(!A(k))throw new TypeError;return q(O)||(O=He(O)),_e(k,O)}r("getOwnMetadataKeys",C);function P(k,O,M){if(!A(O))throw new TypeError;if(q(M)||(M=He(M)),!A(O))throw new TypeError;q(M)||(M=He(M));var F=Io(O,M,!1);return q(F)?!1:F.OrdinaryDeleteMetadata(k,O,M)}r("deleteMetadata",P);function L(k,O){for(var M=k.length-1;M>=0;--M){var F=k[M],ne=F(O);if(!q(ne)&&!qe(ne)){if(!Kt(ne))throw new TypeError;O=ne}}return O}function te(k,O,M,F){for(var ne=k.length-1;ne>=0;--ne){var Ue=k[ne],je=Ue(O,M,F);if(!q(je)&&!qe(je)){if(!A(je))throw new TypeError;F=je}}return F}function U(k,O,M){var F=V(k,O,M);if(F)return!0;var ne=wc(O);return qe(ne)?!1:U(k,ne,M)}function V(k,O,M){var F=Io(O,M,!1);return q(F)?!1:we(F.OrdinaryHasOwnMetadata(k,O,M))}function z(k,O,M){var F=V(k,O,M);if(F)return se(k,O,M);var ne=wc(O);if(!qe(ne))return z(k,ne,M)}function se(k,O,M){var F=Io(O,M,!1);if(!q(F))return F.OrdinaryGetOwnMetadata(k,O,M)}function ve(k,O,M,F){var ne=Io(M,F,!0);ne.OrdinaryDefineOwnMetadata(k,O,M,F)}function Ae(k,O){var M=_e(k,O),F=wc(k);if(F===null)return M;var ne=Ae(F,O);if(ne.length<=0)return M;if(M.length<=0)return ne;for(var Ue=new h,je=[],le=0,G=M;le<G.length;le++){var X=G[le],Q=Ue.has(X);Q||(Ue.add(X),je.push(X))}for(var re=0,de=ne;re<de.length;re++){var X=de[re],Q=Ue.has(X);Q||(Ue.add(X),je.push(X))}return je}function _e(k,O){var M=Io(k,O,!1);return M?M.OrdinaryOwnMetadataKeys(k,O):[]}function Ie(k){if(k===null)return 1;switch(typeof k){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return k===null?1:6;default:return 6}}function q(k){return k===void 0}function qe(k){return k===null}function rt(k){return typeof k=="symbol"}function A(k){return typeof k=="object"?k!==null:typeof k=="function"}function ae(k,O){switch(Ie(k)){case 0:return k;case 1:return k;case 2:return k;case 3:return k;case 4:return k;case 5:return k}var M="string",F=lf(k,i);if(F!==void 0){var ne=F.call(k,M);if(A(ne))throw new TypeError;return ne}return ye(k)}function ye(k,O){var M,F;{var ne=k.toString;if(Gr(ne)){var F=ne.call(k);if(!A(F))return F}var M=k.valueOf;if(Gr(M)){var F=M.call(k);if(!A(F))return F}}throw new TypeError}function we(k){return!!k}function Wt(k){return""+k}function He(k){var O=ae(k);return rt(O)?O:Wt(O)}function $n(k){return Array.isArray?Array.isArray(k):k instanceof Object?k instanceof Array:Object.prototype.toString.call(k)==="[object Array]"}function Gr(k){return typeof k=="function"}function Kt(k){return typeof k=="function"}function Ir(k){switch(Ie(k)){case 3:return!0;case 4:return!0;default:return!1}}function bc(k,O){return k===O||k!==k&&O!==O}function lf(k,O){var M=k[O];if(M!=null){if(!Gr(M))throw new TypeError;return M}}function df(k){var O=lf(k,a);if(!Gr(O))throw new TypeError;var M=O.call(k);if(!A(M))throw new TypeError;return M}function ff(k){return k.value}function pf(k){var O=k.next();return O.done?!1:O}function hf(k){var O=k.return;O&&O.call(k)}function wc(k){var O=Object.getPrototypeOf(k);if(typeof k!="function"||k===m||O!==m)return O;var M=k.prototype,F=M&&Object.getPrototypeOf(M);if(F==null||F===Object.prototype)return O;var ne=F.constructor;return typeof ne!="function"||ne===k?O:ne}function gb(){var k;!q(g)&&typeof n.Reflect<"u"&&!(g in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(k=wb(n.Reflect));var O,M,F,ne=new v,Ue={registerProvider:je,getProvider:G,setProvider:Q};return Ue;function je(re){if(!Object.isExtensible(Ue))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case k===re:break;case q(O):O=re;break;case O===re:break;case q(M):M=re;break;case M===re:break;default:F===void 0&&(F=new h),F.add(re);break}}function le(re,de){if(!q(O)){if(O.isProviderFor(re,de))return O;if(!q(M)){if(M.isProviderFor(re,de))return O;if(!q(F))for(var Ee=df(F);;){var Be=pf(Ee);if(!Be)return;var $t=ff(Be);if($t.isProviderFor(re,de))return hf(Ee),$t}}}if(!q(k)&&k.isProviderFor(re,de))return k}function G(re,de){var Ee=ne.get(re),Be;return q(Ee)||(Be=Ee.get(de)),q(Be)&&(Be=le(re,de),q(Be)||(q(Ee)&&(Ee=new p,ne.set(re,Ee)),Ee.set(de,Be))),Be}function X(re){if(q(re))throw new TypeError;return O===re||M===re||!q(F)&&F.has(re)}function Q(re,de,Ee){if(!X(Ee))throw new Error("Metadata provider not registered.");var Be=G(re,de);if(Be!==Ee){if(!q(Be))return!1;var $t=ne.get(re);q($t)&&($t=new p,ne.set(re,$t)),$t.set(de,Ee)}return!0}}function vb(){var k;return!q(g)&&A(n.Reflect)&&Object.isExtensible(n.Reflect)&&(k=n.Reflect[g]),q(k)&&(k=gb()),!q(g)&&A(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,g,{enumerable:!1,configurable:!1,writable:!1,value:k}),k}function bb(k){var O=new v,M={isProviderFor:function(X,Q){var re=O.get(X);return q(re)?!1:re.has(Q)},OrdinaryDefineOwnMetadata:je,OrdinaryHasOwnMetadata:ne,OrdinaryGetOwnMetadata:Ue,OrdinaryOwnMetadataKeys:le,OrdinaryDeleteMetadata:G};return I.registerProvider(M),M;function F(X,Q,re){var de=O.get(X),Ee=!1;if(q(de)){if(!re)return;de=new p,O.set(X,de),Ee=!0}var Be=de.get(Q);if(q(Be)){if(!re)return;if(Be=new p,de.set(Q,Be),!k.setProvider(X,Q,M))throw de.delete(Q),Ee&&O.delete(X),new Error("Wrong provider for target.")}return Be}function ne(X,Q,re){var de=F(Q,re,!1);return q(de)?!1:we(de.has(X))}function Ue(X,Q,re){var de=F(Q,re,!1);if(!q(de))return de.get(X)}function je(X,Q,re,de){var Ee=F(re,de,!0);Ee.set(X,Q)}function le(X,Q){var re=[],de=F(X,Q,!1);if(q(de))return re;for(var Ee=de.keys(),Be=df(Ee),$t=0;;){var mf=pf(Be);if(!mf)return re.length=$t,re;var Eb=ff(mf);try{re[$t]=Eb}catch(xb){try{hf(Be)}finally{throw xb}}$t++}}function G(X,Q,re){var de=F(Q,re,!1);if(q(de)||!de.delete(X))return!1;if(de.size===0){var Ee=O.get(Q);q(Ee)||(Ee.delete(re),Ee.size===0&&O.delete(Ee))}return!0}}function wb(k){var O=k.defineMetadata,M=k.hasOwnMetadata,F=k.getOwnMetadata,ne=k.getOwnMetadataKeys,Ue=k.deleteMetadata,je=new v,le={isProviderFor:function(G,X){var Q=je.get(G);return!q(Q)&&Q.has(X)?!0:ne(G,X).length?(q(Q)&&(Q=new h,je.set(G,Q)),Q.add(X),!0):!1},OrdinaryDefineOwnMetadata:O,OrdinaryHasOwnMetadata:M,OrdinaryGetOwnMetadata:F,OrdinaryOwnMetadataKeys:ne,OrdinaryDeleteMetadata:Ue};return le}function Io(k,O,M){var F=I.getProvider(k,O);if(!q(F))return F;if(M){if(I.setProvider(k,O,N))return N;throw new Error("Illegal state.")}}function Ab(){var k={},O=[],M=(function(){function le(G,X,Q){this._index=0,this._keys=G,this._values=X,this._selector=Q}return le.prototype["@@iterator"]=function(){return this},le.prototype[a]=function(){return this},le.prototype.next=function(){var G=this._index;if(G>=0&&G<this._keys.length){var X=this._selector(this._keys[G],this._values[G]);return G+1>=this._keys.length?(this._index=-1,this._keys=O,this._values=O):this._index++,{value:X,done:!1}}return{value:void 0,done:!0}},le.prototype.throw=function(G){throw this._index>=0&&(this._index=-1,this._keys=O,this._values=O),G},le.prototype.return=function(G){return this._index>=0&&(this._index=-1,this._keys=O,this._values=O),{value:G,done:!0}},le})(),F=(function(){function le(){this._keys=[],this._values=[],this._cacheKey=k,this._cacheIndex=-2}return Object.defineProperty(le.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),le.prototype.has=function(G){return this._find(G,!1)>=0},le.prototype.get=function(G){var X=this._find(G,!1);return X>=0?this._values[X]:void 0},le.prototype.set=function(G,X){var Q=this._find(G,!0);return this._values[Q]=X,this},le.prototype.delete=function(G){var X=this._find(G,!1);if(X>=0){for(var Q=this._keys.length,re=X+1;re<Q;re++)this._keys[re-1]=this._keys[re],this._values[re-1]=this._values[re];return this._keys.length--,this._values.length--,bc(G,this._cacheKey)&&(this._cacheKey=k,this._cacheIndex=-2),!0}return!1},le.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=k,this._cacheIndex=-2},le.prototype.keys=function(){return new M(this._keys,this._values,ne)},le.prototype.values=function(){return new M(this._keys,this._values,Ue)},le.prototype.entries=function(){return new M(this._keys,this._values,je)},le.prototype["@@iterator"]=function(){return this.entries()},le.prototype[a]=function(){return this.entries()},le.prototype._find=function(G,X){if(!bc(this._cacheKey,G)){this._cacheIndex=-1;for(var Q=0;Q<this._keys.length;Q++)if(bc(this._keys[Q],G)){this._cacheIndex=Q;break}}return this._cacheIndex<0&&X&&(this._cacheIndex=this._keys.length,this._keys.push(G),this._values.push(void 0)),this._cacheIndex},le})();return F;function ne(le,G){return le}function Ue(le,G){return G}function je(le,G){return[le,G]}}function Sb(){var k=(function(){function O(){this._map=new p}return Object.defineProperty(O.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),O.prototype.has=function(M){return this._map.has(M)},O.prototype.add=function(M){return this._map.set(M,M),this},O.prototype.delete=function(M){return this._map.delete(M)},O.prototype.clear=function(){this._map.clear()},O.prototype.keys=function(){return this._map.keys()},O.prototype.values=function(){return this._map.keys()},O.prototype.entries=function(){return this._map.entries()},O.prototype["@@iterator"]=function(){return this.keys()},O.prototype[a]=function(){return this.keys()},O})();return k}function kb(){var k=16,O=l.create(),M=F();return(function(){function G(){this._key=F()}return G.prototype.has=function(X){var Q=ne(X,!1);return Q!==void 0?l.has(Q,this._key):!1},G.prototype.get=function(X){var Q=ne(X,!1);return Q!==void 0?l.get(Q,this._key):void 0},G.prototype.set=function(X,Q){var re=ne(X,!0);return re[this._key]=Q,this},G.prototype.delete=function(X){var Q=ne(X,!1);return Q!==void 0?delete Q[this._key]:!1},G.prototype.clear=function(){this._key=F()},G})();function F(){var G;do G="@@WeakMap@@"+le();while(l.has(O,G));return O[G]=!0,G}function ne(G,X){if(!o.call(G,M)){if(!X)return;Object.defineProperty(G,M,{value:l.create()})}return G[M]}function Ue(G,X){for(var Q=0;Q<X;++Q)G[Q]=Math.random()*255|0;return G}function je(G){if(typeof Uint8Array=="function"){var X=new Uint8Array(G);return typeof crypto<"u"?crypto.getRandomValues(X):typeof msCrypto<"u"?msCrypto.getRandomValues(X):Ue(X,G),X}return Ue(new Array(G),G)}function le(){var G=je(k);G[6]=G[6]&79|64,G[8]=G[8]&191|128;for(var X="",Q=0;Q<k;++Q){var re=G[Q];(Q===4||Q===6||Q===8)&&(X+="-"),re<16&&(X+="0"),X+=re.toString(16).toLowerCase()}return X}}function Ac(k){return k.__=void 0,delete k.__,k}})})(t||(t={})),$p}pk();const hk="[object ArrayBuffer]";class K{static isArrayBuffer(e){return Object.prototype.toString.call(e)===hk}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,r){if(e.constructor===r)return e;if(this.isArrayBuffer(e))return new r(e);if(this.isArrayBufferView(e))return new r(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,r){const n=K.toUint8Array(e),o=K.toUint8Array(r);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let r;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?r=e[0]:e[e.length-1]instanceof Function?r=e.slice(0,e.length-1):r=e;let n=0;for(const i of r)n+=i.byteLength;const o=new Uint8Array(n);let s=0;for(const i of r){const a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}}const Uc="string",mk=/^[0-9a-f\s]+$/i,yk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,gk=/^[a-zA-Z0-9-_]+$/;class Rp{static fromString(e){const r=unescape(encodeURIComponent(e)),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o);return n.buffer}static toString(e){const r=K.toUint8Array(e);let n="";for(let s=0;s<r.length;s++)n+=String.fromCharCode(r[s]);return decodeURIComponent(escape(n))}}class Gt{static toString(e,r=!1){const n=K.toArrayBuffer(e),o=new DataView(n);let s="";for(let i=0;i<n.byteLength;i+=2){const a=o.getUint16(i,r);s+=String.fromCharCode(a)}return s}static fromString(e,r=!1){const n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),r);return n}}class ee{static isHex(e){return typeof e===Uc&&mk.test(e)}static isBase64(e){return typeof e===Uc&&yk.test(e)}static isBase64Url(e){return typeof e===Uc&&gk.test(e)}static ToString(e,r="utf8"){const n=K.toUint8Array(e);switch(r.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Gt.toString(n,!0);case"utf16":case"utf16be":return Gt.toString(n);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromString(e,r="utf8"){if(!e)return new ArrayBuffer(0);switch(r.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Gt.fromString(e,!0);case"utf16":case"utf16be":return Gt.fromString(e);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToBase64(e){const r=K.toUint8Array(e);if(typeof btoa<"u"){const n=this.ToString(r,"binary");return btoa(n)}else return Buffer.from(r).toString("base64")}static FromBase64(e){const r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!ee.isBase64(r))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(r)):new Uint8Array(Buffer.from(r,"base64")).buffer}static FromBase64Url(e){const r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!ee.isBase64Url(r))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(r.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,r=ee.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.FromBinary(e);case"utf8":return Rp.fromString(e);case"utf16":case"utf16be":return Gt.fromString(e);case"utf16le":case"usc2":return Gt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToUtf8String(e,r=ee.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.ToBinary(e);case"utf8":return Rp.toString(e);case"utf16":case"utf16be":return Gt.toString(e);case"utf16le":case"usc2":return Gt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromBinary(e){const r=e.length,n=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){const r=K.toUint8Array(e);let n="";for(let o=0;o<r.length;o++)n+=String.fromCharCode(r[o]);return n}static ToHex(e){const r=K.toUint8Array(e);let n="";const o=r.length;for(let s=0;s<o;s++){const i=r[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!ee.isHex(r))throw new TypeError("Argument 'hexString' is not HEX encoded");r.length%2&&(r=`0${r}`);const n=new Uint8Array(r.length/2);for(let o=0;o<r.length;o=o+2){const s=r.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,r=!1){return Gt.toString(e,r)}static FromUtf16String(e,r=!1){return Gt.fromString(e,r)}static Base64Padding(e){const r=4-e.length%4;if(r<4)for(let n=0;n<r;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}}ee.DEFAULT_UTF8_ENCODING="utf8";function vk(...t){const e=t.map(o=>o.byteLength).reduce((o,s)=>o+s),r=new Uint8Array(e);let n=0;return t.map(o=>new Uint8Array(o)).forEach(o=>{for(const s of o)r[n++]=s}),r.buffer}function bk(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;const r=new Uint8Array(t),n=new Uint8Array(e);for(let o=0;o<t.byteLength;o++)if(r[o]!==n[o])return!1;return!0}function eo(t,e){let r=0;if(t.length===1)return t[0];for(let n=t.length-1;n>=0;n--)r+=t[t.length-1-n]*Math.pow(2,e*n);return r}function ln(t,e,r=-1){const n=r;let o=t,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(t<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}const u=new Uint8Array(c);for(let d=a-1;d>=0;d--){const l=Math.pow(2,d*e);u[s-d-1]=Math.floor(o/l),o-=u[s-d-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function mu(...t){let e=0,r=0;for(const s of t)e+=s.length;const n=new ArrayBuffer(e),o=new Uint8Array(n);for(const s of t)o.set(s,r),r+=s.length;return o}function lg(){const t=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const a=t[0]===255&&t[1]&128,c=t[0]===0&&(t[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}const e=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)r[a]=0;r[0]=t[0]&128;const n=eo(r,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=t[a];return s[0]&=127,eo(s,8)-n}function wk(t){const e=t<0?t*-1:t;let r=128;for(let n=1;n<8;n++){if(e<=r){if(t<0){const i=r-e,a=ln(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=ln(e,8,n),s=new Uint8Array(o);if(s[0]&128){const i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}r*=Math.pow(2,8)}return new ArrayBuffer(0)}function Ak(t,e){if(t.byteLength!==e.byteLength)return!1;const r=new Uint8Array(t),n=new Uint8Array(e);for(let o=0;o<r.length;o++)if(r[o]!==n[o])return!1;return!0}function ht(t,e){const r=t.toString(10);if(e<r.length)return"";const n=e-r.length,o=Array.from({length:n});for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(r)}function $i(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function gd(t){let e=0,r=0;for(let o=0;o<t.length;o++){const s=t[o];e+=s.byteLength}const n=new Uint8Array(e);for(let o=0;o<t.length;o++){const s=t[o];n.set(new Uint8Array(s),r),r+=s.byteLength}return n.buffer}function Sr(t,e,r,n){return e instanceof Uint8Array?e.byteLength?r<0?(t.error="Wrong parameter: inputOffset less than zero",!1):n<0?(t.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-r-n<0?(t.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(t.error="Wrong parameter: inputBuffer has zero length",!1):(t.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class ka{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return gd(this.items)}}const No=[new Uint8Array([1])],Mp="0123456789",Vc="name",_p="valueHexView",Sk="isHexOnly",kk="idBlock",Ek="tagClass",xk="tagNumber",Ik="isConstructed",Ok="fromBER",Ck="toBER",Nk="local",ot="",nr=new ArrayBuffer(0),Ea=new Uint8Array(0),ys="EndOfContent",dg="OCTET STRING",fg="BIT STRING";function or(t){var e;return e=class extends t{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var o;super(...n);const s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?K.toUint8Array(s.valueHex):Ea}fromBER(n,o,s,i){const a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Sr(this,a,o,s))return-1;const c=o+s;return this.valueHexView=a.subarray(o,c),this.valueHexView.length?(this.blockLength=s,c):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",nr)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ee.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}class On{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:r=ot,warnings:n=[],valueBeforeDecode:o=Ea}={}){this.blockLength=e,this.error=r,this.warnings=n,this.valueBeforeDecodeView=K.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ee.ToHex(this.valueBeforeDecodeView)}}}On.NAME="baseBlock";class Xe extends On{fromBER(e,r,n,o){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Xe.NAME="valueBlock";class pg extends or(On){constructor({idBlock:e={}}={}){var r,n,o,s;super(),e?(this.isHexOnly=(r=e.isHexOnly)!==null&&r!==void 0?r:!1,this.valueHexView=e.valueHex?K.toUint8Array(e.valueHex):Ea,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let r=0;switch(this.tagClass){case 1:r|=0;break;case 2:r|=64;break;case 3:r|=128;break;case 4:r|=192;break;default:return this.error="Unknown tag class",nr}if(this.isConstructed&&(r|=32),this.tagNumber<31&&!this.isHexOnly){const o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,r|=s,o[0]=r}return o.buffer}if(!this.isHexOnly){const o=ln(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=r|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}const n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=r|31,!e){const o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,r,n){const o=K.toUint8Array(e);if(!Sr(this,o,r,n))return-1;const s=o.subarray(r,r+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;const a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){const d=c+1;if(d>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(s[d]&128)===0)break}this.blockLength=c+1;const u=this.valueHexView=new Uint8Array(c);for(let d=0;d<c;d++)u[d]=s[d+1]&127;this.blockLength<=9?this.tagNumber=eo(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return r+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}pg.NAME="identificationBlock";class hg extends On{constructor({lenBlock:e={}}={}){var r,n,o;super(),this.isIndefiniteForm=(r=e.isIndefiniteForm)!==null&&r!==void 0?r:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,r,n){const o=K.toUint8Array(e);if(!Sr(this,o,r,n))return-1;const s=o.subarray(r,r+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,r+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,r+this.blockLength;const i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;const a=r+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=eo(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,r+this.blockLength}toBER(e=!1){let r,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return r=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(r),n[0]=128),r;if(this.longFormUsed){const o=ln(this.length,8);if(o.byteLength>127)return this.error="Too big length",nr;if(r=new ArrayBuffer(o.byteLength+1),e)return r;const s=new Uint8Array(o);n=new Uint8Array(r),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return r}return r=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(r),n[0]=this.length),r}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}hg.NAME="lengthBlock";const Y={};class Ve extends On{constructor({name:e=ot,optional:r=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=r,n&&(this.primitiveSchema=n),this.idBlock=new pg(o),this.lenBlock=new hg(o),this.valueBlock=s?new s(o):new Xe(o)}fromBER(e,r,n,o){const s=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}toBER(e,r){const n=r||new ka;r||mg(this);const o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{const s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;const i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return r?nr:n.final()}toJSON(){const e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():ee.ToHex(this.toBER())}onAsciiEncoding(){const e=this.constructor.NAME,r=ee.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${r}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;const r=this.toBER(),n=e.toBER();return Ak(r,n)}}Ve.NAME="BaseBlock";function mg(t){var e;if(t instanceof Y.Constructed)for(const r of t.valueBlock.value)mg(r)&&(t.lenBlock.isIndefiniteForm=!0);return!!(!((e=t.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}class vd extends Ve{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=ot,...r}={},n){super(r,n),e&&this.fromString(e)}fromBER(e,r,n){const o=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}vd.NAME="BaseStringBlock";class yg extends or(Xe){constructor({isHexOnly:e=!0,...r}={}){super(r),this.isHexOnly=e}}yg.NAME="PrimitiveValueBlock";var gg;class Rs extends Ve{constructor(e={}){super(e,yg),this.idBlock.isConstructed=!1}}gg=Rs;Y.Primitive=gg;Rs.NAME="PRIMITIVE";const vg=100,bg=1e4,wg=16*1024*1024,Tk="Maximum ASN.1 nesting depth exceeded",$k="Maximum ASN.1 node count exceeded",Bk="Maximum ASN.1 content length exceeded";function Ms(t={}){var e,r,n;return{depth:0,maxDepth:(e=t.maxDepth)!==null&&e!==void 0?e:vg,nodesCount:0,maxNodes:(r=t.maxNodes)!==null&&r!==void 0?r:bg,maxContentLength:(n=t.maxContentLength)!==null&&n!==void 0?n:wg}}function Rk(t){const e=new Ve({},Xe);return e.error=t,{offset:-1,result:e}}function Mk(t){if(t.nodesCount+=1,t.nodesCount>t.maxNodes)return $k}function _k(t,e){if(t>e.maxContentLength)return Bk}function bd(t,e,r,n){const o=n.depth+1;if(o>n.maxDepth)return Rk(Tk);n.depth=o;try{return xa(t,e,r,n)}finally{n.depth-=1}}function jk(t,e){if(t instanceof e)return t;const r=new e;return r.idBlock=t.idBlock,r.lenBlock=t.lenBlock,r.warnings=t.warnings,r.valueBeforeDecodeView=t.valueBeforeDecodeView,r}function xa(t,e=0,r=t.length,n=Ms()){const o=e;let s=new Ve({},Xe);const i=new On;if(!Sr(i,t,e,r))return s.error=i.error,{offset:-1,result:s};if(!t.subarray(e,e+r).length)return s.error="Zero buffer length",{offset:-1,result:s};const c=Mk(n);if(c)return s.error=c,{offset:-1,result:s};let u=s.idBlock.fromBER(t,e,r);if(s.idBlock.warnings.length&&s.warnings.concat(s.idBlock.warnings),u===-1)return s.error=s.idBlock.error,{offset:-1,result:s};if(e=u,r-=s.idBlock.blockLength,u=s.lenBlock.fromBER(t,e,r),s.lenBlock.warnings.length&&s.warnings.concat(s.lenBlock.warnings),u===-1)return s.error=s.lenBlock.error,{offset:-1,result:s};e=u,r-=s.lenBlock.blockLength;const d=s.lenBlock.isIndefiniteForm?r:s.lenBlock.length,l=_k(d,n);if(l)return s.error=l,{offset:-1,result:s};if(!s.idBlock.isConstructed&&s.lenBlock.isIndefiniteForm)return s.error="Indefinite length form used for primitive encoding form",{offset:-1,result:s};let m=Ve;switch(s.idBlock.tagClass){case 1:if(s.idBlock.tagNumber>=37&&s.idBlock.isHexOnly===!1)return s.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:s};switch(s.idBlock.tagNumber){case 0:if(s.idBlock.isConstructed&&s.lenBlock.length>0)return s.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:s};m=Y.EndOfContent;break;case 1:m=Y.Boolean;break;case 2:m=Y.Integer;break;case 3:m=Y.BitString;break;case 4:m=Y.OctetString;break;case 5:m=Y.Null;break;case 6:m=Y.ObjectIdentifier;break;case 10:m=Y.Enumerated;break;case 12:m=Y.Utf8String;break;case 13:m=Y.RelativeObjectIdentifier;break;case 14:m=Y.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:m=Y.Sequence;break;case 17:m=Y.Set;break;case 18:m=Y.NumericString;break;case 19:m=Y.PrintableString;break;case 20:m=Y.TeletexString;break;case 21:m=Y.VideotexString;break;case 22:m=Y.IA5String;break;case 23:m=Y.UTCTime;break;case 24:m=Y.GeneralizedTime;break;case 25:m=Y.GraphicString;break;case 26:m=Y.VisibleString;break;case 27:m=Y.GeneralString;break;case 28:m=Y.UniversalString;break;case 29:m=Y.CharacterString;break;case 30:m=Y.BmpString;break;case 31:m=Y.DATE;break;case 32:m=Y.TimeOfDay;break;case 33:m=Y.DateTime;break;case 34:m=Y.Duration;break;default:{const p=s.idBlock.isConstructed?new Y.Constructed:new Y.Primitive;p.idBlock=s.idBlock,p.lenBlock=s.lenBlock,p.warnings=s.warnings,s=p}}break;default:m=s.idBlock.isConstructed?Y.Constructed:Y.Primitive}return s=jk(s,m),u=s.fromBER(t,e,d,n),s.valueBeforeDecodeView=t.subarray(o,o+s.blockLength),{offset:u,result:s}}function Gn(t,e={}){if(!t.byteLength){const r=new Ve({},Xe);return r.error="Input buffer has zero length",{offset:-1,result:r}}return xa(K.toUint8Array(t).slice(),0,t.byteLength,Ms(e))}function Dk(t,e){return t?1:e}class Rr extends Xe{constructor({value:e=[],isIndefiniteForm:r=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=r}fromBER(e,r,n,o){const s=K.toUint8Array(e),i=o??Ms();if(!Sr(this,s,r,n))return-1;if(this.valueBeforeDecodeView=s.subarray(r,r+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),r;let a=r;for(;Dk(this.isIndefiniteForm,n)>0;){const c=bd(s,a,n,i);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===ys)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===ys?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,r){const n=r||new ka;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return r?nr:n.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const r of this.value)e.value.push(r.toJSON());return e}}Rr.NAME="ConstructedValueBlock";var Ag;class et extends Ve{constructor(e={}){super(e,Rr),this.idBlock.isConstructed=!0}fromBER(e,r,n,o){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const s=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){const e=[];for(const n of this.valueBlock.value)e.push(n.toString("ascii").split(`
102
+ `).map(o=>` ${o}`).join(`
85
103
  `));const r=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${r} :
86
104
  ${e.join(`
87
- `)}`:`${r} :`}}Uy=ze;H.Constructed=Uy;ze.NAME="CONSTRUCTED";class Vy extends Fe{fromBER(e,r,n){return r}toBER(e){return Yt}}Vy.override="EndOfContentValueBlock";var Hy;class Jl extends _e{constructor(e={}){super(e,Vy),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Hy=Jl;H.EndOfContent=Hy;Jl.NAME=eo;var Fy;class Qr extends _e{constructor(e={}){super(e,Fe),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,r,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,r+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):r+n}toBER(e,r){const n=new ArrayBuffer(2);if(!e){const s=new Uint8Array(n);s[0]=5,s[1]=0}return r&&r.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}}Fy=Qr;H.Null=Fy;Qr.NAME="NULL";class Wy extends Xt(Fe){get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...r}={}){super(r),r.valueHex?this.valueHexView=U.toUint8Array(r.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,r,n){const s=U.toUint8Array(e);return gr(this,s,r,n)?(this.valueHexView=s.subarray(r,r+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Ny.call(this),this.blockLength=n,r+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}Wy.NAME="BooleanValueBlock";var Ky;let fa=class extends _e{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,Wy),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Ky=fa;H.Boolean=Ky;fa.NAME="BOOLEAN";class Gy extends Xt(Cr){constructor({isConstructed:e=!1,...r}={}){super(r),this.isConstructed=e}fromBER(e,r,n,s){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=Cr.prototype.fromBER.call(this,e,r,n,s),o===-1)return o;for(let i=0;i<this.value.length;i++){const a=this.value[i].constructor.NAME;if(a===eo){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==Ty)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,r,n),this.blockLength=n;return o}toBER(e,r){return this.isConstructed?Cr.prototype.toBER.call(this,e,r):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Gy.NAME="OctetStringValueBlock";var Zl;let Gr=class extends _e{constructor({idBlock:e={},lenBlock:r={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!n.isIndefiniteForm},...n},Gy),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,r,n,s){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),r;if(!this.valueBlock.isConstructed){const i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(r,r+n);try{if(i.byteLength){const a=s??bo(),c=Xl(i,0,i.byteLength,a);c.offset!==-1&&c.offset===n&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,r,n,s)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return ze.prototype.onAsciiEncoding.call(this);const e=this.constructor.NAME,r=Y.ToHex(this.valueBlock.valueHexView);return`${e} : ${r}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const r of this.valueBlock.value)r instanceof Zl&&e.push(r.valueBlock.valueHexView);return U.concat(e)}};Zl=Gr;H.OctetString=Zl;Gr.NAME=Ty;class qy extends Xt(Cr){constructor({unusedBits:e=0,isConstructed:r=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=r,this.blockLength=this.valueHexView.byteLength}fromBER(e,r,n,s){if(!n)return r;let o=-1;if(this.isConstructed){if(o=Cr.prototype.fromBER.call(this,e,r,n,s),o===-1)return o;for(const c of this.value){const u=c.constructor.NAME;if(u===eo){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(u!==By)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const l=c.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}const i=U.toUint8Array(e);if(!gr(this,i,r,n))return-1;const a=i.subarray(r,r+n);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const c=a.subarray(1);try{if(c.byteLength){const u=s??bo(),l=Xl(c,0,c.byteLength,u);l.offset!==-1&&l.offset===n-1&&(this.value=[l.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,r+n}toBER(e,r){if(this.isConstructed)return Cr.prototype.toBER.call(this,e,r);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){const s=new Uint8Array(1);return s[0]=0,s.buffer}const n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}qy.NAME="BitStringValueBlock";var zy;let qr=class extends _e{constructor({idBlock:e={},lenBlock:r={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!n.isIndefiniteForm},...n},qy),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,r,n,s){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,r,n,s)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return ze.prototype.onAsciiEncoding.call(this);{const e=[],r=this.valueBlock.valueHexView;for(const i of r)e.push(i.toString(2).padStart(8,"0"));const n=e.join(""),s=this.constructor.NAME,o=n.substring(0,n.length-this.valueBlock.unusedBits);return`${s} : ${o}`}}};zy=qr;H.BitString=zy;qr.NAME=By;var Yy;function bk(t,e){const r=new Uint8Array([0]),n=new Uint8Array(t),s=new Uint8Array(e);let o=n.slice(0);const i=o.length-1,a=s.slice(0),c=a.length-1;let u=0;const l=c<i?i:c;let d=0;for(let m=l;m>=0;m--,d++)!0===d<a.length?u=o[i-d]+a[c-d]+r[0]:u=o[i-d]+r[0],r[0]=u/10,!0===d>=o.length?o=Xc(new Uint8Array([u%10]),o):o[i-d]=u%10;return r[0]>0&&(o=Xc(r,o)),o}function dp(t){if(t>=hs.length)for(let e=hs.length;e<=t;e++){const r=new Uint8Array([0]);let n=hs[e-1].slice(0);for(let s=n.length-1;s>=0;s--){const o=new Uint8Array([(n[s]<<1)+r[0]]);r[0]=o[0]/10,n[s]=o[0]%10}r[0]>0&&(n=Xc(r,n)),hs.push(n)}return hs[t]}function wk(t,e){let r=0;const n=new Uint8Array(t),s=new Uint8Array(e),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1;let u,l=0;for(let d=c;d>=0;d--,l++)u=o[i-l]-a[c-l]-r,!0===u<0?(r=1,o[i-l]=u+10):(r=0,o[i-l]=u);if(r>0)for(let d=i-c+1;d>=0;d--,l++)if(u=o[i-l]-r,u<0)r=1,o[i-l]=u+10;else{r=0,o[i-l]=u;break}return o.slice()}class Ql extends Xt(Fe){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Ny.call(this)))}constructor({value:e,...r}={}){super(r),this._valueDec=0,r.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(tk(e))}get valueDec(){return this._valueDec}fromDER(e,r,n,s=0){const o=this.fromBER(e,r,n);if(o===-1)return o;const i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):s!==0&&i.length<s&&(s-i.length>1&&(s=i.length+1),this.valueHexView=i.subarray(s-i.length)),o}toDER(e=!1){const r=this.valueHexView;switch(!0){case(r[0]&128)!==0:{const n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(r,1),this.valueHexView=n}break;case(r[0]===0&&(r[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,r,n){const s=super.fromBER(e,r,n);return s===-1||this.setValueHex(),s}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=this.valueHexView.length*8-1;let r=new Uint8Array(this.valueHexView.length*8/3),n=0,s;const o=this.valueHexView;let i="",a=!1;for(let c=o.byteLength-1;c>=0;c--){s=o[c];for(let u=0;u<8;u++)(s&1)===1&&(n===e?(r=wk(dp(n),r),i="-"):r=bk(r,dp(n))),n++,s>>=1}for(let c=0;c<r.length;c++)r[c]&&(a=!0),a&&(i+=up.charAt(r[c]));return a===!1&&(i+=up.charAt(0)),i}}Yy=Ql;Ql.NAME="IntegerValueBlock";Object.defineProperty(Yy.prototype,"valueHex",{set:function(t){this.valueHexView=new Uint8Array(t),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Us;class ts extends _e{constructor(e={}){super(e,Ql),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return vi(),BigInt(this.valueBlock.toString())}static fromBigInt(e){vi();const r=BigInt(e),n=new ua,s=r.toString(16).replace(/^-/,""),o=new Uint8Array(Y.FromHex(s));if(r<0){const a=new Uint8Array(o.length+(o[0]&128?1:0));a[0]|=128;const u=BigInt(`0x${Y.ToHex(a)}`)+r,l=U.toUint8Array(Y.FromHex(u.toString(16)));l[0]|=128,n.write(l)}else o[0]&128&&n.write(new Uint8Array([0])),n.write(o);return new Us({valueHex:n.final()})}convertToDER(){const e=new Us({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Us({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}Us=ts;H.Integer=Us;ts.NAME="INTEGER";var Xy;class pa extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Xy=pa;H.Enumerated=Xy;pa.NAME="ENUMERATED";class Jc extends Xt(Fe){constructor({valueDec:e=-1,isFirstSid:r=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=r}fromBER(e,r,n){if(!n)return r;const s=U.toUint8Array(e);if(!gr(this,s,r,n))return-1;const o=s.subarray(r,r+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,(o[a]&128)!==0);a++);const i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(o[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Hn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}set valueBigInt(e){vi();let r=BigInt(e).toString(2);for(;r.length%7;)r="0"+r;const n=new Uint8Array(r.length/7);for(let s=0;s<n.length;s++)n[s]=parseInt(r.slice(s*7,s*7+7),2)+(s+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}const r=Zr(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",Yt;const n=new Uint8Array(r.byteLength);if(!e){const s=new Uint8Array(r),o=r.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}return n}toString(){let e="";if(this.isHexOnly)e=Y.ToHex(this.valueHexView);else if(this.isFirstSid){let r=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",r-=40):(e="2.",r-=80),e+=r.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}Jc.NAME="sidBlock";class Jy extends Fe{constructor({value:e=Je,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let s=r;for(;n>0;){const o=new Jc;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.value.length===0&&(o.isFirstSid=!0),this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e){const r=[];for(let n=0;n<this.value.length;n++){const s=this.value[n].toBER(e);if(s.byteLength===0)return this.error=this.value[n].error,Yt;r.push(s)}return zl(r)}fromString(e){this.value=[];let r=0,n=0,s="",o=!1;do if(n=e.indexOf(".",r),n===-1?s=e.substring(r):s=e.substring(r,n),r=n+1,o){const i=this.value[0];let a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}const c=parseInt(s,10);if(isNaN(c))return;i.valueDec=c+a,o=!1}else{const i=new Jc;if(s>Number.MAX_SAFE_INTEGER){vi();const a=BigInt(s);i.valueBigInt=a}else if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,o=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",r=!1;for(let n=0;n<this.value.length;n++){r=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),r?(s=`{${s}}`,this.value[n].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}}Jy.NAME="ObjectIdentifierValueBlock";var Zy;class ha extends _e{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Jy),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Zy=ha;H.ObjectIdentifier=Zy;ha.NAME="OBJECT IDENTIFIER";class Zc extends Xt(yn){constructor({valueDec:e=0,...r}={}){super(r),this.valueDec=e}fromBER(e,r,n){if(n===0)return r;const s=U.toUint8Array(e);if(!gr(this,s,r,n))return-1;const o=s.subarray(r,r+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,(o[a]&128)!==0);a++);const i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(o[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Hn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}const r=Zr(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",Yt;const n=new Uint8Array(r.byteLength);if(!e){const s=new Uint8Array(r),o=r.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}return n.buffer}toString(){let e="";return this.isHexOnly?e=Y.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Zc.NAME="relativeSidBlock";class Qy extends Fe{constructor({value:e=Je,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let s=r;for(;n>0;){const o=new Zc;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e,r){const n=[];for(let s=0;s<this.value.length;s++){const o=this.value[s].toBER(e);if(o.byteLength===0)return this.error=this.value[s].error,Yt;n.push(o)}return zl(n)}fromString(e){this.value=[];let r=0,n=0,s="";do{n=e.indexOf(".",r),n===-1?s=e.substring(r):s=e.substring(r,n),r=n+1;const o=new Zc;if(o.valueDec=parseInt(s,10),isNaN(o.valueDec))return!0;this.value.push(o)}while(n!==-1);return!0}toString(){let e="",r=!1;for(let n=0;n<this.value.length;n++){r=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),r&&(s=`{${s}}`),e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}}Qy.NAME="RelativeObjectIdentifierValueBlock";var eg;class ma extends _e{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Qy),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}eg=ma;H.RelativeObjectIdentifier=eg;ma.NAME="RelativeObjectIdentifier";var tg;class $t extends ze{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}tg=$t;H.Sequence=tg;$t.NAME="SEQUENCE";var rg;let Ft=class extends ze{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};rg=Ft;H.Set=rg;Ft.NAME="SET";class ng extends Xt(Fe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Je}toJSON(){return{...super.toJSON(),value:this.value}}}ng.NAME="StringValueBlock";class sg extends ng{}sg.NAME="SimpleStringValueBlock";class ft extends Yl{constructor({...e}={}){super(e,sg)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,U.toUint8Array(e))}fromString(e){const r=e.length,n=this.valueBlock.valueHexView=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e.charCodeAt(s);this.valueBlock.value=e}}ft.NAME="SIMPLE STRING";class og extends ft{fromBuffer(e){this.valueBlock.valueHexView=U.toUint8Array(e);try{this.valueBlock.value=Y.ToUtf8String(e)}catch(r){this.warnings.push(`Error during "decodeURIComponent": ${r}, using raw string`),this.valueBlock.value=Y.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Y.FromUtf8String(e)),this.valueBlock.value=e}}og.NAME="Utf8StringValueBlock";var ig;class vr extends og{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}ig=vr;H.Utf8String=ig;vr.NAME="UTF8String";class ag extends ft{fromBuffer(e){this.valueBlock.value=Y.ToUtf16String(e),this.valueBlock.valueHexView=U.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Y.FromUtf16String(e))}}ag.NAME="BmpStringValueBlock";var cg;class ya extends ag{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}cg=ya;H.BmpString=cg;ya.NAME="BMPString";class ug extends ft{fromBuffer(e){const r=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(r);for(let s=0;s<n.length;s+=4)n[s]=n[s+3],n[s+1]=n[s+2],n[s+2]=0,n[s+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(r))}fromString(e){const r=e.length,n=this.valueBlock.valueHexView=new Uint8Array(r*4);for(let s=0;s<r;s++){const o=Zr(e.charCodeAt(s),8),i=new Uint8Array(o);if(i.length>4)continue;const a=4-i.length;for(let c=i.length-1;c>=0;c--)n[s*4+c+a]=i[c]}this.valueBlock.value=e}}ug.NAME="UniversalStringValueBlock";var lg;class ga extends ug{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}lg=ga;H.UniversalString=lg;ga.NAME="UniversalString";var dg;class va extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}dg=va;H.NumericString=dg;va.NAME="NumericString";var fg;class ba extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}fg=ba;H.PrintableString=fg;ba.NAME="PrintableString";var pg;class wa extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}pg=wa;H.TeletexString=pg;wa.NAME="TeletexString";var hg;class Aa extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}hg=Aa;H.VideotexString=hg;Aa.NAME="VideotexString";var mg;class Sa extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}mg=Sa;H.IA5String=mg;Sa.NAME="IA5String";var yg;class ka extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}yg=ka;H.GraphicString=yg;ka.NAME="GraphicString";var gg;class wo extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}gg=wo;H.VisibleString=gg;wo.NAME="VisibleString";var vg;class xa extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}vg=xa;H.GeneralString=vg;xa.NAME="GeneralString";var bg;class Ea extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}bg=Ea;H.CharacterString=bg;Ea.NAME="CharacterString";var wg;class Ao extends wo{constructor({value:e,valueDate:r,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let s=0;s<e.length;s++)this.valueBlock.valueHexView[s]=e.charCodeAt(s)}r&&(this.fromDate(r),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,U.toUint8Array(e)))}toBuffer(){const e=this.toString(),r=new ArrayBuffer(e.length),n=new Uint8Array(r);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return r}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}const s=parseInt(n[1],10);s>=50?this.year=1900+s:this.year=2e3+s,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){const r=new Array(7);return r[0]=ct(this.year<2e3?this.year-1900:this.year-2e3,2),r[1]=ct(this.month,2),r[2]=ct(this.day,2),r[3]=ct(this.hour,2),r[4]=ct(this.minute,2),r[5]=ct(this.second,2),r[6]="Z",r.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}wg=Ao;H.UTCTime=wg;Ao.NAME="UTCTime";var Ag;class Ia extends Ao{constructor(e={}){var r;super(e),(r=this.millisecond)!==null&&r!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){const e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let r=!1,n="",s="",o=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),r=!0;else{const d=new Number(e[e.length-1]);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let d=1,m=n.indexOf("+"),p="";if(m===-1&&(m=n.indexOf("-"),d=-1),m!==-1){if(p=n.substring(m+1),n=n.substring(0,m),p.length!==2&&p.length!==4)throw new Error("Wrong input string for conversion");let y=parseInt(p.substring(0,2),10);if(isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");if(a=d*y,p.length===4){if(y=parseInt(p.substring(2,4),10),isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");c=d*y}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){const d=new Number(`0${n.substring(u)}`);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");o=d.valueOf(),s=n.substring(0,u)}else s=n;switch(!0){case s.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case s.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let d=60*o;this.minute=Math.floor(d),d=60*(d-this.minute),this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case s.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let d=60*o;this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case s.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){const d=1e3*o;this.millisecond=Math.floor(d)}break;default:throw new Error("Wrong input string for conversion")}const l=i.exec(s);if(l===null)throw new Error("Wrong input string for conversion");for(let d=1;d<l.length;d++)switch(d){case 1:this.year=parseInt(l[d],10);break;case 2:this.month=parseInt(l[d],10);break;case 3:this.day=parseInt(l[d],10);break;case 4:this.hour=parseInt(l[d],10)+a;break;case 5:this.minute=parseInt(l[d],10)+c;break;case 6:this.second=parseInt(l[d],10);break;default:throw new Error("Wrong input string for conversion")}if(r===!1){const d=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=d.getUTCFullYear(),this.month=d.getUTCMonth(),this.day=d.getUTCDay(),this.hour=d.getUTCHours(),this.minute=d.getUTCMinutes(),this.second=d.getUTCSeconds(),this.millisecond=d.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){const r=[];return r.push(ct(this.year,4)),r.push(ct(this.month,2)),r.push(ct(this.day,2)),r.push(ct(this.hour,2)),r.push(ct(this.minute,2)),r.push(ct(this.second,2)),this.millisecond!==0&&(r.push("."),r.push(ct(this.millisecond,3))),r.push("Z"),r.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}Ag=Ia;H.GeneralizedTime=Ag;Ia.NAME="GeneralizedTime";var Sg;class ed extends vr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}Sg=ed;H.DATE=Sg;ed.NAME="DATE";var kg;class td extends vr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}kg=td;H.TimeOfDay=kg;td.NAME="TimeOfDay";var xg;class rd extends vr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}xg=rd;H.DateTime=xg;rd.NAME="DateTime";var Eg;class nd extends vr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}Eg=nd;H.Duration=Eg;nd.NAME="Duration";var Ig;class sd extends vr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}Ig=sd;H.TIME=Ig;sd.NAME="TIME";class en{constructor({name:e=Je,optional:r=!1}={}){this.name=e,this.optional=r}}class od extends en{constructor({value:e=[],...r}={}){super(r),this.value=e}}class bi extends en{constructor({value:e=new en,local:r=!1,...n}={}){super(n),this.value=e,this.local=r}}class Ak{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=U.toUint8Array(e)}constructor({data:e=la}={}){this.dataView=U.toUint8Array(e)}fromBER(e,r,n){const s=r+n;return this.dataView=U.toUint8Array(e).subarray(r,s),s}toBER(e){return this.dataView.slice().buffer}}function xr(t,e,r){if(r instanceof od){for(const o of r.value)if(xr(t,e,o).verified)return{verified:!0,result:t};{const o={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(xc)&&(o.name=r.name),o}}if(r instanceof en)return r.hasOwnProperty(xc)&&(t[r.name]=e),{verified:!0,result:t};if(!(t instanceof Object))return{verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(r instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(sk in r))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(ck in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(uk in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const n=r.idBlock.toBER(!1);if(n.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(r.idBlock.fromBER(n,0,n.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(r.idBlock.hasOwnProperty(ok)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==e.idBlock.tagClass)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(ik)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==e.idBlock.tagNumber)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(ak)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:t};if(!(nk in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==e.idBlock.isHexOnly)return{verified:!1,result:t};if(r.idBlock.isHexOnly){if(!(lp in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const o=r.idBlock.valueHexView,i=e.idBlock.valueHexView;if(o.length!==i.length)return{verified:!1,result:t};for(let a=0;a<o.length;a++)if(o[a]!==i[1])return{verified:!1,result:t}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Je),r.name&&(t[r.name]=e)),r instanceof H.Constructed){let o=0,i={verified:!1,result:{error:"Unknown error"}},a=r.valueBlock.value.length;if(a>0&&r.valueBlock.value[0]instanceof bi&&(a=e.valueBlock.value.length),a===0)return{verified:!0,result:t};if(e.valueBlock.value.length===0&&r.valueBlock.value.length!==0){let c=!0;for(let u=0;u<r.valueBlock.value.length;u++)c=c&&(r.valueBlock.value[u].optional||!1);return c?{verified:!0,result:t}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Je),r.name&&delete t[r.name]),t.error="Inconsistent object length",{verified:!1,result:t})}for(let c=0;c<a;c++)if(c-o>=e.valueBlock.value.length){if(r.valueBlock.value[c].optional===!1){const u={verified:!1,result:t};return t.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Je),r.name&&(delete t[r.name],u.name=r.name)),u}}else if(r.valueBlock.value[0]instanceof bi){if(i=xr(t,e.valueBlock.value[c],r.valueBlock.value[0].value),i.verified===!1)if(r.valueBlock.value[0].optional)o++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Je),r.name&&delete t[r.name]),i;if(xc in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let u={};lk in r.valueBlock.value[0]&&r.valueBlock.value[0].local?u=e:u=t,typeof u[r.valueBlock.value[0].name]>"u"&&(u[r.valueBlock.value[0].name]=[]),u[r.valueBlock.value[0].name].push(e.valueBlock.value[c])}}else if(i=xr(t,e.valueBlock.value[c-o],r.valueBlock.value[c]),i.verified===!1)if(r.valueBlock.value[c].optional)o++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Je),r.name&&delete t[r.name]),i;if(i.verified===!1){const c={verified:!1,result:t};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Je),r.name&&(delete t[r.name],c.name=r.name)),c}return{verified:!0,result:t}}if(r.primitiveSchema&&lp in e.valueBlock){const o=da(e.valueBlock.valueHexView);if(o.offset===-1){const i={verified:!1,result:o.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Je),r.name&&(delete t[r.name],i.name=r.name)),i}return xr(t,o.result,r.primitiveSchema)}return{verified:!0,result:t}}function Sk(t,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=da(U.toUint8Array(t));return r.offset===-1?{verified:!1,result:r.result}:xr(r.result,r.result,e)}const Cg=Object.freeze(Object.defineProperty({__proto__:null,Any:en,BaseBlock:_e,BaseStringBlock:Yl,BitString:qr,BmpString:ya,Boolean:fa,CharacterString:Ea,Choice:od,Constructed:ze,DATE:ed,DEFAULT_MAX_CONTENT_LENGTH:Ly,DEFAULT_MAX_DEPTH:Dy,DEFAULT_MAX_NODES:Py,DateTime:rd,Duration:nd,EndOfContent:Jl,Enumerated:pa,GeneralString:xa,GeneralizedTime:Ia,GraphicString:ka,HexBlock:Xt,IA5String:Sa,Integer:ts,Null:Qr,NumericString:va,ObjectIdentifier:ha,OctetString:Gr,Primitive:vo,PrintableString:ba,RawData:Ak,RelativeObjectIdentifier:ma,Repeated:bi,Sequence:$t,Set:Ft,TIME:sd,TeletexString:wa,TimeOfDay:td,UTCTime:Ao,UniversalString:ga,Utf8String:vr,ValueBlock:Fe,VideotexString:Aa,ViewWriter:ua,VisibleString:wo,compareSchema:xr,fromBER:_n,verifySchema:Sk},Symbol.toStringTag,{value:"Module"})),kk="[object ArrayBuffer]",xk="[object SharedArrayBuffer]";function Og(t){return Object.prototype.toString.call(t)}function Ek(t){if(ArrayBuffer.isView(t))return!0;if(!t||typeof t!="object")return!1;const e=t;return typeof e.byteOffset=="number"&&typeof e.byteLength=="number"&&id(e.buffer)}function Ng(t){return Og(t)===kk}function Ik(t){return typeof SharedArrayBuffer<"u"&&Og(t)===xk}function id(t){return Ng(t)||Ik(t)}function Ck(t){return Ek(t)}function Ca(t){return id(t)||Ck(t)}function Tg(t){if(!Ca(t))throw new TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function tn(t){return Tg(t),id(t)?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function At(t){if(Tg(t),Ng(t))return t;const e=new ArrayBuffer(t.byteLength);return new Uint8Array(e).set(tn(t)),e}function Ok(t,e,r={}){const n=tn(t),s=tn(e);if(!r.constantTime&&n.byteLength!==s.byteLength)return!1;const o=Math.max(n.byteLength,s.byteLength);let i=n.byteLength^s.byteLength;for(let a=0;a<o;a++)i|=(n[a]??0)^(s[a]??0);return i===0}function Bg(t){const e=tn(t);let r="";for(const n of e)r+=String.fromCharCode(n);return r}function $g(t){const e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r)&255;return e}function Nk(t){return typeof t=="string"}const Tk=/^[0-9a-f]$/i,Bk=[" "," ",`
88
- `,"\r",":","-","."];function $k(t){return t.separators==="none"?[]:!t.separators||t.separators==="common"?Bk:t.separators}function Rk(t){if(!t)throw new TypeError("Hex separators must be non-empty strings")}function _k(t,e,r){for(const n of r)if(t.startsWith(n,e))return n}function Mk(t){const e=/[A-F]/.test(t),r=/[a-f]/.test(t);return e&&!r?"upper":"lower"}function jk(t){const e=/\r\n|\n/.exec(t);if(e)return e[0]===`\r
105
+ `)}`:`${r} :`}}Ag=et;Y.Constructed=Ag;et.NAME="CONSTRUCTED";class Sg extends Xe{fromBER(e,r,n){return r}toBER(e){return nr}}Sg.override="EndOfContentValueBlock";var kg;class wd extends Ve{constructor(e={}){super(e,Sg),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}kg=wd;Y.EndOfContent=kg;wd.NAME=ys;var Eg;class dn extends Ve{constructor(e={}){super(e,Xe),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,r,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,r+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):r+n}toBER(e,r){const n=new ArrayBuffer(2);if(!e){const o=new Uint8Array(n);o[0]=5,o[1]=0}return r&&r.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}}Eg=dn;Y.Null=Eg;dn.NAME="NULL";class xg extends or(Xe){get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...r}={}){super(r),r.valueHex?this.valueHexView=K.toUint8Array(r.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,r,n){const o=K.toUint8Array(e);return Sr(this,o,r,n)?(this.valueHexView=o.subarray(r,r+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,lg.call(this),this.blockLength=n,r+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}xg.NAME="BooleanValueBlock";var Ig;let Ia=class extends Ve{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,xg),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Ig=Ia;Y.Boolean=Ig;Ia.NAME="BOOLEAN";class Og extends or(Rr){constructor({isConstructed:e=!1,...r}={}){super(r),this.isConstructed=e}fromBER(e,r,n,o){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=Rr.prototype.fromBER.call(this,e,r,n,o),s===-1)return s;for(let i=0;i<this.value.length;i++){const a=this.value[i].constructor.NAME;if(a===ys){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==dg)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,r,n),this.blockLength=n;return s}toBER(e,r){return this.isConstructed?Rr.prototype.toBER.call(this,e,r):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Og.NAME="OctetStringValueBlock";var Ad;let nn=class extends Ve{constructor({idBlock:e={},lenBlock:r={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!n.isIndefiniteForm},...n},Og),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,r,n,o){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),r;if(!this.valueBlock.isConstructed){const i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(r,r+n);try{if(i.byteLength){const a=o??Ms(),c=bd(i,0,i.byteLength,a);c.offset!==-1&&c.offset===n&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,r,n,o)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return et.prototype.onAsciiEncoding.call(this);const e=this.constructor.NAME,r=ee.ToHex(this.valueBlock.valueHexView);return`${e} : ${r}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const r of this.valueBlock.value)r instanceof Ad&&e.push(r.valueBlock.valueHexView);return K.concat(e)}};Ad=nn;Y.OctetString=Ad;nn.NAME=dg;class Cg extends or(Rr){constructor({unusedBits:e=0,isConstructed:r=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=r,this.blockLength=this.valueHexView.byteLength}fromBER(e,r,n,o){if(!n)return r;let s=-1;if(this.isConstructed){if(s=Rr.prototype.fromBER.call(this,e,r,n,o),s===-1)return s;for(const c of this.value){const u=c.constructor.NAME;if(u===ys){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(u!==fg)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const d=c.valueBlock;if(this.unusedBits>0&&d.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=d.unusedBits}return s}const i=K.toUint8Array(e);if(!Sr(this,i,r,n))return-1;const a=i.subarray(r,r+n);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const c=a.subarray(1);try{if(c.byteLength){const u=o??Ms(),d=bd(c,0,c.byteLength,u);d.offset!==-1&&d.offset===n-1&&(this.value=[d.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,r+n}toBER(e,r){if(this.isConstructed)return Rr.prototype.toBER.call(this,e,r);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){const o=new Uint8Array(1);return o[0]=0,o.buffer}const n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}Cg.NAME="BitStringValueBlock";var Ng;let on=class extends Ve{constructor({idBlock:e={},lenBlock:r={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!n.isIndefiniteForm},...n},Cg),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,r,n,o){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,r,n,o)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return et.prototype.onAsciiEncoding.call(this);{const e=[],r=this.valueBlock.valueHexView;for(const i of r)e.push(i.toString(2).padStart(8,"0"));const n=e.join(""),o=this.constructor.NAME,s=n.substring(0,n.length-this.valueBlock.unusedBits);return`${o} : ${s}`}}};Ng=on;Y.BitString=Ng;on.NAME=fg;var Tg;function Lk(t,e){const r=new Uint8Array([0]),n=new Uint8Array(t),o=new Uint8Array(e);let s=n.slice(0);const i=s.length-1,a=o.slice(0),c=a.length-1;let u=0;const d=c<i?i:c;let l=0;for(let m=d;m>=0;m--,l++)!0===l<a.length?u=s[i-l]+a[c-l]+r[0]:u=s[i-l]+r[0],r[0]=u/10,!0===l>=s.length?s=mu(new Uint8Array([u%10]),s):s[i-l]=u%10;return r[0]>0&&(s=mu(r,s)),s}function jp(t){if(t>=No.length)for(let e=No.length;e<=t;e++){const r=new Uint8Array([0]);let n=No[e-1].slice(0);for(let o=n.length-1;o>=0;o--){const s=new Uint8Array([(n[o]<<1)+r[0]]);r[0]=s[0]/10,n[o]=s[0]%10}r[0]>0&&(n=mu(r,n)),No.push(n)}return No[t]}function Pk(t,e){let r=0;const n=new Uint8Array(t),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1;let u,d=0;for(let l=c;l>=0;l--,d++)u=s[i-d]-a[c-d]-r,!0===u<0?(r=1,s[i-d]=u+10):(r=0,s[i-d]=u);if(r>0)for(let l=i-c+1;l>=0;l--,d++)if(u=s[i-d]-r,u<0)r=1,s[i-d]=u+10;else{r=0,s[i-d]=u;break}return s.slice()}class Sd extends or(Xe){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=lg.call(this)))}constructor({value:e,...r}={}){super(r),this._valueDec=0,r.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(wk(e))}get valueDec(){return this._valueDec}fromDER(e,r,n,o=0){const s=this.fromBER(e,r,n);if(s===-1)return s;const i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){const r=this.valueHexView;switch(!0){case(r[0]&128)!==0:{const n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(r,1),this.valueHexView=n}break;case(r[0]===0&&(r[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,r,n){const o=super.fromBER(e,r,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=this.valueHexView.length*8-1;let r=new Uint8Array(this.valueHexView.length*8/3),n=0,o;const s=this.valueHexView;let i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++)(o&1)===1&&(n===e?(r=Pk(jp(n),r),i="-"):r=Lk(r,jp(n))),n++,o>>=1}for(let c=0;c<r.length;c++)r[c]&&(a=!0),a&&(i+=Mp.charAt(r[c]));return a===!1&&(i+=Mp.charAt(0)),i}}Tg=Sd;Sd.NAME="IntegerValueBlock";Object.defineProperty(Tg.prototype,"valueHex",{set:function(t){this.valueHexView=new Uint8Array(t),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var ts;class mo extends Ve{constructor(e={}){super(e,Sd),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return $i(),BigInt(this.valueBlock.toString())}static fromBigInt(e){$i();const r=BigInt(e),n=new ka,o=r.toString(16).replace(/^-/,""),s=new Uint8Array(ee.FromHex(o));if(r<0){const a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;const u=BigInt(`0x${ee.ToHex(a)}`)+r,d=K.toUint8Array(ee.FromHex(u.toString(16)));d[0]|=128,n.write(d)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new ts({valueHex:n.final()})}convertToDER(){const e=new ts({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new ts({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}ts=mo;Y.Integer=ts;mo.NAME="INTEGER";var $g;class Oa extends mo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}$g=Oa;Y.Enumerated=$g;Oa.NAME="ENUMERATED";class yu extends or(Xe){constructor({valueDec:e=-1,isFirstSid:r=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=r}fromBER(e,r,n){if(!n)return r;const o=K.toUint8Array(e);if(!Sr(this,o,r,n))return-1;const s=o.subarray(r,r+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);const i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=eo(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}set valueBigInt(e){$i();let r=BigInt(e).toString(2);for(;r.length%7;)r="0"+r;const n=new Uint8Array(r.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(r.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}const r=ln(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",nr;const n=new Uint8Array(r.byteLength);if(!e){const o=new Uint8Array(r),s=r.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=ee.ToHex(this.valueHexView);else if(this.isFirstSid){let r=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",r-=40):(e="2.",r-=80),e+=r.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}yu.NAME="sidBlock";class Bg extends Xe{constructor({value:e=ot,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let o=r;for(;n>0;){const s=new yu;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){const r=[];for(let n=0;n<this.value.length;n++){const o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,nr;r.push(o)}return gd(r)}fromString(e){this.value=[];let r=0,n=0,o="",s=!1;do if(n=e.indexOf(".",r),n===-1?o=e.substring(r):o=e.substring(r,n),r=n+1,s){const i=this.value[0];let a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}const c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{const i=new yu;if(o>Number.MAX_SAFE_INTEGER){$i();const a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",r=!1;for(let n=0;n<this.value.length;n++){r=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),r?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}}Bg.NAME="ObjectIdentifierValueBlock";var Rg;class Ca extends Ve{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Bg),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Rg=Ca;Y.ObjectIdentifier=Rg;Ca.NAME="OBJECT IDENTIFIER";class gu extends or(On){constructor({valueDec:e=0,...r}={}){super(r),this.valueDec=e}fromBER(e,r,n){if(n===0)return r;const o=K.toUint8Array(e);if(!Sr(this,o,r,n))return-1;const s=o.subarray(r,r+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);const i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=eo(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}const r=ln(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",nr;const n=new Uint8Array(r.byteLength);if(!e){const o=new Uint8Array(r),s=r.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=ee.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}gu.NAME="relativeSidBlock";class Mg extends Xe{constructor({value:e=ot,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let o=r;for(;n>0;){const s=new gu;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,r){const n=[];for(let o=0;o<this.value.length;o++){const s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,nr;n.push(s)}return gd(n)}fromString(e){this.value=[];let r=0,n=0,o="";do{n=e.indexOf(".",r),n===-1?o=e.substring(r):o=e.substring(r,n),r=n+1;const s=new gu;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",r=!1;for(let n=0;n<this.value.length;n++){r=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),r&&(o=`{${o}}`),e+=o}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}}Mg.NAME="RelativeObjectIdentifierValueBlock";var _g;class Na extends Ve{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Mg),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}_g=Na;Y.RelativeObjectIdentifier=_g;Na.NAME="RelativeObjectIdentifier";var jg;class Pt extends et{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}jg=Pt;Y.Sequence=jg;Pt.NAME="SEQUENCE";var Dg;let Jt=class extends et{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Dg=Jt;Y.Set=Dg;Jt.NAME="SET";class Lg extends or(Xe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ot}toJSON(){return{...super.toJSON(),value:this.value}}}Lg.NAME="StringValueBlock";class Pg extends Lg{}Pg.NAME="SimpleStringValueBlock";class wt extends vd{constructor({...e}={}){super(e,Pg)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,K.toUint8Array(e))}fromString(e){const r=e.length,n=this.valueBlock.valueHexView=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}}wt.NAME="SIMPLE STRING";class Ug extends wt{fromBuffer(e){this.valueBlock.valueHexView=K.toUint8Array(e);try{this.valueBlock.value=ee.ToUtf8String(e)}catch(r){this.warnings.push(`Error during "decodeURIComponent": ${r}, using raw string`),this.valueBlock.value=ee.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(ee.FromUtf8String(e)),this.valueBlock.value=e}}Ug.NAME="Utf8StringValueBlock";var Vg;class kr extends Ug{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}Vg=kr;Y.Utf8String=Vg;kr.NAME="UTF8String";class Hg extends wt{fromBuffer(e){this.valueBlock.value=ee.ToUtf16String(e),this.valueBlock.valueHexView=K.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(ee.FromUtf16String(e))}}Hg.NAME="BmpStringValueBlock";var Fg;class Ta extends Hg{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}Fg=Ta;Y.BmpString=Fg;Ta.NAME="BMPString";class Wg extends wt{fromBuffer(e){const r=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(r);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(r))}fromString(e){const r=e.length,n=this.valueBlock.valueHexView=new Uint8Array(r*4);for(let o=0;o<r;o++){const s=ln(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;const a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}}Wg.NAME="UniversalStringValueBlock";var Kg;class $a extends Wg{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Kg=$a;Y.UniversalString=Kg;$a.NAME="UniversalString";var Gg;class Ba extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}Gg=Ba;Y.NumericString=Gg;Ba.NAME="NumericString";var qg;class Ra extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}qg=Ra;Y.PrintableString=qg;Ra.NAME="PrintableString";var zg;class Ma extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}zg=Ma;Y.TeletexString=zg;Ma.NAME="TeletexString";var Yg;class _a extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Yg=_a;Y.VideotexString=Yg;_a.NAME="VideotexString";var Xg;class ja extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}Xg=ja;Y.IA5String=Xg;ja.NAME="IA5String";var Jg;class Da extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}Jg=Da;Y.GraphicString=Jg;Da.NAME="GraphicString";var Zg;class _s extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}Zg=_s;Y.VisibleString=Zg;_s.NAME="VisibleString";var Qg;class La extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}Qg=La;Y.GeneralString=Qg;La.NAME="GeneralString";var ev;class Pa extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}ev=Pa;Y.CharacterString=ev;Pa.NAME="CharacterString";var tv;class js extends _s{constructor({value:e,valueDate:r,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}r&&(this.fromDate(r),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,K.toUint8Array(e)))}toBuffer(){const e=this.toString(),r=new ArrayBuffer(e.length),n=new Uint8Array(r);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return r}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}const o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){const r=new Array(7);return r[0]=ht(this.year<2e3?this.year-1900:this.year-2e3,2),r[1]=ht(this.month,2),r[2]=ht(this.day,2),r[3]=ht(this.hour,2),r[4]=ht(this.minute,2),r[5]=ht(this.second,2),r[6]="Z",r.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}tv=js;Y.UTCTime=tv;js.NAME="UTCTime";var rv;class Ua extends js{constructor(e={}){var r;super(e),(r=this.millisecond)!==null&&r!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){const e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let r=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),r=!0;else{const l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,m=n.indexOf("+"),p="";if(m===-1&&(m=n.indexOf("-"),l=-1),m!==-1){if(p=n.substring(m+1),n=n.substring(0,m),p.length!==2&&p.length!==4)throw new Error("Wrong input string for conversion");let h=parseInt(p.substring(0,2),10);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*h,p.length===4){if(h=parseInt(p.substring(2,4),10),isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");c=l*h}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){const l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){const l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}const d=i.exec(o);if(d===null)throw new Error("Wrong input string for conversion");for(let l=1;l<d.length;l++)switch(l){case 1:this.year=parseInt(d[l],10);break;case 2:this.month=parseInt(d[l],10);break;case 3:this.day=parseInt(d[l],10);break;case 4:this.hour=parseInt(d[l],10)+a;break;case 5:this.minute=parseInt(d[l],10)+c;break;case 6:this.second=parseInt(d[l],10);break;default:throw new Error("Wrong input string for conversion")}if(r===!1){const l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){const r=[];return r.push(ht(this.year,4)),r.push(ht(this.month,2)),r.push(ht(this.day,2)),r.push(ht(this.hour,2)),r.push(ht(this.minute,2)),r.push(ht(this.second,2)),this.millisecond!==0&&(r.push("."),r.push(ht(this.millisecond,3))),r.push("Z"),r.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}rv=Ua;Y.GeneralizedTime=rv;Ua.NAME="GeneralizedTime";var nv;class kd extends kr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}nv=kd;Y.DATE=nv;kd.NAME="DATE";var ov;class Ed extends kr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}ov=Ed;Y.TimeOfDay=ov;Ed.NAME="TimeOfDay";var sv;class xd extends kr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}sv=xd;Y.DateTime=sv;xd.NAME="DateTime";var iv;class Id extends kr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}iv=Id;Y.Duration=iv;Id.NAME="Duration";var av;class Od extends kr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}av=Od;Y.TIME=av;Od.NAME="TIME";class fn{constructor({name:e=ot,optional:r=!1}={}){this.name=e,this.optional=r}}class Cd extends fn{constructor({value:e=[],...r}={}){super(r),this.value=e}}class Bi extends fn{constructor({value:e=new fn,local:r=!1,...n}={}){super(n),this.value=e,this.local=r}}class Uk{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=K.toUint8Array(e)}constructor({data:e=Ea}={}){this.dataView=K.toUint8Array(e)}fromBER(e,r,n){const o=r+n;return this.dataView=K.toUint8Array(e).subarray(r,o),o}toBER(e){return this.dataView.slice().buffer}}function Tr(t,e,r){if(r instanceof Cd){for(const s of r.value)if(Tr(t,e,s).verified)return{verified:!0,result:t};{const s={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(Vc)&&(s.name=r.name),s}}if(r instanceof fn)return r.hasOwnProperty(Vc)&&(t[r.name]=e),{verified:!0,result:t};if(!(t instanceof Object))return{verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(r instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(kk in r))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(Ok in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(Ck in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const n=r.idBlock.toBER(!1);if(n.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(r.idBlock.fromBER(n,0,n.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(r.idBlock.hasOwnProperty(Ek)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==e.idBlock.tagClass)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(xk)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==e.idBlock.tagNumber)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(Ik)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:t};if(!(Sk in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==e.idBlock.isHexOnly)return{verified:!1,result:t};if(r.idBlock.isHexOnly){if(!(_p in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const s=r.idBlock.valueHexView,i=e.idBlock.valueHexView;if(s.length!==i.length)return{verified:!1,result:t};for(let a=0;a<s.length;a++)if(s[a]!==i[1])return{verified:!1,result:t}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&(t[r.name]=e)),r instanceof Y.Constructed){let s=0,i={verified:!1,result:{error:"Unknown error"}},a=r.valueBlock.value.length;if(a>0&&r.valueBlock.value[0]instanceof Bi&&(a=e.valueBlock.value.length),a===0)return{verified:!0,result:t};if(e.valueBlock.value.length===0&&r.valueBlock.value.length!==0){let c=!0;for(let u=0;u<r.valueBlock.value.length;u++)c=c&&(r.valueBlock.value[u].optional||!1);return c?{verified:!0,result:t}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&delete t[r.name]),t.error="Inconsistent object length",{verified:!1,result:t})}for(let c=0;c<a;c++)if(c-s>=e.valueBlock.value.length){if(r.valueBlock.value[c].optional===!1){const u={verified:!1,result:t};return t.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&(delete t[r.name],u.name=r.name)),u}}else if(r.valueBlock.value[0]instanceof Bi){if(i=Tr(t,e.valueBlock.value[c],r.valueBlock.value[0].value),i.verified===!1)if(r.valueBlock.value[0].optional)s++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&delete t[r.name]),i;if(Vc in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let u={};Nk in r.valueBlock.value[0]&&r.valueBlock.value[0].local?u=e:u=t,typeof u[r.valueBlock.value[0].name]>"u"&&(u[r.valueBlock.value[0].name]=[]),u[r.valueBlock.value[0].name].push(e.valueBlock.value[c])}}else if(i=Tr(t,e.valueBlock.value[c-s],r.valueBlock.value[c]),i.verified===!1)if(r.valueBlock.value[c].optional)s++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&delete t[r.name]),i;if(i.verified===!1){const c={verified:!1,result:t};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&(delete t[r.name],c.name=r.name)),c}return{verified:!0,result:t}}if(r.primitiveSchema&&_p in e.valueBlock){const s=xa(e.valueBlock.valueHexView);if(s.offset===-1){const i={verified:!1,result:s.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&(delete t[r.name],i.name=r.name)),i}return Tr(t,s.result,r.primitiveSchema)}return{verified:!0,result:t}}function Vk(t,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=xa(K.toUint8Array(t));return r.offset===-1?{verified:!1,result:r.result}:Tr(r.result,r.result,e)}const cv=Object.freeze(Object.defineProperty({__proto__:null,Any:fn,BaseBlock:Ve,BaseStringBlock:vd,BitString:on,BmpString:Ta,Boolean:Ia,CharacterString:Pa,Choice:Cd,Constructed:et,DATE:kd,DEFAULT_MAX_CONTENT_LENGTH:wg,DEFAULT_MAX_DEPTH:vg,DEFAULT_MAX_NODES:bg,DateTime:xd,Duration:Id,EndOfContent:wd,Enumerated:Oa,GeneralString:La,GeneralizedTime:Ua,GraphicString:Da,HexBlock:or,IA5String:ja,Integer:mo,Null:dn,NumericString:Ba,ObjectIdentifier:Ca,OctetString:nn,Primitive:Rs,PrintableString:Ra,RawData:Uk,RelativeObjectIdentifier:Na,Repeated:Bi,Sequence:Pt,Set:Jt,TIME:Od,TeletexString:Ma,TimeOfDay:Ed,UTCTime:js,UniversalString:$a,Utf8String:kr,ValueBlock:Xe,VideotexString:_a,ViewWriter:ka,VisibleString:_s,compareSchema:Tr,fromBER:Gn,verifySchema:Vk},Symbol.toStringTag,{value:"Module"})),Hk="[object ArrayBuffer]",Fk="[object SharedArrayBuffer]";function uv(t){return Object.prototype.toString.call(t)}function Wk(t){if(ArrayBuffer.isView(t))return!0;if(!t||typeof t!="object")return!1;const e=t;return typeof e.byteOffset=="number"&&typeof e.byteLength=="number"&&Nd(e.buffer)}function lv(t){return uv(t)===Hk}function Kk(t){return typeof SharedArrayBuffer<"u"&&uv(t)===Fk}function Nd(t){return lv(t)||Kk(t)}function Gk(t){return Wk(t)}function Va(t){return Nd(t)||Gk(t)}function dv(t){if(!Va(t))throw new TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function pn(t){return dv(t),Nd(t)?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function Nt(t){if(dv(t),lv(t))return t;const e=new ArrayBuffer(t.byteLength);return new Uint8Array(e).set(pn(t)),e}function qk(t,e,r={}){const n=pn(t),o=pn(e);if(!r.constantTime&&n.byteLength!==o.byteLength)return!1;const s=Math.max(n.byteLength,o.byteLength);let i=n.byteLength^o.byteLength;for(let a=0;a<s;a++)i|=(n[a]??0)^(o[a]??0);return i===0}function fv(t){const e=pn(t);let r="";for(const n of e)r+=String.fromCharCode(n);return r}function pv(t){const e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r)&255;return e}function zk(t){return typeof t=="string"}const Yk=/^[0-9a-f]$/i,Xk=[" "," ",`
106
+ `,"\r",":","-","."];function Jk(t){return t.separators==="none"?[]:!t.separators||t.separators==="common"?Xk:t.separators}function Zk(t){if(!t)throw new TypeError("Hex separators must be non-empty strings")}function Qk(t,e,r){for(const n of r)if(t.startsWith(n,e))return n}function eE(t){const e=/[A-F]/.test(t),r=/[a-f]/.test(t);return e&&!r?"upper":"lower"}function tE(t){const e=/\r\n|\n/.exec(t);if(e)return e[0]===`\r
89
107
  `?`\r
90
108
  `:`
91
- `}function fp(t){return t.replace(/[^0-9a-f]/gi,"")}function Dk(t){const e=t.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(e.length<3)return;const r=e.filter((i,a)=>a%2===0),n=e.filter((i,a)=>a%2===1),s=n[0];if(!s||n.some(i=>i!==s)||r.some(i=>i.length===0||i.length%2!==0))return;const o=r[0]?.length??0;if(o&&!r.slice(0,-1).some(i=>i.length!==o)&&!((r[r.length-1]?.length??0)>o))return{size:o/2,separator:s}}function Pk(t){const e=t.trim(),r=/^0x/i.test(e)?"0x":"",n=r?e.slice(2):e,s=jk(n),o=n.split(/\r\n|\n/).filter(u=>u.length>0),i=o[0]?.trim()??"",a=Dk(i),c={case:Mk(e),prefix:r};if(a&&(c.group=a),s&&o.length>1){const u=fp(o[0]??"").length/2;u>0&&o.slice(0,-1).every(l=>fp(l).length/2===u)&&(c.line={bytesPerLine:u,separator:s})}return c}function Lk(t,e){const r=e.allowPrefix??!0,n=[...$k(e)].sort((a,c)=>c.length-a.length);for(const a of n)Rk(a);let s=t.trim();if(/^0x/i.test(s)){if(!r)throw new TypeError("Hexadecimal text must not include a 0x prefix");s=s.slice(2)}let o="",i=!1;for(let a=0;a<s.length;){const c=s[a]??"";if(Tk.test(c)){o+=c,i=!1,a+=1;continue}const u=_k(s,a,n);if(!u)throw new TypeError("Input is not valid hexadecimal text");if(e.strict&&(i||o.length===0))throw new TypeError("Hexadecimal text contains misplaced separators");i=!0,a+=u.length}if(e.strict&&i&&o.length>0)throw new TypeError("Hexadecimal text must not end with a separator");if(o.length%2!==0){if(!e.allowOddLength)throw new TypeError("Hexadecimal text must contain an even number of characters");o=`0${o}`}return o.toLowerCase()}function pp(t,e){if(!e)return t.join("");if(!Number.isInteger(e.size)||e.size<1)throw new RangeError("Hex group size must be a positive integer");const r=[];for(let n=0;n<t.length;n+=e.size)r.push(t.slice(n,n+e.size).join(""));return r.join(e.separator)}function Oa(t,e={}){return Lk(t,e)}function Uk(t,e={}){if(typeof t!="string")return!1;try{return Oa(t,e),!0}catch{return!1}}function Na(t,e={}){const r=tn(t),n=e.case??"lower",s=Array.from(r,i=>{const a=i.toString(16).padStart(2,"0");return n==="upper"?a.toUpperCase():a});let o="";if(e.line){const i=e.line.bytesPerLine;if(!Number.isInteger(i)||i<1)throw new RangeError("Hex bytesPerLine must be a positive integer");const a=e.line.separator??`
92
- `,c=[];for(let u=0;u<s.length;u+=i)c.push(pp(s.slice(u,u+i),e.group));o=c.join(a)}else o=pp(s,e.group);return`${e.prefix??""}${o}`}function Rg(t,e={}){const r=Oa(t,e),n=new Uint8Array(r.length/2);for(let s=0;s<r.length;s+=2)n[s/2]=Number.parseInt(r.slice(s,s+2),16);return n}function Vk(t,e={}){const r=Oa(t,e);return{bytes:Rg(r),format:Pk(t),normalized:r}}function Hk(t,e){return Na(t,e)}function Fk(t){return new TextEncoder().encode(t)}function Wk(t){return new TextDecoder("utf-8",{fatal:!1}).decode(tn(t))}function _g(t,e={}){const r=new ArrayBuffer(t.length*2),n=new DataView(r);for(let s=0;s<t.length;s++)n.setUint16(s*2,t.charCodeAt(s),e.littleEndian??!1);return new Uint8Array(r)}function Mg(t,e={}){const r=At(t),n=new DataView(r);let s="";for(let o=0;o<r.byteLength;o+=2)s+=String.fromCharCode(n.getUint16(o,e.littleEndian??!1));return s}const Kk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function jg(){return globalThis.Buffer}function Ta(t){return t.replace(/[\n\r\t ]/g,"")}function Gk(t){const e=t.length%4;return e?t+"=".repeat(4-e):t}function ad(t){if(typeof t!="string")return!1;const e=Ta(t);return e===""||Kk.test(e)}function Dg(t,e){const r=tn(t),n=jg();return n?n.from(r).toString("base64"):btoa(Bg(r))}function Pg(t,e){const r=Ta(t);if(!ad(r))throw new TypeError("Input is not valid Base64 text");const n=jg();return n?new Uint8Array(n.from(r,"base64")):$g(atob(r))}const to={encode:Dg,decode:Pg,is:ad,normalize:Ta,pad:Gk},qk=/^[A-Za-z0-9_-]*$/;function cd(t){return t.replace(/[\n\r\t ]/g,"")}function Lg(t){return typeof t=="string"&&qk.test(cd(t))}function zk(t,e){return to.encode(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Yk(t,e){const r=cd(t);if(!Lg(r))throw new TypeError("Input is not valid Base64Url text");return to.decode(to.pad(r.replace(/-/g,"+").replace(/_/g,"/")))}const Xk=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,hp=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function Ug(t){if(!Xk.test(t))throw new TypeError(`Invalid PEM label '${t}'`)}function Jk(t,e){const r=[];for(let n=0;n<t.length;n+=e)r.push(t.slice(n,n+e));return r}function Zk(t){const r=t.trim().replace(/\r\n/g,`
109
+ `}function Dp(t){return t.replace(/[^0-9a-f]/gi,"")}function rE(t){const e=t.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(e.length<3)return;const r=e.filter((i,a)=>a%2===0),n=e.filter((i,a)=>a%2===1),o=n[0];if(!o||n.some(i=>i!==o)||r.some(i=>i.length===0||i.length%2!==0))return;const s=r[0]?.length??0;if(s&&!r.slice(0,-1).some(i=>i.length!==s)&&!((r[r.length-1]?.length??0)>s))return{size:s/2,separator:o}}function nE(t){const e=t.trim(),r=/^0x/i.test(e)?"0x":"",n=r?e.slice(2):e,o=tE(n),s=n.split(/\r\n|\n/).filter(u=>u.length>0),i=s[0]?.trim()??"",a=rE(i),c={case:eE(e),prefix:r};if(a&&(c.group=a),o&&s.length>1){const u=Dp(s[0]??"").length/2;u>0&&s.slice(0,-1).every(d=>Dp(d).length/2===u)&&(c.line={bytesPerLine:u,separator:o})}return c}function oE(t,e){const r=e.allowPrefix??!0,n=[...Jk(e)].sort((a,c)=>c.length-a.length);for(const a of n)Zk(a);let o=t.trim();if(/^0x/i.test(o)){if(!r)throw new TypeError("Hexadecimal text must not include a 0x prefix");o=o.slice(2)}let s="",i=!1;for(let a=0;a<o.length;){const c=o[a]??"";if(Yk.test(c)){s+=c,i=!1,a+=1;continue}const u=Qk(o,a,n);if(!u)throw new TypeError("Input is not valid hexadecimal text");if(e.strict&&(i||s.length===0))throw new TypeError("Hexadecimal text contains misplaced separators");i=!0,a+=u.length}if(e.strict&&i&&s.length>0)throw new TypeError("Hexadecimal text must not end with a separator");if(s.length%2!==0){if(!e.allowOddLength)throw new TypeError("Hexadecimal text must contain an even number of characters");s=`0${s}`}return s.toLowerCase()}function Lp(t,e){if(!e)return t.join("");if(!Number.isInteger(e.size)||e.size<1)throw new RangeError("Hex group size must be a positive integer");const r=[];for(let n=0;n<t.length;n+=e.size)r.push(t.slice(n,n+e.size).join(""));return r.join(e.separator)}function Ha(t,e={}){return oE(t,e)}function sE(t,e={}){if(typeof t!="string")return!1;try{return Ha(t,e),!0}catch{return!1}}function Fa(t,e={}){const r=pn(t),n=e.case??"lower",o=Array.from(r,i=>{const a=i.toString(16).padStart(2,"0");return n==="upper"?a.toUpperCase():a});let s="";if(e.line){const i=e.line.bytesPerLine;if(!Number.isInteger(i)||i<1)throw new RangeError("Hex bytesPerLine must be a positive integer");const a=e.line.separator??`
110
+ `,c=[];for(let u=0;u<o.length;u+=i)c.push(Lp(o.slice(u,u+i),e.group));s=c.join(a)}else s=Lp(o,e.group);return`${e.prefix??""}${s}`}function hv(t,e={}){const r=Ha(t,e),n=new Uint8Array(r.length/2);for(let o=0;o<r.length;o+=2)n[o/2]=Number.parseInt(r.slice(o,o+2),16);return n}function iE(t,e={}){const r=Ha(t,e);return{bytes:hv(r),format:nE(t),normalized:r}}function aE(t,e){return Fa(t,e)}function cE(t){return new TextEncoder().encode(t)}function uE(t){return new TextDecoder("utf-8",{fatal:!1}).decode(pn(t))}function mv(t,e={}){const r=new ArrayBuffer(t.length*2),n=new DataView(r);for(let o=0;o<t.length;o++)n.setUint16(o*2,t.charCodeAt(o),e.littleEndian??!1);return new Uint8Array(r)}function yv(t,e={}){const r=Nt(t),n=new DataView(r);let o="";for(let s=0;s<r.byteLength;s+=2)o+=String.fromCharCode(n.getUint16(s,e.littleEndian??!1));return o}const lE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function gv(){return globalThis.Buffer}function Wa(t){return t.replace(/[\n\r\t ]/g,"")}function dE(t){const e=t.length%4;return e?t+"=".repeat(4-e):t}function Td(t){if(typeof t!="string")return!1;const e=Wa(t);return e===""||lE.test(e)}function vv(t,e){const r=pn(t),n=gv();return n?n.from(r).toString("base64"):btoa(fv(r))}function bv(t,e){const r=Wa(t);if(!Td(r))throw new TypeError("Input is not valid Base64 text");const n=gv();return n?new Uint8Array(n.from(r,"base64")):pv(atob(r))}const gs={encode:vv,decode:bv,is:Td,normalize:Wa,pad:dE},fE=/^[A-Za-z0-9_-]*$/;function $d(t){return t.replace(/[\n\r\t ]/g,"")}function wv(t){return typeof t=="string"&&fE.test($d(t))}function pE(t,e){return gs.encode(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function hE(t,e){const r=$d(t);if(!wv(r))throw new TypeError("Input is not valid Base64Url text");return gs.decode(gs.pad(r.replace(/-/g,"+").replace(/_/g,"/")))}const mE=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,Pp=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function Av(t){if(!mE.test(t))throw new TypeError(`Invalid PEM label '${t}'`)}function yE(t,e){const r=[];for(let n=0;n<t.length;n+=e)r.push(t.slice(n,n+e));return r}function gE(t){const r=t.trim().replace(/\r\n/g,`
93
111
  `).split(`
94
- `).map(o=>o.trim()).filter(Boolean),n={};let s=0;for(;s<r.length;s++){const o=r[s],i=o.indexOf(":");if(i<=0)break;n[o.slice(0,i).trim()]=o.slice(i+1).trim()}return{headers:Object.keys(n).length?n:void 0,base64Lines:r.slice(s),base64Text:r.slice(s).join("")}}function Qk(t){return/\r\n/.test(t)?`\r
112
+ `).map(s=>s.trim()).filter(Boolean),n={};let o=0;for(;o<r.length;o++){const s=r[o],i=s.indexOf(":");if(i<=0)break;n[s.slice(0,i).trim()]=s.slice(i+1).trim()}return{headers:Object.keys(n).length?n:void 0,base64Lines:r.slice(o),base64Text:r.slice(o).join("")}}function vE(t){return/\r\n/.test(t)?`\r
95
113
  `:`
96
- `}function Vg(t,e={}){const r=[],n=e.label;let s;for(hp.lastIndex=0;s=hp.exec(t);){const o=s[1].trim();if(n&&o!==n)continue;Ug(o);const i=Zk(s[2]);r.push({label:o,data:to.decode(i.base64Text),headers:i.headers,lineLength:i.base64Lines[0]?.length??64,newline:Qk(s[0])})}if(e.strict&&r.length===0)throw new TypeError(n?`No PEM block with label '${n}' was found`:"No PEM blocks were found");return r}function ud(t,e,r={}){Ug(t);const n=r.lineLength??64;if(!Number.isInteger(n)||n<1)throw new RangeError("PEM lineLength must be a positive integer");const s=r.newline??`
97
- `,o=[`-----BEGIN ${t}-----`];if(r.headers){for(const[i,a]of Object.entries(r.headers))o.push(`${i}: ${a}`);o.push("")}return o.push(...Jk(to.encode(e),n)),o.push(`-----END ${t}-----`),`${o.join(s)}${s}`}function ex(t,e={}){return Vg(t,e).map(({lineLength:r,newline:n,...s})=>s)}function tx(t,e){const[r]=ex(t,{label:e,strict:!0});return r.data}function rx(t,e={}){const[r]=Vg(t,{...e,strict:!0}),n={label:r.label,headers:r.headers,lineLength:r.lineLength,newline:r.newline};return{bytes:r.data,format:n,normalized:ud(r.label,r.data,n)}}function nx(t,e){return ud(e.label,t,e)}const sx={name:"pem",encode:(t,e)=>{if(!e?.label)throw new TypeError("PEM label is required");return ud(e.label,t,e)},decode:(t,e)=>tx(t,e?.label),format:nx,is:t=>typeof t=="string"&&/-----BEGIN [^-]+-----/.test(t),parse:rx};function Ut(t){return t.trim().toLowerCase()}function ox(t){return t instanceof Error?t:new Error(String(t))}function mp(t,e,r){for(const n of[r.name,...r.aliases??[]])t.delete(Ut(n));e.delete(Ut(r.name))}function Ec(t,e,r){const n=t[r];if(typeof n!="function")throw new Error(`Converter '${e}' does not support ${r}()`);return n}function ix(t,e,r){const n=Ut(r.name||t),s=e.trim();if(!s)return 0;let o=!1;r.is&&(o=r.is(e));let i=!1;try{r.decode(e),i=!0}catch{i=!1}if(!o&&!i)return 0;switch(n){case"pem":return/-----BEGIN [^-]+-----/.test(e)?1:0;case"hex":{const a=s.replace(/^0x/i,"").replace(/[\s:.-]/g,"");return!a||/[^0-9a-f]/i.test(a)||a.length%2!==0?0:/^0x/i.test(s)||/[:\s.-]/.test(s)?.95:/[a-f]/.test(s)||/[A-F]/.test(s)?.8:.45}case"base64url":return/[-_]/.test(s)?.95:/=/.test(s)?.1:.6;case"base64":return/[+/=]/.test(s)?.9:.55;case"binary":case"utf8":case"utf16be":case"utf16le":return 0;default:return o&&i?.75:.5}}function ax(t=[]){const e=new Map,r=new Set,n={register(s,o={}){if(!s.name||!Ut(s.name))throw new TypeError("Converter name is required");const i=[...new Set([s.name,...s.aliases??[]].map(Ut))],a=new Set;for(const c of i){const u=e.get(c);if(u){if(!o.override)throw new Error(`Converter '${c}' is already registered`);a.add(u)}}for(const c of a)mp(e,r,c);for(const c of i)e.set(c,s);return r.add(Ut(s.name)),this},unregister(s){const o=e.get(Ut(s));return o?(mp(e,r,o),!0):!1},has(s){return e.has(Ut(s))},get(s){const o=e.get(Ut(s));if(!o)throw new Error(`Converter '${s}' is not registered`);return o},list(){return[...r].map(s=>this.get(s))},encode(s,o,i){return this.get(s).encode(o,i)},decode(s,o,i){return this.get(s).decode(o,i)},tryDecode(s,o,i){try{return{ok:!0,bytes:this.decode(s,o,i)}}catch(a){return{ok:!1,error:ox(a)}}},normalize(s,o,i){const a=this.get(s);return Ec(a,s,"normalize").call(a,o,i)},parse(s,o,i){const a=this.get(s);return Ec(a,s,"parse").call(a,o,i)},format(s,o,i){const a=this.get(s);return Ec(a,s,"format").call(a,o,i)},transcode(s,o){const i=this.decode(o.from,s,o.fromOptions);return this.encode(o.to,i,o.toOptions)},detect(s,o={}){const i=o.formats?.length?o.formats.map(c=>String(c)):this.list().map(c=>c.name).filter(c=>!["binary","utf8","utf16be","utf16le"].includes(Ut(c))),a=new Map;for(const c of i){const u=this.get(c),l=ix(c,s,u);if(l<=0)continue;const d=u.name,m=a.get(d);(!m||l>m.confidence)&&a.set(d,{format:d,confidence:l})}return[...a.values()].sort((c,u)=>u.confidence-c.confidence)}};for(const s of t)n.register(s);return n}const cx={name:"binary",aliases:["latin1"],encode:Bg,decode:$g,is:Nk},ux={name:"hex",encode:Na,decode:Rg,format:Hk,is:Uk,normalize:Oa,parse:Vk},lx={name:"base64",aliases:["b64"],encode:Dg,decode:Pg,is:ad,normalize:Ta},dx={name:"base64url",aliases:["base64-url","b64url"],encode:zk,decode:Yk,is:Lg,normalize:cd},fx={name:"utf8",aliases:["utf-8"],encode:t=>Wk(t),decode:t=>Fk(t),is:t=>typeof t=="string"},px={name:"utf16be",aliases:["utf16","utf-16","utf-16be"],encode:t=>Mg(t),decode:t=>_g(t),is:t=>typeof t=="string"},hx={name:"utf16le",aliases:["utf-16le","ucs2","usc2"],encode:t=>Mg(t,{littleEndian:!0}),decode:t=>_g(t,{littleEndian:!0}),is:t=>typeof t=="string"},mx=[cx,ux,lx,dx,fx,px,hx,sx];ax(mx);var O;(function(t){t[t.Sequence=0]="Sequence",t[t.Set=1]="Set",t[t.Choice=2]="Choice"})(O||(O={}));var b;(function(t){t[t.Any=1]="Any",t[t.Boolean=2]="Boolean",t[t.OctetString=3]="OctetString",t[t.BitString=4]="BitString",t[t.Integer=5]="Integer",t[t.Enumerated=6]="Enumerated",t[t.ObjectIdentifier=7]="ObjectIdentifier",t[t.Utf8String=8]="Utf8String",t[t.BmpString=9]="BmpString",t[t.UniversalString=10]="UniversalString",t[t.NumericString=11]="NumericString",t[t.PrintableString=12]="PrintableString",t[t.TeletexString=13]="TeletexString",t[t.VideotexString=14]="VideotexString",t[t.IA5String=15]="IA5String",t[t.GraphicString=16]="GraphicString",t[t.VisibleString=17]="VisibleString",t[t.GeneralString=18]="GeneralString",t[t.CharacterString=19]="CharacterString",t[t.UTCTime=20]="UTCTime",t[t.GeneralizedTime=21]="GeneralizedTime",t[t.DATE=22]="DATE",t[t.TimeOfDay=23]="TimeOfDay",t[t.DateTime=24]="DateTime",t[t.Duration=25]="Duration",t[t.TIME=26]="TIME",t[t.Null=27]="Null",t[t.RelativeObjectIdentifier=28]="RelativeObjectIdentifier"})(b||(b={}));class Ba{unusedBits=0;value=new ArrayBuffer(0);constructor(e,r=0){if(e)if(typeof e=="number")this.fromNumber(e);else if(Ca(e))this.unusedBits=r,this.value=At(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof qr))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=At(e.valueBlock.valueHex),this}toASN(){return new qr({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new qr({name:e})}toNumber(){let e="";const r=new Uint8Array(this.value);for(const n of r)e+=n.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let r=e.toString(2);const n=r.length+7>>3;this.unusedBits=(n<<3)-r.length;const s=new Uint8Array(n);r=r.padStart(n<<3,"0").split("").reverse().join("");let o=0;for(;o<n;)s[o]=parseInt(r.slice(o<<3,(o<<3)+8),2),o++;this.value=s.buffer}}class ue{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):Ca(e)?this.buffer=At(e):Array.isArray(e)?this.buffer=new Uint8Array(e).buffer:this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Gr))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=At(e.valueBlock.valueHex),this}toASN(){return new Gr({valueHex:this.buffer})}toSchema(e){return new Gr({name:e})}}const yx={fromASN:t=>t instanceof Qr?null:At(t.valueBeforeDecodeView),toASN:t=>{if(t===null)return new Qr;const e=_n(t);if(e.result.error)throw new Error(e.result.error);return e.result}},gx={fromASN:t=>t.valueBlock.valueHexView.byteLength>=4?t.valueBlock.toString():t.valueBlock.valueDec,toASN:t=>new ts({value:+t})},vx={fromASN:t=>t.valueBlock.valueDec,toASN:t=>new pa({value:t})},be={fromASN:t=>At(t.valueBlock.valueHexView),toASN:t=>new ts({valueHex:t})},bx={fromASN:t=>At(t.valueBlock.valueHexView),toASN:t=>new qr({valueHex:t})},wx={fromASN:t=>t.valueBlock.toString(),toASN:t=>new ha({value:t})},Ax={fromASN:t=>t.valueBlock.toString(),toASN:t=>new ma({value:t})},Sx={fromASN:t=>t.valueBlock.value,toASN:t=>new fa({value:t})},wi={fromASN:t=>At(t.valueBlock.valueHexView),toASN:t=>new Gr({valueHex:t})},kx={fromASN:t=>new ue(t.getValue()),toASN:t=>t.toASN()};function St(t){return{fromASN:e=>e.valueBlock.value,toASN:e=>new t({value:e})}}const Hg=St(vr),xx=St(ya),Ex=St(ga),Ix=St(va),Cx=St(ba),Ox=St(wa),Nx=St(Aa),Tx=St(Sa),Bx=St(ka),$x=St(wo),Rx=St(xa),_x=St(Ea),Mx={fromASN:t=>t.toDate(),toASN:t=>new Ao({valueDate:t})},jx={fromASN:t=>t.toDate(),toASN:t=>new Ia({valueDate:t})},Dx={fromASN:()=>null,toASN:()=>new Qr};function Vs(t){switch(t){case b.Any:return yx;case b.BitString:return bx;case b.BmpString:return xx;case b.Boolean:return Sx;case b.CharacterString:return _x;case b.Enumerated:return vx;case b.GeneralString:return Rx;case b.GeneralizedTime:return jx;case b.GraphicString:return Bx;case b.IA5String:return Tx;case b.Integer:return gx;case b.Null:return Dx;case b.NumericString:return Ix;case b.ObjectIdentifier:return wx;case b.RelativeObjectIdentifier:return Ax;case b.OctetString:return wi;case b.PrintableString:return Cx;case b.TeletexString:return Ox;case b.UTCTime:return Mx;case b.UniversalString:return Ex;case b.Utf8String:return Hg;case b.VideotexString:return Nx;case b.VisibleString:return $x;default:return null}}function ir(t){return typeof t=="function"&&t.prototype?t.prototype.toASN&&t.prototype.fromASN?!0:ir(t.prototype):!!(t&&typeof t=="object"&&"toASN"in t&&"fromASN"in t)}function Fg(t){if(t){const e=Object.getPrototypeOf(t);return e?.prototype?.constructor===Array?!0:Fg(e)}return!1}function Px(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;const r=new Uint8Array(t),n=new Uint8Array(e);for(let s=0;s<t.byteLength;s++)if(r[s]!==n[s])return!1;return!0}class Lx{items=new WeakMap;has(e){return this.items.has(e)}get(e,r=!1){const n=this.items.get(e);if(!n)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(r&&!n.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return n}cache(e){const r=this.get(e);r.schema||(r.schema=this.create(e,!0))}createDefault(e){const r={type:O.Sequence,items:{}},n=this.findParentSchema(e);return n&&(Object.assign(r,n),r.items=Object.assign({},r.items,n.items)),r}create(e,r){const n=this.items.get(e)||this.createDefault(e),s=[];for(const o in n.items){const i=n.items[o],a=r?o:"";let c;if(typeof i.type=="number"){const l=b[i.type],d=Cg[l];if(!d)throw new Error(`Cannot get ASN1 class by name '${l}'`);c=new d({name:a})}else ir(i.type)?c=new i.type().toSchema(a):i.optional?this.get(i.type).type===O.Choice?c=new en({name:a}):(c=this.create(i.type,!1),c.name=a):c=new en({name:a});const u=!!i.optional||i.defaultValue!==void 0;if(i.repeated){c.name="";const l=i.repeated==="set"?Ft:$t;c=new l({name:"",value:[new bi({name:a,value:c})]})}if(i.context!==null&&i.context!==void 0)if(i.implicit)if(typeof i.type=="number"||ir(i.type)){const l=i.repeated?ze:vo;s.push(new l({name:a,optional:u,idBlock:{tagClass:3,tagNumber:i.context}}))}else{this.cache(i.type);const l=!!i.repeated;let d=l?c:this.get(i.type,!0).schema;d="valueBlock"in d?d.valueBlock.value:d.value,s.push(new ze({name:l?"":a,optional:u,idBlock:{tagClass:3,tagNumber:i.context},value:d}))}else s.push(new ze({optional:u,idBlock:{tagClass:3,tagNumber:i.context},value:[c]}));else c.optional=u,s.push(c)}switch(n.type){case O.Sequence:return new $t({value:s,name:""});case O.Set:return new Ft({value:s,name:""});case O.Choice:return new od({value:s,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,r){return this.items.set(e,r),this}findParentSchema(e){const r=Object.getPrototypeOf(e);return r?this.items.get(r)||this.findParentSchema(r):null}}const De=new Lx,$=t=>e=>{let r;De.has(e)?r=De.get(e):(r=De.createDefault(e),De.set(e,r)),Object.assign(r,t)},h=t=>(e,r)=>{let n;De.has(e.constructor)?n=De.get(e.constructor):(n=De.createDefault(e.constructor),De.set(e.constructor,n));const s=Object.assign({},t);if(typeof s.type=="number"&&!s.converter){const o=Vs(t.type);if(!o)throw new Error(`Cannot get default converter for property '${r}' of ${e.constructor.name}`);s.converter=o}s.raw=t.raw,n.items[r]=s};class ms extends Error{schemas=[]}class Ux{static parse(e,r,n){const s=_n(At(e),n?.berOptions);if(s.result.error)throw new Error(s.result.error);return this.fromASN(s.result,r,n)}static fromASN(e,r,n){try{if(ir(r))return new r().fromASN(e);const s=De.get(r);De.cache(r);let o=s.schema;const i=this.handleChoiceTypes(e,s,r,o,n);if(i?.result)return i.result;i?.targetSchema&&(o=i.targetSchema);const a=this.handleSequenceTypes(e,s,r,o),c=new r;return Fg(r)?this.handleArrayTypes(e,s,r,n):(this.processSchemaItems(s,a,c,n),c)}catch(s){throw s instanceof ms&&s.schemas.push(r.name),s}}static handleChoiceTypes(e,r,n,s,o){if(e.constructor===ze&&r.type===O.Choice&&e.idBlock.tagClass===3)for(const i in r.items){const a=r.items[i];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type=="function"&&De.has(a.type)){const c=De.get(a.type);if(c&&c.type===O.Sequence){const u=new $t;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in u.valueBlock){u.valueBlock.value=e.valueBlock.value;const l=this.fromASN(u,a.type,o),d=new n;return d[i]=l,{result:d}}}}}else if(e.constructor===ze&&r.type!==O.Choice){const i=new ze({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:r.schema.valueBlock.value});for(const a in r.items)delete e[a];return{targetSchema:i}}return null}static handleSequenceTypes(e,r,n,s){if(r.type===O.Sequence){const o=xr({},e,s);if(!o.verified)throw new ms(`Data does not match to ${n.name} ASN1 schema.${o.result.error?` ${o.result.error}`:""}`);return o}else{const o=xr({},e,s);if(!o.verified)throw new ms(`Data does not match to ${n.name} ASN1 schema.${o.result.error?` ${o.result.error}`:""}`);return o}}static processRepeatedField(e,r,n){let s=e.slice(r);if(s.length===1&&s[0].constructor.name==="Sequence"){const o=s[0];o.valueBlock&&o.valueBlock.value&&Array.isArray(o.valueBlock.value)&&(s=o.valueBlock.value)}if(typeof n.type=="number"){const o=Vs(n.type);if(!o)throw new Error(`No converter for ASN.1 type ${n.type}`);return s.filter(i=>i&&i.valueBlock).map(i=>{try{return o.fromASN(i)}catch{return}}).filter(i=>i!==void 0)}else return s.filter(o=>o&&o.valueBlock).map(o=>{try{return this.fromASN(o,n.type)}catch{return}}).filter(o=>o!==void 0)}static processPrimitiveField(e,r){const n=Vs(r.type);if(!n)throw new Error(`No converter for ASN.1 type ${r.type}`);return n.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type=="function"&&De.has(e.type)&&De.get(e.type).type===O.Choice}static processOptionalChoiceField(e,r){try{return{processed:!0,value:this.fromASN(e,r.type)}}catch(n){if(n instanceof ms&&/Wrong values for Choice type/.test(n.message))return{processed:!1};throw n}}static handleArrayTypes(e,r,n,s){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const o=r.itemType;if(typeof o=="number"){const i=Vs(o);if(!i)throw new Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);return n.from(e.valueBlock.value,a=>i.fromASN(a))}else return n.from(e.valueBlock.value,i=>this.fromASN(i,o,s))}static processSchemaItems(e,r,n,s){for(const o in e.items){const i=r.result[o];if(!i)continue;const a=e.items[o],c=a.type;let u;typeof c=="number"||ir(c)?u=this.processPrimitiveSchemaItem(i,a,c,s):u=this.processComplexSchemaItem(i,a,c,s),u&&typeof u=="object"&&"value"in u&&"raw"in u?(n[o]=u.value,n[`${o}Raw`]=u.raw):n[o]=u}}static processPrimitiveSchemaItem(e,r,n,s){const o=r.converter??(ir(n)?new n:null);if(!o)throw new Error("Converter is empty");return r.repeated?this.processRepeatedPrimitiveItem(e,r,o,s):this.processSinglePrimitiveItem(e,r,n,o,s)}static processRepeatedPrimitiveItem(e,r,n,s){if(r.implicit){const o=r.repeated==="sequence"?$t:Ft,i=new o;i.valueBlock=e.valueBlock;const a=_n(i.toBER(!1),s?.berOptions);if(a.offset===-1)throw new Error(`Cannot parse the child item. ${a.result.error}`);if(!("value"in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const c=a.result.valueBlock.value;return Array.from(c,u=>n.fromASN(u))}else return Array.from(e,o=>n.fromASN(o))}static processSinglePrimitiveItem(e,r,n,s,o){let i=e;if(r.implicit){let a;if(ir(n))a=new n().toSchema("");else{const c=b[n],u=Cg[c];if(!u)throw new Error(`Cannot get '${c}' class from asn1js module`);a=new u}a.valueBlock=i.valueBlock,i=_n(a.toBER(!1),o?.berOptions).result}return s.fromASN(i)}static processComplexSchemaItem(e,r,n,s){if(r.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,o=>this.fromASN(o,n,s))}else{const o=this.handleImplicitTagging(e,r,n);if(this.isOptionalChoiceField(r))try{return this.fromASN(o,n,s)}catch(i){if(i instanceof ms&&/Wrong values for Choice type/.test(i.message))return;throw i}else{const i=this.fromASN(o,n,s);return r.raw?{value:i,raw:e.valueBeforeDecodeView}:i}}}static handleImplicitTagging(e,r,n){if(r.implicit&&typeof r.context=="number"){const s=De.get(n);if(s.type===O.Sequence){const o=new $t;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in o.valueBlock)return o.valueBlock.value=e.valueBlock.value,o}else if(s.type===O.Set){const o=new Ft;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in o.valueBlock)return o.valueBlock.value=e.valueBlock.value,o}}return e}}class ld{static serialize(e){return e instanceof _e?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&ir(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");const r=e.constructor,n=De.get(r);De.cache(r);let s=[];if(n.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if(typeof n.itemType=="number"){const i=Vs(n.itemType);if(!i)throw new Error(`Cannot get default converter for array item of ${r.name} ASN1 schema`);s=e.map(a=>i.toASN(a))}else s=e.map(i=>this.toAsnItem({type:n.itemType},"[]",r,i))}else for(const i in n.items){const a=n.items[i],c=e[i];if(c===void 0||a.defaultValue===c||typeof a.defaultValue=="object"&&typeof c=="object"&&Px(this.serialize(a.defaultValue),this.serialize(c)))continue;const u=ld.toAsnItem(a,i,r,c);if(typeof a.context=="number")if(a.implicit)if(!a.repeated&&(typeof a.type=="number"||ir(a.type))){const l={};l.valueHex=u instanceof Qr?At(u.valueBeforeDecodeView):u.valueBlock.toBER(),s.push(new vo({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},...l}))}else s.push(new ze({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:u.valueBlock.value}));else s.push(new ze({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:[u]}));else a.repeated?s=s.concat(u):s.push(u)}let o;switch(n.type){case O.Sequence:o=new $t({value:s});break;case O.Set:o=new Ft({value:s});break;case O.Choice:if(!s[0])throw new Error(`Schema '${r.name}' has wrong data. Choice cannot be empty.`);o=s[0];break}return o}static toAsnItem(e,r,n,s){let o;if(typeof e.type=="number"){const i=e.converter;if(!i)throw new Error(`Property '${r}' doesn't have converter for type ${b[e.type]} in schema '${n.name}'`);if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");const a=Array.from(s,u=>i.toASN(u)),c=e.repeated==="sequence"?$t:Ft;o=new c({value:a})}else o=i.toASN(s)}else if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");const i=Array.from(s,c=>this.toASN(c)),a=e.repeated==="sequence"?$t:Ft;o=new a({value:i})}else o=this.toASN(s);return o}}class ce extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(const r of e)this.push(r)}}}class D{static serialize(e){return ld.serialize(e)}static parse(e,r,n){return Ux.parse(e,r,n)}static toString(e,r){const n=Ca(e)?At(e):D.serialize(e),s=_n(n,r?.berOptions);if(s.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${s.result.error}`);return s.result.toString()}}function f(t,e,r,n){var s=arguments.length,o=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(o=(s<3?i(o):s>3?i(e,r,o):i(e,r))||o);return s>3&&o&&Object.defineProperty(e,r,o),o}function te(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function ge(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}class yp{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){const r=e.split(".");if(r.length!==4)throw new Error("Invalid IPv4 address");return r.map(n=>{const s=parseInt(n,10);if(isNaN(s)||s<0||s>255)throw new Error("Invalid IPv4 address part");return s})}static parseIPv6(e){const n=this.expandIPv6(e).split(":");if(n.length!==8)throw new Error("Invalid IPv6 address");return n.reduce((s,o)=>{const i=parseInt(o,16);if(isNaN(i)||i<0||i>65535)throw new Error("Invalid IPv6 address part");return s.push(i>>8&255),s.push(i&255),s},[])}static expandIPv6(e){if(!e.includes("::"))return e;const r=e.split("::");if(r.length>2)throw new Error("Invalid IPv6 address");const n=r[0]?r[0].split(":"):[],s=r[1]?r[1].split(":"):[],o=8-(n.length+s.length);if(o<0)throw new Error("Invalid IPv6 address");return[...n,...Array(o).fill("0"),...s].join(":")}static formatIPv6(e){const r=[];for(let n=0;n<16;n+=2)r.push((e[n]<<8|e[n+1]).toString(16));return this.compressIPv6(r.join(":"))}static compressIPv6(e){const r=e.split(":");let n=-1,s=0,o=-1,i=0;for(let a=0;a<r.length;a++)r[a]==="0"?(o===-1&&(o=a),i++):(i>s&&(n=o,s=i),o=-1,i=0);if(i>s&&(n=o,s=i),s>1){const a=r.slice(0,n).join(":"),c=r.slice(n+s).join(":");return`${a}::${c}`}return e}static parseCIDR(e){const[r,n]=e.split("/"),s=parseInt(n,10);if(this.isIPv4(r)){if(s<0||s>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(r),s]}else{if(s<0||s>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(r),s]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;const r=parseInt(e.slice(8),16).toString(2).split("").reduce((s,o)=>s+ +o,0);let n=e.slice(0,8).replace(/(.{2})/g,s=>`${parseInt(s,16)}.`);return n=n.slice(0,-1),`${n}/${r}`}static toString(e){const r=new Uint8Array(e);if(r.length===4)return Array.from(r).join(".");if(r.length===16)return this.formatIPv6(r);if(r.length===8||r.length===32){const n=r.length/2,s=r.slice(0,n),o=r.slice(n);if(r.every(c=>c===0))return r.length===8?"0.0.0.0/0":"::/0";const a=o.reduce((c,u)=>c+(u.toString(2).match(/1/g)||[]).length,0);return r.length===8?`${Array.from(s).join(".")}/${a}`:`${this.formatIPv6(s)}/${a}`}return this.decodeIP(Na(e))}static fromString(e){if(e.includes("/")){const[n,s]=this.parseCIDR(e),o=new Uint8Array(n.length);let i=s;for(let c=0;c<o.length;c++)i>=8?(o[c]=255,i-=8):i>0&&(o[c]=255<<8-i,i=0);const a=new Uint8Array(n.length*2);return a.set(n,0),a.set(o,n.length),a.buffer}const r=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(r).buffer}}var Qc,eu,tu;let Ve=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};f([h({type:b.TeletexString})],Ve.prototype,"teletexString",void 0);f([h({type:b.PrintableString})],Ve.prototype,"printableString",void 0);f([h({type:b.UniversalString})],Ve.prototype,"universalString",void 0);f([h({type:b.Utf8String})],Ve.prototype,"utf8String",void 0);f([h({type:b.BmpString})],Ve.prototype,"bmpString",void 0);Ve=f([$({type:O.Choice})],Ve);let Fn=class extends Ve{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Na(this.anyValue):super.toString())}};f([h({type:b.IA5String})],Fn.prototype,"ia5String",void 0);f([h({type:b.Any})],Fn.prototype,"anyValue",void 0);Fn=f([$({type:O.Choice})],Fn);class $a{type="";value=new Fn;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],$a.prototype,"type",void 0);f([h({type:Fn})],$a.prototype,"value",void 0);let Wn=Qc=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Qc.prototype)}};Wn=Qc=f([$({type:O.Set,itemType:$a})],Wn);let ru=eu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,eu.prototype)}};ru=eu=f([$({type:O.Sequence,itemType:Wn})],ru);let Ie=tu=class extends ru{constructor(e){super(e),Object.setPrototypeOf(this,tu.prototype)}};Ie=tu=f([$({type:O.Sequence})],Ie);const Vx={fromASN:t=>yp.toString(wi.fromASN(t)),toASN:t=>wi.toASN(yp.fromString(t))};class ro{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],ro.prototype,"typeId",void 0);f([h({type:b.Any,context:0})],ro.prototype,"value",void 0);class dd{nameAssigner;partyName=new Ve;constructor(e={}){Object.assign(this,e)}}f([h({type:Ve,optional:!0,context:0,implicit:!0})],dd.prototype,"nameAssigner",void 0);f([h({type:Ve,context:1,implicit:!0})],dd.prototype,"partyName",void 0);let ne=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};f([h({type:ro,context:0,implicit:!0})],ne.prototype,"otherName",void 0);f([h({type:b.IA5String,context:1,implicit:!0})],ne.prototype,"rfc822Name",void 0);f([h({type:b.IA5String,context:2,implicit:!0})],ne.prototype,"dNSName",void 0);f([h({type:b.Any,context:3,implicit:!0})],ne.prototype,"x400Address",void 0);f([h({type:Ie,context:4,implicit:!1})],ne.prototype,"directoryName",void 0);f([h({type:dd,context:5})],ne.prototype,"ediPartyName",void 0);f([h({type:b.IA5String,context:6,implicit:!0})],ne.prototype,"uniformResourceIdentifier",void 0);f([h({type:b.OctetString,context:7,implicit:!0,converter:Vx})],ne.prototype,"iPAddress",void 0);f([h({type:b.ObjectIdentifier,context:8,implicit:!0})],ne.prototype,"registeredID",void 0);ne=f([$({type:O.Choice})],ne);const fd="1.3.6.1.5.5.7",Hx=`${fd}.1`,rs=`${fd}.3`,Ra=`${fd}.48`,gp=`${Ra}.1`,vp=`${Ra}.2`,bp=`${Ra}.3`,wp=`${Ra}.5`,br="2.5.29";var nu;const su=`${Hx}.1`;class So{accessMethod="";accessLocation=new ne;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],So.prototype,"accessMethod",void 0);f([h({type:ne})],So.prototype,"accessLocation",void 0);let Tn=nu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,nu.prototype)}};Tn=nu=f([$({type:O.Sequence,itemType:So})],Tn);const ou=`${br}.35`;class pd extends ue{}class Wr{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}}f([h({type:pd,context:0,optional:!0,implicit:!0})],Wr.prototype,"keyIdentifier",void 0);f([h({type:ne,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Wr.prototype,"authorityCertIssuer",void 0);f([h({type:b.Integer,context:2,optional:!0,implicit:!0,converter:be})],Wr.prototype,"authorityCertSerialNumber",void 0);const Wg=`${br}.19`;class Ai{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Boolean,defaultValue:!1})],Ai.prototype,"cA",void 0);f([h({type:b.Integer,optional:!0})],Ai.prototype,"pathLenConstraint",void 0);var iu;let He=iu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,iu.prototype)}};He=iu=f([$({type:O.Sequence,itemType:ne})],He);var au;let Ap=au=class extends He{constructor(e){super(e),Object.setPrototypeOf(this,au.prototype)}};Ap=au=f([$({type:O.Sequence})],Ap);var cu;const Kg=`${br}.32`;let dr=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};f([h({type:b.IA5String})],dr.prototype,"ia5String",void 0);f([h({type:b.VisibleString})],dr.prototype,"visibleString",void 0);f([h({type:b.BmpString})],dr.prototype,"bmpString",void 0);f([h({type:b.Utf8String})],dr.prototype,"utf8String",void 0);dr=f([$({type:O.Choice})],dr);class hd{organization=new dr;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}}f([h({type:dr})],hd.prototype,"organization",void 0);f([h({type:b.Integer,repeated:"sequence"})],hd.prototype,"noticeNumbers",void 0);class md{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}}f([h({type:hd,optional:!0})],md.prototype,"noticeRef",void 0);f([h({type:dr,optional:!0})],md.prototype,"explicitText",void 0);let Si=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};f([h({type:b.IA5String})],Si.prototype,"cPSuri",void 0);f([h({type:md})],Si.prototype,"userNotice",void 0);Si=f([$({type:O.Choice})],Si);class yd{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],yd.prototype,"policyQualifierId",void 0);f([h({type:b.Any})],yd.prototype,"qualifier",void 0);class _a{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],_a.prototype,"policyIdentifier",void 0);f([h({type:yd,repeated:"sequence",optional:!0})],_a.prototype,"policyQualifiers",void 0);let ki=cu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,cu.prototype)}};ki=cu=f([$({type:O.Sequence,itemType:_a})],ki);let xi=class{value;constructor(e=0){this.value=e}};f([h({type:b.Integer})],xi.prototype,"value",void 0);xi=f([$({type:O.Choice})],xi);let Sp=class extends xi{};Sp=f([$({type:O.Choice})],Sp);var uu;const lu=`${br}.31`;var It;(function(t){t[t.unused=1]="unused",t[t.keyCompromise=2]="keyCompromise",t[t.cACompromise=4]="cACompromise",t[t.affiliationChanged=8]="affiliationChanged",t[t.superseded=16]="superseded",t[t.cessationOfOperation=32]="cessationOfOperation",t[t.certificateHold=64]="certificateHold",t[t.privilegeWithdrawn=128]="privilegeWithdrawn",t[t.aACompromise=256]="aACompromise"})(It||(It={}));class Gg extends Ba{toJSON(){const e=[],r=this.toNumber();return r&It.aACompromise&&e.push("aACompromise"),r&It.affiliationChanged&&e.push("affiliationChanged"),r&It.cACompromise&&e.push("cACompromise"),r&It.certificateHold&&e.push("certificateHold"),r&It.cessationOfOperation&&e.push("cessationOfOperation"),r&It.keyCompromise&&e.push("keyCompromise"),r&It.privilegeWithdrawn&&e.push("privilegeWithdrawn"),r&It.superseded&&e.push("superseded"),r&It.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let rn=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};f([h({type:ne,context:0,repeated:"sequence",implicit:!0})],rn.prototype,"fullName",void 0);f([h({type:Wn,context:1,implicit:!0})],rn.prototype,"nameRelativeToCRLIssuer",void 0);rn=f([$({type:O.Choice})],rn);class ns{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}}f([h({type:rn,context:0,optional:!0})],ns.prototype,"distributionPoint",void 0);f([h({type:Gg,context:1,optional:!0,implicit:!0})],ns.prototype,"reasons",void 0);f([h({type:ne,context:2,optional:!0,repeated:"sequence",implicit:!0})],ns.prototype,"cRLIssuer",void 0);let Mn=uu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,uu.prototype)}};Mn=uu=f([$({type:O.Sequence,itemType:ns})],Mn);var du;let kp=du=class extends Mn{constructor(e){super(e),Object.setPrototypeOf(this,du.prototype)}};kp=du=f([$({type:O.Sequence,itemType:ns})],kp);class qe{static ONLY=!1;distributionPoint;onlyContainsUserCerts=qe.ONLY;onlyContainsCACerts=qe.ONLY;onlySomeReasons;indirectCRL=qe.ONLY;onlyContainsAttributeCerts=qe.ONLY;constructor(e={}){Object.assign(this,e)}}f([h({type:rn,context:0,optional:!0})],qe.prototype,"distributionPoint",void 0);f([h({type:b.Boolean,context:1,defaultValue:qe.ONLY,implicit:!0})],qe.prototype,"onlyContainsUserCerts",void 0);f([h({type:b.Boolean,context:2,defaultValue:qe.ONLY,implicit:!0})],qe.prototype,"onlyContainsCACerts",void 0);f([h({type:Gg,context:3,optional:!0,implicit:!0})],qe.prototype,"onlySomeReasons",void 0);f([h({type:b.Boolean,context:4,defaultValue:qe.ONLY,implicit:!0})],qe.prototype,"indirectCRL",void 0);f([h({type:b.Boolean,context:5,defaultValue:qe.ONLY,implicit:!0})],qe.prototype,"onlyContainsAttributeCerts",void 0);var Hs;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(Hs||(Hs={}));let fu=class{reason=Hs.unspecified;constructor(e=Hs.unspecified){this.reason=e}toJSON(){return Hs[this.reason]}toString(){return this.toJSON()}};f([h({type:b.Enumerated})],fu.prototype,"reason",void 0);fu=f([$({type:O.Choice})],fu);var pu;const qg=`${br}.37`;let Ei=pu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,pu.prototype)}};Ei=pu=f([$({type:O.Sequence,itemType:b.ObjectIdentifier})],Ei);const Fx=`${rs}.1`,Wx=`${rs}.2`,Kx=`${rs}.3`,Gx=`${rs}.4`,qx=`${rs}.8`,zx=`${rs}.9`;let hu=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};f([h({type:b.Integer,converter:be})],hu.prototype,"value",void 0);hu=f([$({type:O.Choice})],hu);let mu=class{value=new Date;constructor(e){e&&(this.value=e)}};f([h({type:b.GeneralizedTime})],mu.prototype,"value",void 0);mu=f([$({type:O.Choice})],mu);var yu;const zg=`${br}.18`;let xp=yu=class extends He{constructor(e){super(e),Object.setPrototypeOf(this,yu.prototype)}};xp=yu=f([$({type:O.Sequence})],xp);const Yg=`${br}.15`;var Ct;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(Ct||(Ct={}));class Ic extends Ba{toJSON(){const e=this.toNumber(),r=[];return e&Ct.cRLSign&&r.push("crlSign"),e&Ct.dataEncipherment&&r.push("dataEncipherment"),e&Ct.decipherOnly&&r.push("decipherOnly"),e&Ct.digitalSignature&&r.push("digitalSignature"),e&Ct.encipherOnly&&r.push("encipherOnly"),e&Ct.keyAgreement&&r.push("keyAgreement"),e&Ct.keyCertSign&&r.push("keyCertSign"),e&Ct.keyEncipherment&&r.push("keyEncipherment"),e&Ct.nonRepudiation&&r.push("nonRepudiation"),r}toString(){return`[${this.toJSON().join(", ")}]`}}var gu;class Ma{base=new ne;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}}f([h({type:ne})],Ma.prototype,"base",void 0);f([h({type:b.Integer,context:0,defaultValue:0,implicit:!0})],Ma.prototype,"minimum",void 0);f([h({type:b.Integer,context:1,optional:!0,implicit:!0})],Ma.prototype,"maximum",void 0);let Ii=gu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,gu.prototype)}};Ii=gu=f([$({type:O.Sequence,itemType:Ma})],Ii);class Xg{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}}f([h({type:Ii,context:0,optional:!0,implicit:!0})],Xg.prototype,"permittedSubtrees",void 0);f([h({type:Ii,context:1,optional:!0,implicit:!0})],Xg.prototype,"excludedSubtrees",void 0);class Jg{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,context:0,implicit:!0,optional:!0,converter:be})],Jg.prototype,"requireExplicitPolicy",void 0);f([h({type:b.Integer,context:1,implicit:!0,optional:!0,converter:be})],Jg.prototype,"inhibitPolicyMapping",void 0);var vu;class gd{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],gd.prototype,"issuerDomainPolicy",void 0);f([h({type:b.ObjectIdentifier})],gd.prototype,"subjectDomainPolicy",void 0);let Ep=vu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,vu.prototype)}};Ep=vu=f([$({type:O.Sequence,itemType:gd})],Ep);var bu;const Zg=`${br}.17`;let wu=bu=class extends He{constructor(e){super(e),Object.setPrototypeOf(this,bu.prototype)}};wu=bu=f([$({type:O.Sequence})],wu);let fr=class{type="";values=[];constructor(e={}){Object.assign(this,e)}};f([h({type:b.ObjectIdentifier})],fr.prototype,"type",void 0);f([h({type:b.Any,repeated:"set"})],fr.prototype,"values",void 0);var Au;let Ip=Au=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Au.prototype)}};Ip=Au=f([$({type:O.Sequence,itemType:fr})],Ip);const Qg=`${br}.14`;class Or extends pd{}class ev{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}}f([h({type:b.GeneralizedTime,context:0,implicit:!0,optional:!0})],ev.prototype,"notBefore",void 0);f([h({type:b.GeneralizedTime,context:1,implicit:!0,optional:!0})],ev.prototype,"notAfter",void 0);var Fs;(function(t){t[t.keyUpdateAllowed=1]="keyUpdateAllowed",t[t.newExtensions=2]="newExtensions",t[t.pKIXCertificate=4]="pKIXCertificate"})(Fs||(Fs={}));class tv extends Ba{toJSON(){const e=[],r=this.toNumber();return r&Fs.pKIXCertificate&&e.push("pKIXCertificate"),r&Fs.newExtensions&&e.push("newExtensions"),r&Fs.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class rv{entrustVers="";entrustInfoFlags=new tv;constructor(e={}){Object.assign(this,e)}}f([h({type:b.GeneralString})],rv.prototype,"entrustVers",void 0);f([h({type:tv})],rv.prototype,"entrustInfoFlags",void 0);var Su;let Cp=Su=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Su.prototype)}};Cp=Su=f([$({type:O.Sequence,itemType:So})],Cp);class L{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof L&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Ok(e.parameters,this.parameters)||e.parameters===this.parameters)}}f([h({type:b.ObjectIdentifier})],L.prototype,"algorithm",void 0);f([h({type:b.Any,optional:!0})],L.prototype,"parameters",void 0);class bt{algorithm=new L;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:L})],bt.prototype,"algorithm",void 0);f([h({type:b.BitString})],bt.prototype,"subjectPublicKey",void 0);let Le=class{utcTime;generalTime;constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){const r=new Date(e);r.setMilliseconds(0),r.getUTCFullYear()>2049?this.generalTime=r:this.utcTime=r}else Object.assign(this,e)}getTime(){const e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};f([h({type:b.UTCTime})],Le.prototype,"utcTime",void 0);f([h({type:b.GeneralizedTime})],Le.prototype,"generalTime",void 0);Le=f([$({type:O.Choice})],Le);class ko{notBefore=new Le(new Date);notAfter=new Le(new Date);constructor(e){e&&(this.notBefore=new Le(e.notBefore),this.notAfter=new Le(e.notAfter))}}f([h({type:Le})],ko.prototype,"notBefore",void 0);f([h({type:Le})],ko.prototype,"notAfter",void 0);var ku;let _t=class nv{static CRITICAL=!1;extnID="";critical=nv.CRITICAL;extnValue=new ue;constructor(e={}){Object.assign(this,e)}};f([h({type:b.ObjectIdentifier})],_t.prototype,"extnID",void 0);f([h({type:b.Boolean,defaultValue:_t.CRITICAL})],_t.prototype,"critical",void 0);f([h({type:ue})],_t.prototype,"extnValue",void 0);let Tr=ku=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,ku.prototype)}};Tr=ku=f([$({type:O.Sequence,itemType:_t})],Tr);var nn;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2",t[t.v3=2]="v3"})(nn||(nn={}));class pt{version=nn.v1;serialNumber=new ArrayBuffer(0);signature=new L;issuer=new Ie;validity=new ko;subject=new Ie;subjectPublicKeyInfo=new bt;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,context:0,defaultValue:nn.v1})],pt.prototype,"version",void 0);f([h({type:b.Integer,converter:be})],pt.prototype,"serialNumber",void 0);f([h({type:L})],pt.prototype,"signature",void 0);f([h({type:Ie})],pt.prototype,"issuer",void 0);f([h({type:ko})],pt.prototype,"validity",void 0);f([h({type:Ie})],pt.prototype,"subject",void 0);f([h({type:bt})],pt.prototype,"subjectPublicKeyInfo",void 0);f([h({type:b.BitString,context:1,implicit:!0,optional:!0})],pt.prototype,"issuerUniqueID",void 0);f([h({type:b.BitString,context:2,implicit:!0,optional:!0})],pt.prototype,"subjectUniqueID",void 0);f([h({type:Tr,context:3,optional:!0})],pt.prototype,"extensions",void 0);class sn{tbsCertificate=new pt;tbsCertificateRaw;signatureAlgorithm=new L;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:pt,raw:!0})],sn.prototype,"tbsCertificate",void 0);f([h({type:L})],sn.prototype,"signatureAlgorithm",void 0);f([h({type:b.BitString})],sn.prototype,"signatureValue",void 0);class ja{userCertificate=new ArrayBuffer(0);revocationDate=new Le;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,converter:be})],ja.prototype,"userCertificate",void 0);f([h({type:Le})],ja.prototype,"revocationDate",void 0);f([h({type:_t,optional:!0,repeated:"sequence"})],ja.prototype,"crlEntryExtensions",void 0);class wr{version;signature=new L;issuer=new Ie;thisUpdate=new Le;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,optional:!0})],wr.prototype,"version",void 0);f([h({type:L})],wr.prototype,"signature",void 0);f([h({type:Ie})],wr.prototype,"issuer",void 0);f([h({type:Le})],wr.prototype,"thisUpdate",void 0);f([h({type:Le,optional:!0})],wr.prototype,"nextUpdate",void 0);f([h({type:ja,repeated:"sequence",optional:!0})],wr.prototype,"revokedCertificates",void 0);f([h({type:_t,optional:!0,context:0,repeated:"sequence"})],wr.prototype,"crlExtensions",void 0);class vd{tbsCertList=new wr;tbsCertListRaw;signatureAlgorithm=new L;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:wr,raw:!0})],vd.prototype,"tbsCertList",void 0);f([h({type:L})],vd.prototype,"signatureAlgorithm",void 0);f([h({type:b.BitString})],vd.prototype,"signature",void 0);class ss{issuer=new Ie;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:Ie})],ss.prototype,"issuer",void 0);f([h({type:b.Integer,converter:be})],ss.prototype,"serialNumber",void 0);let Kn=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([h({type:Or,context:0,implicit:!0})],Kn.prototype,"subjectKeyIdentifier",void 0);f([h({type:ss})],Kn.prototype,"issuerAndSerialNumber",void 0);Kn=f([$({type:O.Choice})],Kn);var pr;(function(t){t[t.v0=0]="v0",t[t.v1=1]="v1",t[t.v2=2]="v2",t[t.v3=3]="v3",t[t.v4=4]="v4",t[t.v5=5]="v5"})(pr||(pr={}));let no=class extends L{};no=f([$({type:O.Sequence})],no);let Ci=class extends L{};Ci=f([$({type:O.Sequence})],Ci);let Kt=class extends L{};Kt=f([$({type:O.Sequence})],Kt);let Oi=class extends L{};Oi=f([$({type:O.Sequence})],Oi);let Op=class extends L{};Op=f([$({type:O.Sequence})],Op);let xu=class extends L{};xu=f([$({type:O.Sequence})],xu);let os=class{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}};f([h({type:b.ObjectIdentifier})],os.prototype,"attrType",void 0);f([h({type:b.Any,repeated:"set"})],os.prototype,"attrValues",void 0);var Eu;class Jt{version=pr.v0;sid=new Kn;digestAlgorithm=new no;signedAttrs;signedAttrsRaw;signatureAlgorithm=new Ci;signature=new ue;unsignedAttrs;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],Jt.prototype,"version",void 0);f([h({type:Kn})],Jt.prototype,"sid",void 0);f([h({type:no})],Jt.prototype,"digestAlgorithm",void 0);f([h({type:os,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],Jt.prototype,"signedAttrs",void 0);f([h({type:Ci})],Jt.prototype,"signatureAlgorithm",void 0);f([h({type:ue})],Jt.prototype,"signature",void 0);f([h({type:os,repeated:"set",context:1,implicit:!0,optional:!0})],Jt.prototype,"unsignedAttrs",void 0);let Ni=Eu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Eu.prototype)}};Ni=Eu=f([$({type:O.Set,itemType:Jt})],Ni);let Np=class extends Jt{};Np=f([$({type:O.Sequence})],Np);let Tp=class extends Le{};Tp=f([$({type:O.Choice})],Tp);class bd{acIssuer=new ne;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}}f([h({type:ne})],bd.prototype,"acIssuer",void 0);f([h({type:b.Integer})],bd.prototype,"acSerial",void 0);f([h({type:fr,repeated:"sequence"})],bd.prototype,"attrs",void 0);var Iu;let Ti=Iu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Iu.prototype)}};Ti=Iu=f([$({type:O.Sequence,itemType:b.ObjectIdentifier})],Ti);class Da{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,optional:!0})],Da.prototype,"pathLenConstraint",void 0);f([h({type:Ti,implicit:!0,context:0,optional:!0})],Da.prototype,"permittedAttrs",void 0);f([h({type:Ti,implicit:!0,context:1,optional:!0})],Da.prototype,"excludedAttrs",void 0);f([h({type:b.Boolean,defaultValue:!0})],Da.prototype,"permitUnSpecified",void 0);class gn{issuer=new He;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:He})],gn.prototype,"issuer",void 0);f([h({type:b.Integer,converter:be})],gn.prototype,"serial",void 0);f([h({type:b.BitString,optional:!0})],gn.prototype,"issuerUID",void 0);var Cu;(function(t){t[t.publicKey=0]="publicKey",t[t.publicKeyCert=1]="publicKeyCert",t[t.otherObjectTypes=2]="otherObjectTypes"})(Cu||(Cu={}));class vn{digestedObjectType=Cu.publicKey;otherObjectTypeID;digestAlgorithm=new L;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.Enumerated})],vn.prototype,"digestedObjectType",void 0);f([h({type:b.ObjectIdentifier,optional:!0})],vn.prototype,"otherObjectTypeID",void 0);f([h({type:L})],vn.prototype,"digestAlgorithm",void 0);f([h({type:b.BitString})],vn.prototype,"objectDigest",void 0);class Pa{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}f([h({type:He,optional:!0})],Pa.prototype,"issuerName",void 0);f([h({type:gn,context:0,implicit:!0,optional:!0})],Pa.prototype,"baseCertificateID",void 0);f([h({type:vn,context:1,implicit:!0,optional:!0})],Pa.prototype,"objectDigestInfo",void 0);let Gn=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};f([h({type:ne,repeated:"sequence"})],Gn.prototype,"v1Form",void 0);f([h({type:Pa,context:0,implicit:!0})],Gn.prototype,"v2Form",void 0);Gn=f([$({type:O.Choice})],Gn);class La{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}}f([h({type:b.GeneralizedTime})],La.prototype,"notBeforeTime",void 0);f([h({type:b.GeneralizedTime})],La.prototype,"notAfterTime",void 0);class xo{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}f([h({type:gn,implicit:!0,context:0,optional:!0})],xo.prototype,"baseCertificateID",void 0);f([h({type:He,implicit:!0,context:1,optional:!0})],xo.prototype,"entityName",void 0);f([h({type:vn,implicit:!0,context:2,optional:!0})],xo.prototype,"objectDigestInfo",void 0);var Ou;(function(t){t[t.v2=1]="v2"})(Ou||(Ou={}));class jt{version=Ou.v2;holder=new xo;issuer=new Gn;signature=new L;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new La;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],jt.prototype,"version",void 0);f([h({type:xo})],jt.prototype,"holder",void 0);f([h({type:Gn})],jt.prototype,"issuer",void 0);f([h({type:L})],jt.prototype,"signature",void 0);f([h({type:b.Integer,converter:be})],jt.prototype,"serialNumber",void 0);f([h({type:La})],jt.prototype,"attrCertValidityPeriod",void 0);f([h({type:fr,repeated:"sequence"})],jt.prototype,"attributes",void 0);f([h({type:b.BitString,optional:!0})],jt.prototype,"issuerUniqueID",void 0);f([h({type:Tr,optional:!0})],jt.prototype,"extensions",void 0);class Ua{acinfo=new jt;signatureAlgorithm=new L;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:jt})],Ua.prototype,"acinfo",void 0);f([h({type:L})],Ua.prototype,"signatureAlgorithm",void 0);f([h({type:b.BitString})],Ua.prototype,"signatureValue",void 0);var Bi;(function(t){t[t.unmarked=1]="unmarked",t[t.unclassified=2]="unclassified",t[t.restricted=4]="restricted",t[t.confidential=8]="confidential",t[t.secret=16]="secret",t[t.topSecret=32]="topSecret"})(Bi||(Bi={}));class Nu extends Ba{}class wd{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier,implicit:!0,context:0})],wd.prototype,"type",void 0);f([h({type:b.Any,implicit:!0,context:1})],wd.prototype,"value",void 0);class Ad{policyId="";classList=new Nu(Bi.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],Ad.prototype,"policyId",void 0);f([h({type:Nu,defaultValue:new Nu(Bi.unclassified)})],Ad.prototype,"classList",void 0);f([h({type:wd,repeated:"set"})],Ad.prototype,"securityCategories",void 0);class Va{cotets;oid;string;constructor(e={}){Object.assign(this,e)}}f([h({type:ue})],Va.prototype,"cotets",void 0);f([h({type:b.ObjectIdentifier})],Va.prototype,"oid",void 0);f([h({type:b.Utf8String})],Va.prototype,"string",void 0);class sv{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}}f([h({type:He,implicit:!0,context:0,optional:!0})],sv.prototype,"policyAuthority",void 0);f([h({type:Va,repeated:"sequence"})],sv.prototype,"values",void 0);var Tu;class Ha{targetCertificate=new gn;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}}f([h({type:gn})],Ha.prototype,"targetCertificate",void 0);f([h({type:ne,optional:!0})],Ha.prototype,"targetName",void 0);f([h({type:vn,optional:!0})],Ha.prototype,"certDigestInfo",void 0);let qn=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};f([h({type:ne,context:0,implicit:!0})],qn.prototype,"targetName",void 0);f([h({type:ne,context:1,implicit:!0})],qn.prototype,"targetGroup",void 0);f([h({type:Ha,context:2,implicit:!0})],qn.prototype,"targetCert",void 0);qn=f([$({type:O.Choice})],qn);let Bu=Tu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Tu.prototype)}};Bu=Tu=f([$({type:O.Sequence,itemType:qn})],Bu);var $u;let Bp=$u=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,$u.prototype)}};Bp=$u=f([$({type:O.Sequence,itemType:Bu})],Bp);class ov{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}}f([h({type:He,implicit:!0,context:0,optional:!0})],ov.prototype,"roleAuthority",void 0);f([h({type:ne,implicit:!0,context:1})],ov.prototype,"roleName",void 0);class Sd{service=new ne;ident=new ne;authInfo;constructor(e={}){Object.assign(this,e)}}f([h({type:ne})],Sd.prototype,"service",void 0);f([h({type:ne})],Sd.prototype,"ident",void 0);f([h({type:ue,optional:!0})],Sd.prototype,"authInfo",void 0);var Ru;class kd{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],kd.prototype,"otherCertFormat",void 0);f([h({type:b.Any})],kd.prototype,"otherCert",void 0);let zn=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};f([h({type:sn})],zn.prototype,"certificate",void 0);f([h({type:Ua,context:2,implicit:!0})],zn.prototype,"v2AttrCert",void 0);f([h({type:kd,context:3,implicit:!0})],zn.prototype,"other",void 0);zn=f([$({type:O.Choice})],zn);let $i=Ru=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Ru.prototype)}};$i=Ru=f([$({type:O.Set,itemType:zn})],$i);class is{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],is.prototype,"contentType",void 0);f([h({type:b.Any,context:0})],is.prototype,"content",void 0);let so=class{single;any;constructor(e={}){Object.assign(this,e)}};f([h({type:ue})],so.prototype,"single",void 0);f([h({type:b.Any})],so.prototype,"any",void 0);so=f([$({type:O.Choice})],so);class Fa{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],Fa.prototype,"eContentType",void 0);f([h({type:so,context:0,optional:!0})],Fa.prototype,"eContent",void 0);let oo=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};f([h({type:ue,context:0,implicit:!0,optional:!0})],oo.prototype,"value",void 0);f([h({type:ue,converter:kx,context:0,implicit:!0,optional:!0,repeated:"sequence"})],oo.prototype,"constructedValue",void 0);oo=f([$({type:O.Choice})],oo);class Eo{contentType="";contentEncryptionAlgorithm=new Oi;encryptedContent;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],Eo.prototype,"contentType",void 0);f([h({type:Oi})],Eo.prototype,"contentEncryptionAlgorithm",void 0);f([h({type:oo,optional:!0})],Eo.prototype,"encryptedContent",void 0);class Wa{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],Wa.prototype,"keyAttrId",void 0);f([h({type:b.Any,optional:!0})],Wa.prototype,"keyAttr",void 0);var _u;class Ka{subjectKeyIdentifier=new Or;date;other;constructor(e={}){Object.assign(this,e)}}f([h({type:Or})],Ka.prototype,"subjectKeyIdentifier",void 0);f([h({type:b.GeneralizedTime,optional:!0})],Ka.prototype,"date",void 0);f([h({type:Wa,optional:!0})],Ka.prototype,"other",void 0);let Yn=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([h({type:Ka,context:0,implicit:!0,optional:!0})],Yn.prototype,"rKeyId",void 0);f([h({type:ss,optional:!0})],Yn.prototype,"issuerAndSerialNumber",void 0);Yn=f([$({type:O.Choice})],Yn);class xd{rid=new Yn;encryptedKey=new ue;constructor(e={}){Object.assign(this,e)}}f([h({type:Yn})],xd.prototype,"rid",void 0);f([h({type:ue})],xd.prototype,"encryptedKey",void 0);let Ri=_u=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,_u.prototype)}};Ri=_u=f([$({type:O.Sequence,itemType:xd})],Ri);class Ed{algorithm=new L;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:L})],Ed.prototype,"algorithm",void 0);f([h({type:b.BitString})],Ed.prototype,"publicKey",void 0);let on=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([h({type:Or,context:0,implicit:!0,optional:!0})],on.prototype,"subjectKeyIdentifier",void 0);f([h({type:Ed,context:1,implicit:!0,optional:!0})],on.prototype,"originatorKey",void 0);f([h({type:ss,optional:!0})],on.prototype,"issuerAndSerialNumber",void 0);on=f([$({type:O.Choice})],on);class as{version=pr.v3;originator=new on;ukm;keyEncryptionAlgorithm=new Kt;recipientEncryptedKeys=new Ri;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],as.prototype,"version",void 0);f([h({type:on,context:0})],as.prototype,"originator",void 0);f([h({type:ue,context:1,optional:!0})],as.prototype,"ukm",void 0);f([h({type:Kt})],as.prototype,"keyEncryptionAlgorithm",void 0);f([h({type:Ri})],as.prototype,"recipientEncryptedKeys",void 0);let Xn=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([h({type:Or,context:0,implicit:!0})],Xn.prototype,"subjectKeyIdentifier",void 0);f([h({type:ss})],Xn.prototype,"issuerAndSerialNumber",void 0);Xn=f([$({type:O.Choice})],Xn);class Io{version=pr.v0;rid=new Xn;keyEncryptionAlgorithm=new Kt;encryptedKey=new ue;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],Io.prototype,"version",void 0);f([h({type:Xn})],Io.prototype,"rid",void 0);f([h({type:Kt})],Io.prototype,"keyEncryptionAlgorithm",void 0);f([h({type:ue})],Io.prototype,"encryptedKey",void 0);class Co{keyIdentifier=new ue;date;other;constructor(e={}){Object.assign(this,e)}}f([h({type:ue})],Co.prototype,"keyIdentifier",void 0);f([h({type:b.GeneralizedTime,optional:!0})],Co.prototype,"date",void 0);f([h({type:Wa,optional:!0})],Co.prototype,"other",void 0);class Oo{version=pr.v4;kekid=new Co;keyEncryptionAlgorithm=new Kt;encryptedKey=new ue;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],Oo.prototype,"version",void 0);f([h({type:Co})],Oo.prototype,"kekid",void 0);f([h({type:Kt})],Oo.prototype,"keyEncryptionAlgorithm",void 0);f([h({type:ue})],Oo.prototype,"encryptedKey",void 0);class No{version=pr.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new Kt;encryptedKey=new ue;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],No.prototype,"version",void 0);f([h({type:xu,context:0,optional:!0})],No.prototype,"keyDerivationAlgorithm",void 0);f([h({type:Kt})],No.prototype,"keyEncryptionAlgorithm",void 0);f([h({type:ue})],No.prototype,"encryptedKey",void 0);class Id{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],Id.prototype,"oriType",void 0);f([h({type:b.Any})],Id.prototype,"oriValue",void 0);let Br=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};f([h({type:Io,optional:!0})],Br.prototype,"ktri",void 0);f([h({type:as,context:1,implicit:!0,optional:!0})],Br.prototype,"kari",void 0);f([h({type:Oo,context:2,implicit:!0,optional:!0})],Br.prototype,"kekri",void 0);f([h({type:No,context:3,implicit:!0,optional:!0})],Br.prototype,"pwri",void 0);f([h({type:Id,context:4,implicit:!0,optional:!0})],Br.prototype,"ori",void 0);Br=f([$({type:O.Choice})],Br);var Mu;let _i=Mu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Mu.prototype)}};_i=Mu=f([$({type:O.Set,itemType:Br})],_i);var ju;class Ga{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],Ga.prototype,"otherRevInfoFormat",void 0);f([h({type:b.Any})],Ga.prototype,"otherRevInfo",void 0);let Mi=class{other=new Ga;constructor(e={}){Object.assign(this,e)}};f([h({type:Ga,context:1,implicit:!0})],Mi.prototype,"other",void 0);Mi=f([$({type:O.Choice})],Mi);let ji=ju=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,ju.prototype)}};ji=ju=f([$({type:O.Set,itemType:Mi})],ji);class Cd{certs;crls;constructor(e={}){Object.assign(this,e)}}f([h({type:$i,context:0,implicit:!0,optional:!0})],Cd.prototype,"certs",void 0);f([h({type:ji,context:1,implicit:!0,optional:!0})],Cd.prototype,"crls",void 0);var Du;let Pu=Du=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Du.prototype)}};Pu=Du=f([$({type:O.Set,itemType:os})],Pu);class To{version=pr.v0;originatorInfo;recipientInfos=new _i;encryptedContentInfo=new Eo;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],To.prototype,"version",void 0);f([h({type:Cd,context:0,implicit:!0,optional:!0})],To.prototype,"originatorInfo",void 0);f([h({type:_i})],To.prototype,"recipientInfos",void 0);f([h({type:Eo})],To.prototype,"encryptedContentInfo",void 0);f([h({type:Pu,context:1,implicit:!0,optional:!0})],To.prototype,"unprotectedAttrs",void 0);const Yx="1.2.840.113549.1.7.2";var Lu;let Di=Lu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Lu.prototype)}};Di=Lu=f([$({type:O.Set,itemType:no})],Di);class cs{version=pr.v0;digestAlgorithms=new Di;encapContentInfo=new Fa;certificates;crls;signerInfos=new Ni;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],cs.prototype,"version",void 0);f([h({type:Di})],cs.prototype,"digestAlgorithms",void 0);f([h({type:Fa})],cs.prototype,"encapContentInfo",void 0);f([h({type:$i,context:0,implicit:!0,optional:!0})],cs.prototype,"certificates",void 0);f([h({type:ji,context:1,implicit:!0,optional:!0})],cs.prototype,"crls",void 0);f([h({type:Ni})],cs.prototype,"signerInfos",void 0);const io="1.2.840.10045.2.1",Od="1.2.840.10045.4.1",iv="1.2.840.10045.4.3.1",Nd="1.2.840.10045.4.3.2",Td="1.2.840.10045.4.3.3",Bd="1.2.840.10045.4.3.4",$p="1.2.840.10045.3.1.7",Rp="1.3.132.0.34",_p="1.3.132.0.35";function Bo(t){return new L({algorithm:t})}const Xx=Bo(Od);Bo(iv);const Jx=Bo(Nd),Zx=Bo(Td),Qx=Bo(Bd);let ao=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};f([h({type:b.ObjectIdentifier})],ao.prototype,"fieldType",void 0);f([h({type:b.Any})],ao.prototype,"parameters",void 0);ao=f([$({type:O.Sequence})],ao);class eE extends ue{}let Jn=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};f([h({type:b.OctetString})],Jn.prototype,"a",void 0);f([h({type:b.OctetString})],Jn.prototype,"b",void 0);f([h({type:b.BitString,optional:!0})],Jn.prototype,"seed",void 0);Jn=f([$({type:O.Sequence})],Jn);var Uu;(function(t){t[t.ecpVer1=1]="ecpVer1"})(Uu||(Uu={}));let hr=class{version=Uu.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};f([h({type:b.Integer})],hr.prototype,"version",void 0);f([h({type:ao})],hr.prototype,"fieldID",void 0);f([h({type:Jn})],hr.prototype,"curve",void 0);f([h({type:eE})],hr.prototype,"base",void 0);f([h({type:b.Integer,converter:be})],hr.prototype,"order",void 0);f([h({type:b.Integer,optional:!0})],hr.prototype,"cofactor",void 0);hr=f([$({type:O.Sequence})],hr);let $r=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};f([h({type:b.ObjectIdentifier})],$r.prototype,"namedCurve",void 0);f([h({type:b.Null})],$r.prototype,"implicitCurve",void 0);f([h({type:hr})],$r.prototype,"specifiedCurve",void 0);$r=f([$({type:O.Choice})],$r);class qa{version=1;privateKey=new ue;parameters;publicKey;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],qa.prototype,"version",void 0);f([h({type:ue})],qa.prototype,"privateKey",void 0);f([h({type:$r,context:0,optional:!0})],qa.prototype,"parameters",void 0);f([h({type:b.BitString,context:1,optional:!0})],qa.prototype,"publicKey",void 0);class Pi{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,converter:be})],Pi.prototype,"r",void 0);f([h({type:b.Integer,converter:be})],Pi.prototype,"s",void 0);const nt="1.2.840.113549.1.1",an=`${nt}.1`,tE=`${nt}.7`,rE=`${nt}.9`,Ws=`${nt}.10`,nE=`${nt}.2`,sE=`${nt}.4`,Li=`${nt}.5`,oE=`${nt}.14`,Vu=`${nt}.11`,Ui=`${nt}.12`,Vi=`${nt}.13`,av=`${nt}.15`,cv=`${nt}.16`,Hi="1.3.14.3.2.26",uv="2.16.840.1.101.3.4.2.4",Fi="2.16.840.1.101.3.4.2.1",Wi="2.16.840.1.101.3.4.2.2",Ki="2.16.840.1.101.3.4.2.3",iE="2.16.840.1.101.3.4.2.5",aE="2.16.840.1.101.3.4.2.6",cE="1.2.840.113549.2.2",uE="1.2.840.113549.2.5",za=`${nt}.8`;function Be(t){return new L({algorithm:t,parameters:null})}Be(cE);Be(uE);const cn=Be(Hi);Be(uv);Be(Fi);Be(Wi);Be(Ki);Be(iE);Be(aE);const lv=new L({algorithm:za,parameters:D.serialize(cn)}),dv=new L({algorithm:rE,parameters:D.serialize(wi.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});Be(an);Be(nE);Be(sE);Be(Li);Be(av);Be(cv);Be(Ui);Be(Vi);Be(av);Be(cv);class Ya{hashAlgorithm=new L(cn);maskGenAlgorithm=new L({algorithm:za,parameters:D.serialize(cn)});pSourceAlgorithm=new L(dv);constructor(e={}){Object.assign(this,e)}}f([h({type:L,context:0,defaultValue:cn})],Ya.prototype,"hashAlgorithm",void 0);f([h({type:L,context:1,defaultValue:lv})],Ya.prototype,"maskGenAlgorithm",void 0);f([h({type:L,context:2,defaultValue:dv})],Ya.prototype,"pSourceAlgorithm",void 0);new L({algorithm:tE,parameters:D.serialize(new Ya)});class un{hashAlgorithm=new L(cn);maskGenAlgorithm=new L({algorithm:za,parameters:D.serialize(cn)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}}f([h({type:L,context:0,defaultValue:cn})],un.prototype,"hashAlgorithm",void 0);f([h({type:L,context:1,defaultValue:lv})],un.prototype,"maskGenAlgorithm",void 0);f([h({type:b.Integer,context:2,defaultValue:20})],un.prototype,"saltLength",void 0);f([h({type:b.Integer,context:3,defaultValue:1})],un.prototype,"trailerField",void 0);new L({algorithm:Ws,parameters:D.serialize(new un)});class Xa{digestAlgorithm=new L;digest=new ue;constructor(e={}){Object.assign(this,e)}}f([h({type:L})],Xa.prototype,"digestAlgorithm",void 0);f([h({type:ue})],Xa.prototype,"digest",void 0);var Hu;class Ja{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,converter:be})],Ja.prototype,"prime",void 0);f([h({type:b.Integer,converter:be})],Ja.prototype,"exponent",void 0);f([h({type:b.Integer,converter:be})],Ja.prototype,"coefficient",void 0);let Fu=Hu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Hu.prototype)}};Fu=Hu=f([$({type:O.Sequence,itemType:Ja})],Fu);class Zt{version=0;modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);privateExponent=new ArrayBuffer(0);prime1=new ArrayBuffer(0);prime2=new ArrayBuffer(0);exponent1=new ArrayBuffer(0);exponent2=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);otherPrimeInfos;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],Zt.prototype,"version",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"modulus",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"publicExponent",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"privateExponent",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"prime1",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"prime2",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"exponent1",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"exponent2",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"coefficient",void 0);f([h({type:Fu,optional:!0})],Zt.prototype,"otherPrimeInfos",void 0);class $d{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,converter:be})],$d.prototype,"modulus",void 0);f([h({type:b.Integer,converter:be})],$d.prototype,"publicExponent",void 0);var Wu;(function(t){t[t.Transient=0]="Transient",t[t.Singleton=1]="Singleton",t[t.ResolutionScoped=2]="ResolutionScoped",t[t.ContainerScoped=3]="ContainerScoped"})(Wu||(Wu={}));const Xe=Wu;var Ku=function(t,e){return Ku=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var s in n)n.hasOwnProperty(s)&&(r[s]=n[s])},Ku(t,e)};function Rd(t,e){Ku(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function lE(t,e,r,n){function s(o){return o instanceof r?o:new r(function(i){i(o)})}return new(r||(r=Promise))(function(o,i){function a(l){try{u(n.next(l))}catch(d){i(d)}}function c(l){try{u(n.throw(l))}catch(d){i(d)}}function u(l){l.done?o(l.value):s(l.value).then(a,c)}u((n=n.apply(t,[])).next())})}function dE(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,s,o,i;return i={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(u){return function(l){return c([u,l])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,s&&(o=u[0]&2?s.return:u[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,u[1])).done)return o;switch(s=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,s=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]<o[3])){r.label=u[1];break}if(u[0]===6&&r.label<o[1]){r.label=o[1],o=u;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(u);break}o[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],s=0}finally{n=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function Go(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Gi(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return o}function Fr(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Gi(arguments[e]));return t}var fE="injectionTokens";function pE(t){var e=Reflect.getMetadata("design:paramtypes",t)||[],r=Reflect.getOwnMetadata(fE,t)||{};return Object.keys(r).forEach(function(n){e[+n]=r[n]}),e}function fv(t){return!!t.useClass}function Gu(t){return!!t.useFactory}var pv=(function(){function t(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return t.prototype.createProxy=function(e){var r=this,n={},s=!1,o,i=function(){return s||(o=e(r.wrap()),s=!0),o};return new Proxy(n,this.createHandler(i))},t.prototype.createHandler=function(e){var r={},n=function(s){r[s]=function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];o[0]=e();var a=Reflect[s];return a.apply(void 0,Fr(o))}};return this.reflectMethods.forEach(n),r},t})();function Sn(t){return typeof t=="string"||typeof t=="symbol"}function hE(t){return typeof t=="object"&&"token"in t&&"multiple"in t}function Mp(t){return typeof t=="object"&&"token"in t&&"transform"in t}function mE(t){return typeof t=="function"||t instanceof pv}function ri(t){return!!t.useToken}function ni(t){return t.useValue!=null}function yE(t){return fv(t)||ni(t)||ri(t)||Gu(t)}var _d=(function(){function t(){this._registryMap=new Map}return t.prototype.entries=function(){return this._registryMap.entries()},t.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},t.prototype.get=function(e){this.ensure(e);var r=this._registryMap.get(e);return r[r.length-1]||null},t.prototype.set=function(e,r){this.ensure(e),this._registryMap.get(e).push(r)},t.prototype.setAll=function(e,r){this._registryMap.set(e,r)},t.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},t.prototype.clear=function(){this._registryMap.clear()},t.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},t})(),gE=(function(t){Rd(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(_d),qo=(function(){function t(){this.scopedResolutions=new Map}return t})();function vE(t,e){if(t===null)return"at position #"+e;var r=t.split(",")[e].trim();return'"'+r+'" at position #'+e}function bE(t,e,r){return r===void 0&&(r=" "),Fr([t],e.message.split(`
114
+ `}function Sv(t,e={}){const r=[],n=e.label;let o;for(Pp.lastIndex=0;o=Pp.exec(t);){const s=o[1].trim();if(n&&s!==n)continue;Av(s);const i=gE(o[2]);r.push({label:s,data:gs.decode(i.base64Text),headers:i.headers,lineLength:i.base64Lines[0]?.length??64,newline:vE(o[0])})}if(e.strict&&r.length===0)throw new TypeError(n?`No PEM block with label '${n}' was found`:"No PEM blocks were found");return r}function Bd(t,e,r={}){Av(t);const n=r.lineLength??64;if(!Number.isInteger(n)||n<1)throw new RangeError("PEM lineLength must be a positive integer");const o=r.newline??`
115
+ `,s=[`-----BEGIN ${t}-----`];if(r.headers){for(const[i,a]of Object.entries(r.headers))s.push(`${i}: ${a}`);s.push("")}return s.push(...yE(gs.encode(e),n)),s.push(`-----END ${t}-----`),`${s.join(o)}${o}`}function bE(t,e={}){return Sv(t,e).map(({lineLength:r,newline:n,...o})=>o)}function wE(t,e){const[r]=bE(t,{label:e,strict:!0});return r.data}function AE(t,e={}){const[r]=Sv(t,{...e,strict:!0}),n={label:r.label,headers:r.headers,lineLength:r.lineLength,newline:r.newline};return{bytes:r.data,format:n,normalized:Bd(r.label,r.data,n)}}function SE(t,e){return Bd(e.label,t,e)}const kE={name:"pem",encode:(t,e)=>{if(!e?.label)throw new TypeError("PEM label is required");return Bd(e.label,t,e)},decode:(t,e)=>wE(t,e?.label),format:SE,is:t=>typeof t=="string"&&/-----BEGIN [^-]+-----/.test(t),parse:AE};function zt(t){return t.trim().toLowerCase()}function EE(t){return t instanceof Error?t:new Error(String(t))}function Up(t,e,r){for(const n of[r.name,...r.aliases??[]])t.delete(zt(n));e.delete(zt(r.name))}function Hc(t,e,r){const n=t[r];if(typeof n!="function")throw new Error(`Converter '${e}' does not support ${r}()`);return n}function xE(t,e,r){const n=zt(r.name||t),o=e.trim();if(!o)return 0;let s=!1;r.is&&(s=r.is(e));let i=!1;try{r.decode(e),i=!0}catch{i=!1}if(!s&&!i)return 0;switch(n){case"pem":return/-----BEGIN [^-]+-----/.test(e)?1:0;case"hex":{const a=o.replace(/^0x/i,"").replace(/[\s:.-]/g,"");return!a||/[^0-9a-f]/i.test(a)||a.length%2!==0?0:/^0x/i.test(o)||/[:\s.-]/.test(o)?.95:/[a-f]/.test(o)||/[A-F]/.test(o)?.8:.45}case"base64url":return/[-_]/.test(o)?.95:/=/.test(o)?.1:.6;case"base64":return/[+/=]/.test(o)?.9:.55;case"binary":case"utf8":case"utf16be":case"utf16le":return 0;default:return s&&i?.75:.5}}function IE(t=[]){const e=new Map,r=new Set,n={register(o,s={}){if(!o.name||!zt(o.name))throw new TypeError("Converter name is required");const i=[...new Set([o.name,...o.aliases??[]].map(zt))],a=new Set;for(const c of i){const u=e.get(c);if(u){if(!s.override)throw new Error(`Converter '${c}' is already registered`);a.add(u)}}for(const c of a)Up(e,r,c);for(const c of i)e.set(c,o);return r.add(zt(o.name)),this},unregister(o){const s=e.get(zt(o));return s?(Up(e,r,s),!0):!1},has(o){return e.has(zt(o))},get(o){const s=e.get(zt(o));if(!s)throw new Error(`Converter '${o}' is not registered`);return s},list(){return[...r].map(o=>this.get(o))},encode(o,s,i){return this.get(o).encode(s,i)},decode(o,s,i){return this.get(o).decode(s,i)},tryDecode(o,s,i){try{return{ok:!0,bytes:this.decode(o,s,i)}}catch(a){return{ok:!1,error:EE(a)}}},normalize(o,s,i){const a=this.get(o);return Hc(a,o,"normalize").call(a,s,i)},parse(o,s,i){const a=this.get(o);return Hc(a,o,"parse").call(a,s,i)},format(o,s,i){const a=this.get(o);return Hc(a,o,"format").call(a,s,i)},transcode(o,s){const i=this.decode(s.from,o,s.fromOptions);return this.encode(s.to,i,s.toOptions)},detect(o,s={}){const i=s.formats?.length?s.formats.map(c=>String(c)):this.list().map(c=>c.name).filter(c=>!["binary","utf8","utf16be","utf16le"].includes(zt(c))),a=new Map;for(const c of i){const u=this.get(c),d=xE(c,o,u);if(d<=0)continue;const l=u.name,m=a.get(l);(!m||d>m.confidence)&&a.set(l,{format:l,confidence:d})}return[...a.values()].sort((c,u)=>u.confidence-c.confidence)}};for(const o of t)n.register(o);return n}const OE={name:"binary",aliases:["latin1"],encode:fv,decode:pv,is:zk},CE={name:"hex",encode:Fa,decode:hv,format:aE,is:sE,normalize:Ha,parse:iE},NE={name:"base64",aliases:["b64"],encode:vv,decode:bv,is:Td,normalize:Wa},TE={name:"base64url",aliases:["base64-url","b64url"],encode:pE,decode:hE,is:wv,normalize:$d},$E={name:"utf8",aliases:["utf-8"],encode:t=>uE(t),decode:t=>cE(t),is:t=>typeof t=="string"},BE={name:"utf16be",aliases:["utf16","utf-16","utf-16be"],encode:t=>yv(t),decode:t=>mv(t),is:t=>typeof t=="string"},RE={name:"utf16le",aliases:["utf-16le","ucs2","usc2"],encode:t=>yv(t,{littleEndian:!0}),decode:t=>mv(t,{littleEndian:!0}),is:t=>typeof t=="string"},ME=[OE,CE,NE,TE,$E,BE,RE,kE];IE(ME);var R;(function(t){t[t.Sequence=0]="Sequence",t[t.Set=1]="Set",t[t.Choice=2]="Choice"})(R||(R={}));var b;(function(t){t[t.Any=1]="Any",t[t.Boolean=2]="Boolean",t[t.OctetString=3]="OctetString",t[t.BitString=4]="BitString",t[t.Integer=5]="Integer",t[t.Enumerated=6]="Enumerated",t[t.ObjectIdentifier=7]="ObjectIdentifier",t[t.Utf8String=8]="Utf8String",t[t.BmpString=9]="BmpString",t[t.UniversalString=10]="UniversalString",t[t.NumericString=11]="NumericString",t[t.PrintableString=12]="PrintableString",t[t.TeletexString=13]="TeletexString",t[t.VideotexString=14]="VideotexString",t[t.IA5String=15]="IA5String",t[t.GraphicString=16]="GraphicString",t[t.VisibleString=17]="VisibleString",t[t.GeneralString=18]="GeneralString",t[t.CharacterString=19]="CharacterString",t[t.UTCTime=20]="UTCTime",t[t.GeneralizedTime=21]="GeneralizedTime",t[t.DATE=22]="DATE",t[t.TimeOfDay=23]="TimeOfDay",t[t.DateTime=24]="DateTime",t[t.Duration=25]="Duration",t[t.TIME=26]="TIME",t[t.Null=27]="Null",t[t.RelativeObjectIdentifier=28]="RelativeObjectIdentifier"})(b||(b={}));class Ka{unusedBits=0;value=new ArrayBuffer(0);constructor(e,r=0){if(e)if(typeof e=="number")this.fromNumber(e);else if(Va(e))this.unusedBits=r,this.value=Nt(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof on))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=Nt(e.valueBlock.valueHex),this}toASN(){return new on({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new on({name:e})}toNumber(){let e="";const r=new Uint8Array(this.value);for(const n of r)e+=n.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let r=e.toString(2);const n=r.length+7>>3;this.unusedBits=(n<<3)-r.length;const o=new Uint8Array(n);r=r.padStart(n<<3,"0").split("").reverse().join("");let s=0;for(;s<n;)o[s]=parseInt(r.slice(s<<3,(s<<3)+8),2),s++;this.value=o.buffer}}class he{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):Va(e)?this.buffer=Nt(e):Array.isArray(e)?this.buffer=new Uint8Array(e).buffer:this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof nn))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=Nt(e.valueBlock.valueHex),this}toASN(){return new nn({valueHex:this.buffer})}toSchema(e){return new nn({name:e})}}const _E={fromASN:t=>t instanceof dn?null:Nt(t.valueBeforeDecodeView),toASN:t=>{if(t===null)return new dn;const e=Gn(t);if(e.result.error)throw new Error(e.result.error);return e.result}},jE={fromASN:t=>t.valueBlock.valueHexView.byteLength>=4?t.valueBlock.toString():t.valueBlock.valueDec,toASN:t=>new mo({value:+t})},DE={fromASN:t=>t.valueBlock.valueDec,toASN:t=>new Oa({value:t})},xe={fromASN:t=>Nt(t.valueBlock.valueHexView),toASN:t=>new mo({valueHex:t})},LE={fromASN:t=>Nt(t.valueBlock.valueHexView),toASN:t=>new on({valueHex:t})},PE={fromASN:t=>t.valueBlock.toString(),toASN:t=>new Ca({value:t})},UE={fromASN:t=>t.valueBlock.toString(),toASN:t=>new Na({value:t})},VE={fromASN:t=>t.valueBlock.value,toASN:t=>new Ia({value:t})},Ri={fromASN:t=>Nt(t.valueBlock.valueHexView),toASN:t=>new nn({valueHex:t})},HE={fromASN:t=>new he(t.getValue()),toASN:t=>t.toASN()};function Tt(t){return{fromASN:e=>e.valueBlock.value,toASN:e=>new t({value:e})}}const kv=Tt(kr),FE=Tt(Ta),WE=Tt($a),KE=Tt(Ba),GE=Tt(Ra),qE=Tt(Ma),zE=Tt(_a),YE=Tt(ja),XE=Tt(Da),JE=Tt(_s),ZE=Tt(La),QE=Tt(Pa),ex={fromASN:t=>t.toDate(),toASN:t=>new js({valueDate:t})},tx={fromASN:t=>t.toDate(),toASN:t=>new Ua({valueDate:t})},rx={fromASN:()=>null,toASN:()=>new dn};function rs(t){switch(t){case b.Any:return _E;case b.BitString:return LE;case b.BmpString:return FE;case b.Boolean:return VE;case b.CharacterString:return QE;case b.Enumerated:return DE;case b.GeneralString:return ZE;case b.GeneralizedTime:return tx;case b.GraphicString:return XE;case b.IA5String:return YE;case b.Integer:return jE;case b.Null:return rx;case b.NumericString:return KE;case b.ObjectIdentifier:return PE;case b.RelativeObjectIdentifier:return UE;case b.OctetString:return Ri;case b.PrintableString:return GE;case b.TeletexString:return qE;case b.UTCTime:return ex;case b.UniversalString:return WE;case b.Utf8String:return kv;case b.VideotexString:return zE;case b.VisibleString:return JE;default:return null}}function fr(t){return typeof t=="function"&&t.prototype?t.prototype.toASN&&t.prototype.fromASN?!0:fr(t.prototype):!!(t&&typeof t=="object"&&"toASN"in t&&"fromASN"in t)}function Ev(t){if(t){const e=Object.getPrototypeOf(t);return e?.prototype?.constructor===Array?!0:Ev(e)}return!1}function nx(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;const r=new Uint8Array(t),n=new Uint8Array(e);for(let o=0;o<t.byteLength;o++)if(r[o]!==n[o])return!1;return!0}class ox{items=new WeakMap;has(e){return this.items.has(e)}get(e,r=!1){const n=this.items.get(e);if(!n)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(r&&!n.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return n}cache(e){const r=this.get(e);r.schema||(r.schema=this.create(e,!0))}createDefault(e){const r={type:R.Sequence,items:{}},n=this.findParentSchema(e);return n&&(Object.assign(r,n),r.items=Object.assign({},r.items,n.items)),r}create(e,r){const n=this.items.get(e)||this.createDefault(e),o=[];for(const s in n.items){const i=n.items[s],a=r?s:"";let c;if(typeof i.type=="number"){const d=b[i.type],l=cv[d];if(!l)throw new Error(`Cannot get ASN1 class by name '${d}'`);c=new l({name:a})}else fr(i.type)?c=new i.type().toSchema(a):i.optional?this.get(i.type).type===R.Choice?c=new fn({name:a}):(c=this.create(i.type,!1),c.name=a):c=new fn({name:a});const u=!!i.optional||i.defaultValue!==void 0;if(i.repeated){c.name="";const d=i.repeated==="set"?Jt:Pt;c=new d({name:"",value:[new Bi({name:a,value:c})]})}if(i.context!==null&&i.context!==void 0)if(i.implicit)if(typeof i.type=="number"||fr(i.type)){const d=i.repeated?et:Rs;o.push(new d({name:a,optional:u,idBlock:{tagClass:3,tagNumber:i.context}}))}else{this.cache(i.type);const d=!!i.repeated;let l=d?c:this.get(i.type,!0).schema;l="valueBlock"in l?l.valueBlock.value:l.value,o.push(new et({name:d?"":a,optional:u,idBlock:{tagClass:3,tagNumber:i.context},value:l}))}else o.push(new et({optional:u,idBlock:{tagClass:3,tagNumber:i.context},value:[c]}));else c.optional=u,o.push(c)}switch(n.type){case R.Sequence:return new Pt({value:o,name:""});case R.Set:return new Jt({value:o,name:""});case R.Choice:return new Cd({value:o,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,r){return this.items.set(e,r),this}findParentSchema(e){const r=Object.getPrototypeOf(e);return r?this.items.get(r)||this.findParentSchema(r):null}}const Fe=new ox,j=t=>e=>{let r;Fe.has(e)?r=Fe.get(e):(r=Fe.createDefault(e),Fe.set(e,r)),Object.assign(r,t)},y=t=>(e,r)=>{let n;Fe.has(e.constructor)?n=Fe.get(e.constructor):(n=Fe.createDefault(e.constructor),Fe.set(e.constructor,n));const o=Object.assign({},t);if(typeof o.type=="number"&&!o.converter){const s=rs(t.type);if(!s)throw new Error(`Cannot get default converter for property '${r}' of ${e.constructor.name}`);o.converter=s}o.raw=t.raw,n.items[r]=o};class To extends Error{schemas=[]}class sx{static parse(e,r,n){const o=Gn(Nt(e),n?.berOptions);if(o.result.error)throw new Error(o.result.error);return this.fromASN(o.result,r,n)}static fromASN(e,r,n){try{if(fr(r))return new r().fromASN(e);const o=Fe.get(r);Fe.cache(r);let s=o.schema;const i=this.handleChoiceTypes(e,o,r,s,n);if(i?.result)return i.result;i?.targetSchema&&(s=i.targetSchema);const a=this.handleSequenceTypes(e,o,r,s),c=new r;return Ev(r)?this.handleArrayTypes(e,o,r,n):(this.processSchemaItems(o,a,c,n),c)}catch(o){throw o instanceof To&&o.schemas.push(r.name),o}}static handleChoiceTypes(e,r,n,o,s){if(e.constructor===et&&r.type===R.Choice&&e.idBlock.tagClass===3)for(const i in r.items){const a=r.items[i];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type=="function"&&Fe.has(a.type)){const c=Fe.get(a.type);if(c&&c.type===R.Sequence){const u=new Pt;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in u.valueBlock){u.valueBlock.value=e.valueBlock.value;const d=this.fromASN(u,a.type,s),l=new n;return l[i]=d,{result:l}}}}}else if(e.constructor===et&&r.type!==R.Choice){const i=new et({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:r.schema.valueBlock.value});for(const a in r.items)delete e[a];return{targetSchema:i}}return null}static handleSequenceTypes(e,r,n,o){if(r.type===R.Sequence){const s=Tr({},e,o);if(!s.verified)throw new To(`Data does not match to ${n.name} ASN1 schema.${s.result.error?` ${s.result.error}`:""}`);return s}else{const s=Tr({},e,o);if(!s.verified)throw new To(`Data does not match to ${n.name} ASN1 schema.${s.result.error?` ${s.result.error}`:""}`);return s}}static processRepeatedField(e,r,n){let o=e.slice(r);if(o.length===1&&o[0].constructor.name==="Sequence"){const s=o[0];s.valueBlock&&s.valueBlock.value&&Array.isArray(s.valueBlock.value)&&(o=s.valueBlock.value)}if(typeof n.type=="number"){const s=rs(n.type);if(!s)throw new Error(`No converter for ASN.1 type ${n.type}`);return o.filter(i=>i&&i.valueBlock).map(i=>{try{return s.fromASN(i)}catch{return}}).filter(i=>i!==void 0)}else return o.filter(s=>s&&s.valueBlock).map(s=>{try{return this.fromASN(s,n.type)}catch{return}}).filter(s=>s!==void 0)}static processPrimitiveField(e,r){const n=rs(r.type);if(!n)throw new Error(`No converter for ASN.1 type ${r.type}`);return n.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type=="function"&&Fe.has(e.type)&&Fe.get(e.type).type===R.Choice}static processOptionalChoiceField(e,r){try{return{processed:!0,value:this.fromASN(e,r.type)}}catch(n){if(n instanceof To&&/Wrong values for Choice type/.test(n.message))return{processed:!1};throw n}}static handleArrayTypes(e,r,n,o){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const s=r.itemType;if(typeof s=="number"){const i=rs(s);if(!i)throw new Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);return n.from(e.valueBlock.value,a=>i.fromASN(a))}else return n.from(e.valueBlock.value,i=>this.fromASN(i,s,o))}static processSchemaItems(e,r,n,o){for(const s in e.items){const i=r.result[s];if(!i)continue;const a=e.items[s],c=a.type;let u;typeof c=="number"||fr(c)?u=this.processPrimitiveSchemaItem(i,a,c,o):u=this.processComplexSchemaItem(i,a,c,o),u&&typeof u=="object"&&"value"in u&&"raw"in u?(n[s]=u.value,n[`${s}Raw`]=u.raw):n[s]=u}}static processPrimitiveSchemaItem(e,r,n,o){const s=r.converter??(fr(n)?new n:null);if(!s)throw new Error("Converter is empty");return r.repeated?this.processRepeatedPrimitiveItem(e,r,s,o):this.processSinglePrimitiveItem(e,r,n,s,o)}static processRepeatedPrimitiveItem(e,r,n,o){if(r.implicit){const s=r.repeated==="sequence"?Pt:Jt,i=new s;i.valueBlock=e.valueBlock;const a=Gn(i.toBER(!1),o?.berOptions);if(a.offset===-1)throw new Error(`Cannot parse the child item. ${a.result.error}`);if(!("value"in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const c=a.result.valueBlock.value;return Array.from(c,u=>n.fromASN(u))}else return Array.from(e,s=>n.fromASN(s))}static processSinglePrimitiveItem(e,r,n,o,s){let i=e;if(r.implicit){let a;if(fr(n))a=new n().toSchema("");else{const c=b[n],u=cv[c];if(!u)throw new Error(`Cannot get '${c}' class from asn1js module`);a=new u}a.valueBlock=i.valueBlock,i=Gn(a.toBER(!1),s?.berOptions).result}return o.fromASN(i)}static processComplexSchemaItem(e,r,n,o){if(r.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,s=>this.fromASN(s,n,o))}else{const s=this.handleImplicitTagging(e,r,n);if(this.isOptionalChoiceField(r))try{return this.fromASN(s,n,o)}catch(i){if(i instanceof To&&/Wrong values for Choice type/.test(i.message))return;throw i}else{const i=this.fromASN(s,n,o);return r.raw?{value:i,raw:e.valueBeforeDecodeView}:i}}}static handleImplicitTagging(e,r,n){if(r.implicit&&typeof r.context=="number"){const o=Fe.get(n);if(o.type===R.Sequence){const s=new Pt;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in s.valueBlock)return s.valueBlock.value=e.valueBlock.value,s}else if(o.type===R.Set){const s=new Jt;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in s.valueBlock)return s.valueBlock.value=e.valueBlock.value,s}}return e}}class Rd{static serialize(e){return e instanceof Ve?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&fr(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");const r=e.constructor,n=Fe.get(r);Fe.cache(r);let o=[];if(n.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if(typeof n.itemType=="number"){const i=rs(n.itemType);if(!i)throw new Error(`Cannot get default converter for array item of ${r.name} ASN1 schema`);o=e.map(a=>i.toASN(a))}else o=e.map(i=>this.toAsnItem({type:n.itemType},"[]",r,i))}else for(const i in n.items){const a=n.items[i],c=e[i];if(c===void 0||a.defaultValue===c||typeof a.defaultValue=="object"&&typeof c=="object"&&nx(this.serialize(a.defaultValue),this.serialize(c)))continue;const u=Rd.toAsnItem(a,i,r,c);if(typeof a.context=="number")if(a.implicit)if(!a.repeated&&(typeof a.type=="number"||fr(a.type))){const d={};d.valueHex=u instanceof dn?Nt(u.valueBeforeDecodeView):u.valueBlock.toBER(),o.push(new Rs({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},...d}))}else o.push(new et({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:u.valueBlock.value}));else o.push(new et({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:[u]}));else a.repeated?o=o.concat(u):o.push(u)}let s;switch(n.type){case R.Sequence:s=new Pt({value:o});break;case R.Set:s=new Jt({value:o});break;case R.Choice:if(!o[0])throw new Error(`Schema '${r.name}' has wrong data. Choice cannot be empty.`);s=o[0];break}return s}static toAsnItem(e,r,n,o){let s;if(typeof e.type=="number"){const i=e.converter;if(!i)throw new Error(`Property '${r}' doesn't have converter for type ${b[e.type]} in schema '${n.name}'`);if(e.repeated){if(!Array.isArray(o))throw new TypeError("Parameter 'objProp' should be type of Array.");const a=Array.from(o,u=>i.toASN(u)),c=e.repeated==="sequence"?Pt:Jt;s=new c({value:a})}else s=i.toASN(o)}else if(e.repeated){if(!Array.isArray(o))throw new TypeError("Parameter 'objProp' should be type of Array.");const i=Array.from(o,c=>this.toASN(c)),a=e.repeated==="sequence"?Pt:Jt;s=new a({value:i})}else s=this.toASN(o);return s}}class pe extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(const r of e)this.push(r)}}}class H{static serialize(e){return Rd.serialize(e)}static parse(e,r,n){return sx.parse(e,r,n)}static toString(e,r){const n=Va(e)?Nt(e):H.serialize(e),o=Gn(n,r?.berOptions);if(o.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${o.result.error}`);return o.result.toString()}}function f(t,e,r,n){var o=arguments.length,s=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(o<3?i(s):o>3?i(e,r,s):i(e,r))||s);return o>3&&s&&Object.defineProperty(e,r,s),s}function oe(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function ke(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}class Vp{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){const r=e.split(".");if(r.length!==4)throw new Error("Invalid IPv4 address");return r.map(n=>{const o=parseInt(n,10);if(isNaN(o)||o<0||o>255)throw new Error("Invalid IPv4 address part");return o})}static parseIPv6(e){const n=this.expandIPv6(e).split(":");if(n.length!==8)throw new Error("Invalid IPv6 address");return n.reduce((o,s)=>{const i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error("Invalid IPv6 address part");return o.push(i>>8&255),o.push(i&255),o},[])}static expandIPv6(e){if(!e.includes("::"))return e;const r=e.split("::");if(r.length>2)throw new Error("Invalid IPv6 address");const n=r[0]?r[0].split(":"):[],o=r[1]?r[1].split(":"):[],s=8-(n.length+o.length);if(s<0)throw new Error("Invalid IPv6 address");return[...n,...Array(s).fill("0"),...o].join(":")}static formatIPv6(e){const r=[];for(let n=0;n<16;n+=2)r.push((e[n]<<8|e[n+1]).toString(16));return this.compressIPv6(r.join(":"))}static compressIPv6(e){const r=e.split(":");let n=-1,o=0,s=-1,i=0;for(let a=0;a<r.length;a++)r[a]==="0"?(s===-1&&(s=a),i++):(i>o&&(n=s,o=i),s=-1,i=0);if(i>o&&(n=s,o=i),o>1){const a=r.slice(0,n).join(":"),c=r.slice(n+o).join(":");return`${a}::${c}`}return e}static parseCIDR(e){const[r,n]=e.split("/"),o=parseInt(n,10);if(this.isIPv4(r)){if(o<0||o>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(r),o]}else{if(o<0||o>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(r),o]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;const r=parseInt(e.slice(8),16).toString(2).split("").reduce((o,s)=>o+ +s,0);let n=e.slice(0,8).replace(/(.{2})/g,o=>`${parseInt(o,16)}.`);return n=n.slice(0,-1),`${n}/${r}`}static toString(e){const r=new Uint8Array(e);if(r.length===4)return Array.from(r).join(".");if(r.length===16)return this.formatIPv6(r);if(r.length===8||r.length===32){const n=r.length/2,o=r.slice(0,n),s=r.slice(n);if(r.every(c=>c===0))return r.length===8?"0.0.0.0/0":"::/0";const a=s.reduce((c,u)=>c+(u.toString(2).match(/1/g)||[]).length,0);return r.length===8?`${Array.from(o).join(".")}/${a}`:`${this.formatIPv6(o)}/${a}`}return this.decodeIP(Fa(e))}static fromString(e){if(e.includes("/")){const[n,o]=this.parseCIDR(e),s=new Uint8Array(n.length);let i=o;for(let c=0;c<s.length;c++)i>=8?(s[c]=255,i-=8):i>0&&(s[c]=255<<8-i,i=0);const a=new Uint8Array(n.length*2);return a.set(n,0),a.set(s,n.length),a.buffer}const r=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(r).buffer}}var vu,bu,wu;let Ge=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};f([y({type:b.TeletexString})],Ge.prototype,"teletexString",void 0);f([y({type:b.PrintableString})],Ge.prototype,"printableString",void 0);f([y({type:b.UniversalString})],Ge.prototype,"universalString",void 0);f([y({type:b.Utf8String})],Ge.prototype,"utf8String",void 0);f([y({type:b.BmpString})],Ge.prototype,"bmpString",void 0);Ge=f([j({type:R.Choice})],Ge);let to=class extends Ge{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Fa(this.anyValue):super.toString())}};f([y({type:b.IA5String})],to.prototype,"ia5String",void 0);f([y({type:b.Any})],to.prototype,"anyValue",void 0);to=f([j({type:R.Choice})],to);class Ga{type="";value=new to;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Ga.prototype,"type",void 0);f([y({type:to})],Ga.prototype,"value",void 0);let ro=vu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,vu.prototype)}};ro=vu=f([j({type:R.Set,itemType:Ga})],ro);let Au=bu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,bu.prototype)}};Au=bu=f([j({type:R.Sequence,itemType:ro})],Au);let Re=wu=class extends Au{constructor(e){super(e),Object.setPrototypeOf(this,wu.prototype)}};Re=wu=f([j({type:R.Sequence})],Re);const ix={fromASN:t=>Vp.toString(Ri.fromASN(t)),toASN:t=>Ri.toASN(Vp.fromString(t))};class vs{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],vs.prototype,"typeId",void 0);f([y({type:b.Any,context:0})],vs.prototype,"value",void 0);class Md{nameAssigner;partyName=new Ge;constructor(e={}){Object.assign(this,e)}}f([y({type:Ge,optional:!0,context:0,implicit:!0})],Md.prototype,"nameAssigner",void 0);f([y({type:Ge,context:1,implicit:!0})],Md.prototype,"partyName",void 0);let ie=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};f([y({type:vs,context:0,implicit:!0})],ie.prototype,"otherName",void 0);f([y({type:b.IA5String,context:1,implicit:!0})],ie.prototype,"rfc822Name",void 0);f([y({type:b.IA5String,context:2,implicit:!0})],ie.prototype,"dNSName",void 0);f([y({type:b.Any,context:3,implicit:!0})],ie.prototype,"x400Address",void 0);f([y({type:Re,context:4,implicit:!1})],ie.prototype,"directoryName",void 0);f([y({type:Md,context:5})],ie.prototype,"ediPartyName",void 0);f([y({type:b.IA5String,context:6,implicit:!0})],ie.prototype,"uniformResourceIdentifier",void 0);f([y({type:b.OctetString,context:7,implicit:!0,converter:ix})],ie.prototype,"iPAddress",void 0);f([y({type:b.ObjectIdentifier,context:8,implicit:!0})],ie.prototype,"registeredID",void 0);ie=f([j({type:R.Choice})],ie);const _d="1.3.6.1.5.5.7",ax=`${_d}.1`,yo=`${_d}.3`,qa=`${_d}.48`,Hp=`${qa}.1`,Fp=`${qa}.2`,Wp=`${qa}.3`,Kp=`${qa}.5`,Er="2.5.29";var Su;const ku=`${ax}.1`;class Ds{accessMethod="";accessLocation=new ie;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Ds.prototype,"accessMethod",void 0);f([y({type:ie})],Ds.prototype,"accessLocation",void 0);let Hn=Su=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Su.prototype)}};Hn=Su=f([j({type:R.Sequence,itemType:Ds})],Hn);const Eu=`${Er}.35`;class jd extends he{}class Qr{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}}f([y({type:jd,context:0,optional:!0,implicit:!0})],Qr.prototype,"keyIdentifier",void 0);f([y({type:ie,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Qr.prototype,"authorityCertIssuer",void 0);f([y({type:b.Integer,context:2,optional:!0,implicit:!0,converter:xe})],Qr.prototype,"authorityCertSerialNumber",void 0);const xv=`${Er}.19`;class Mi{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Boolean,defaultValue:!1})],Mi.prototype,"cA",void 0);f([y({type:b.Integer,optional:!0})],Mi.prototype,"pathLenConstraint",void 0);var xu;let Ye=xu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,xu.prototype)}};Ye=xu=f([j({type:R.Sequence,itemType:ie})],Ye);var Iu;let Gp=Iu=class extends Ye{constructor(e){super(e),Object.setPrototypeOf(this,Iu.prototype)}};Gp=Iu=f([j({type:R.Sequence})],Gp);var Ou;const Iv=`${Er}.32`;let yr=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};f([y({type:b.IA5String})],yr.prototype,"ia5String",void 0);f([y({type:b.VisibleString})],yr.prototype,"visibleString",void 0);f([y({type:b.BmpString})],yr.prototype,"bmpString",void 0);f([y({type:b.Utf8String})],yr.prototype,"utf8String",void 0);yr=f([j({type:R.Choice})],yr);class Dd{organization=new yr;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}}f([y({type:yr})],Dd.prototype,"organization",void 0);f([y({type:b.Integer,repeated:"sequence"})],Dd.prototype,"noticeNumbers",void 0);class Ld{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}}f([y({type:Dd,optional:!0})],Ld.prototype,"noticeRef",void 0);f([y({type:yr,optional:!0})],Ld.prototype,"explicitText",void 0);let _i=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};f([y({type:b.IA5String})],_i.prototype,"cPSuri",void 0);f([y({type:Ld})],_i.prototype,"userNotice",void 0);_i=f([j({type:R.Choice})],_i);class Pd{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Pd.prototype,"policyQualifierId",void 0);f([y({type:b.Any})],Pd.prototype,"qualifier",void 0);class za{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],za.prototype,"policyIdentifier",void 0);f([y({type:Pd,repeated:"sequence",optional:!0})],za.prototype,"policyQualifiers",void 0);let ji=Ou=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Ou.prototype)}};ji=Ou=f([j({type:R.Sequence,itemType:za})],ji);let Di=class{value;constructor(e=0){this.value=e}};f([y({type:b.Integer})],Di.prototype,"value",void 0);Di=f([j({type:R.Choice})],Di);let qp=class extends Di{};qp=f([j({type:R.Choice})],qp);var Cu;const Nu=`${Er}.31`;var Mt;(function(t){t[t.unused=1]="unused",t[t.keyCompromise=2]="keyCompromise",t[t.cACompromise=4]="cACompromise",t[t.affiliationChanged=8]="affiliationChanged",t[t.superseded=16]="superseded",t[t.cessationOfOperation=32]="cessationOfOperation",t[t.certificateHold=64]="certificateHold",t[t.privilegeWithdrawn=128]="privilegeWithdrawn",t[t.aACompromise=256]="aACompromise"})(Mt||(Mt={}));class Ov extends Ka{toJSON(){const e=[],r=this.toNumber();return r&Mt.aACompromise&&e.push("aACompromise"),r&Mt.affiliationChanged&&e.push("affiliationChanged"),r&Mt.cACompromise&&e.push("cACompromise"),r&Mt.certificateHold&&e.push("certificateHold"),r&Mt.cessationOfOperation&&e.push("cessationOfOperation"),r&Mt.keyCompromise&&e.push("keyCompromise"),r&Mt.privilegeWithdrawn&&e.push("privilegeWithdrawn"),r&Mt.superseded&&e.push("superseded"),r&Mt.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let hn=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};f([y({type:ie,context:0,repeated:"sequence",implicit:!0})],hn.prototype,"fullName",void 0);f([y({type:ro,context:1,implicit:!0})],hn.prototype,"nameRelativeToCRLIssuer",void 0);hn=f([j({type:R.Choice})],hn);class go{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}}f([y({type:hn,context:0,optional:!0})],go.prototype,"distributionPoint",void 0);f([y({type:Ov,context:1,optional:!0,implicit:!0})],go.prototype,"reasons",void 0);f([y({type:ie,context:2,optional:!0,repeated:"sequence",implicit:!0})],go.prototype,"cRLIssuer",void 0);let qn=Cu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Cu.prototype)}};qn=Cu=f([j({type:R.Sequence,itemType:go})],qn);var Tu;let zp=Tu=class extends qn{constructor(e){super(e),Object.setPrototypeOf(this,Tu.prototype)}};zp=Tu=f([j({type:R.Sequence,itemType:go})],zp);class Qe{static ONLY=!1;distributionPoint;onlyContainsUserCerts=Qe.ONLY;onlyContainsCACerts=Qe.ONLY;onlySomeReasons;indirectCRL=Qe.ONLY;onlyContainsAttributeCerts=Qe.ONLY;constructor(e={}){Object.assign(this,e)}}f([y({type:hn,context:0,optional:!0})],Qe.prototype,"distributionPoint",void 0);f([y({type:b.Boolean,context:1,defaultValue:Qe.ONLY,implicit:!0})],Qe.prototype,"onlyContainsUserCerts",void 0);f([y({type:b.Boolean,context:2,defaultValue:Qe.ONLY,implicit:!0})],Qe.prototype,"onlyContainsCACerts",void 0);f([y({type:Ov,context:3,optional:!0,implicit:!0})],Qe.prototype,"onlySomeReasons",void 0);f([y({type:b.Boolean,context:4,defaultValue:Qe.ONLY,implicit:!0})],Qe.prototype,"indirectCRL",void 0);f([y({type:b.Boolean,context:5,defaultValue:Qe.ONLY,implicit:!0})],Qe.prototype,"onlyContainsAttributeCerts",void 0);var ns;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(ns||(ns={}));let $u=class{reason=ns.unspecified;constructor(e=ns.unspecified){this.reason=e}toJSON(){return ns[this.reason]}toString(){return this.toJSON()}};f([y({type:b.Enumerated})],$u.prototype,"reason",void 0);$u=f([j({type:R.Choice})],$u);var Bu;const Cv=`${Er}.37`;let Li=Bu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Bu.prototype)}};Li=Bu=f([j({type:R.Sequence,itemType:b.ObjectIdentifier})],Li);const cx=`${yo}.1`,ux=`${yo}.2`,lx=`${yo}.3`,dx=`${yo}.4`,fx=`${yo}.8`,px=`${yo}.9`;let Ru=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};f([y({type:b.Integer,converter:xe})],Ru.prototype,"value",void 0);Ru=f([j({type:R.Choice})],Ru);let Mu=class{value=new Date;constructor(e){e&&(this.value=e)}};f([y({type:b.GeneralizedTime})],Mu.prototype,"value",void 0);Mu=f([j({type:R.Choice})],Mu);var _u;const Nv=`${Er}.18`;let Yp=_u=class extends Ye{constructor(e){super(e),Object.setPrototypeOf(this,_u.prototype)}};Yp=_u=f([j({type:R.Sequence})],Yp);const Tv=`${Er}.15`;var _t;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(_t||(_t={}));class Fc extends Ka{toJSON(){const e=this.toNumber(),r=[];return e&_t.cRLSign&&r.push("crlSign"),e&_t.dataEncipherment&&r.push("dataEncipherment"),e&_t.decipherOnly&&r.push("decipherOnly"),e&_t.digitalSignature&&r.push("digitalSignature"),e&_t.encipherOnly&&r.push("encipherOnly"),e&_t.keyAgreement&&r.push("keyAgreement"),e&_t.keyCertSign&&r.push("keyCertSign"),e&_t.keyEncipherment&&r.push("keyEncipherment"),e&_t.nonRepudiation&&r.push("nonRepudiation"),r}toString(){return`[${this.toJSON().join(", ")}]`}}var ju;class Ya{base=new ie;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}}f([y({type:ie})],Ya.prototype,"base",void 0);f([y({type:b.Integer,context:0,defaultValue:0,implicit:!0})],Ya.prototype,"minimum",void 0);f([y({type:b.Integer,context:1,optional:!0,implicit:!0})],Ya.prototype,"maximum",void 0);let Pi=ju=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,ju.prototype)}};Pi=ju=f([j({type:R.Sequence,itemType:Ya})],Pi);class $v{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}}f([y({type:Pi,context:0,optional:!0,implicit:!0})],$v.prototype,"permittedSubtrees",void 0);f([y({type:Pi,context:1,optional:!0,implicit:!0})],$v.prototype,"excludedSubtrees",void 0);class Bv{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,context:0,implicit:!0,optional:!0,converter:xe})],Bv.prototype,"requireExplicitPolicy",void 0);f([y({type:b.Integer,context:1,implicit:!0,optional:!0,converter:xe})],Bv.prototype,"inhibitPolicyMapping",void 0);var Du;class Ud{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Ud.prototype,"issuerDomainPolicy",void 0);f([y({type:b.ObjectIdentifier})],Ud.prototype,"subjectDomainPolicy",void 0);let Xp=Du=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Du.prototype)}};Xp=Du=f([j({type:R.Sequence,itemType:Ud})],Xp);var Lu;const Rv=`${Er}.17`;let Pu=Lu=class extends Ye{constructor(e){super(e),Object.setPrototypeOf(this,Lu.prototype)}};Pu=Lu=f([j({type:R.Sequence})],Pu);let gr=class{type="";values=[];constructor(e={}){Object.assign(this,e)}};f([y({type:b.ObjectIdentifier})],gr.prototype,"type",void 0);f([y({type:b.Any,repeated:"set"})],gr.prototype,"values",void 0);var Uu;let Jp=Uu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Uu.prototype)}};Jp=Uu=f([j({type:R.Sequence,itemType:gr})],Jp);const Mv=`${Er}.14`;class Mr extends jd{}class _v{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}}f([y({type:b.GeneralizedTime,context:0,implicit:!0,optional:!0})],_v.prototype,"notBefore",void 0);f([y({type:b.GeneralizedTime,context:1,implicit:!0,optional:!0})],_v.prototype,"notAfter",void 0);var os;(function(t){t[t.keyUpdateAllowed=1]="keyUpdateAllowed",t[t.newExtensions=2]="newExtensions",t[t.pKIXCertificate=4]="pKIXCertificate"})(os||(os={}));class jv extends Ka{toJSON(){const e=[],r=this.toNumber();return r&os.pKIXCertificate&&e.push("pKIXCertificate"),r&os.newExtensions&&e.push("newExtensions"),r&os.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class Dv{entrustVers="";entrustInfoFlags=new jv;constructor(e={}){Object.assign(this,e)}}f([y({type:b.GeneralString})],Dv.prototype,"entrustVers",void 0);f([y({type:jv})],Dv.prototype,"entrustInfoFlags",void 0);var Vu;let Zp=Vu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Vu.prototype)}};Zp=Vu=f([j({type:R.Sequence,itemType:Ds})],Zp);class W{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof W&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&qk(e.parameters,this.parameters)||e.parameters===this.parameters)}}f([y({type:b.ObjectIdentifier})],W.prototype,"algorithm",void 0);f([y({type:b.Any,optional:!0})],W.prototype,"parameters",void 0);class Ot{algorithm=new W;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:W})],Ot.prototype,"algorithm",void 0);f([y({type:b.BitString})],Ot.prototype,"subjectPublicKey",void 0);let We=class{utcTime;generalTime;constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){const r=new Date(e);r.setMilliseconds(0),r.getUTCFullYear()>2049?this.generalTime=r:this.utcTime=r}else Object.assign(this,e)}getTime(){const e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};f([y({type:b.UTCTime})],We.prototype,"utcTime",void 0);f([y({type:b.GeneralizedTime})],We.prototype,"generalTime",void 0);We=f([j({type:R.Choice})],We);class Ls{notBefore=new We(new Date);notAfter=new We(new Date);constructor(e){e&&(this.notBefore=new We(e.notBefore),this.notAfter=new We(e.notAfter))}}f([y({type:We})],Ls.prototype,"notBefore",void 0);f([y({type:We})],Ls.prototype,"notAfter",void 0);var Hu;let Vt=class Lv{static CRITICAL=!1;extnID="";critical=Lv.CRITICAL;extnValue=new he;constructor(e={}){Object.assign(this,e)}};f([y({type:b.ObjectIdentifier})],Vt.prototype,"extnID",void 0);f([y({type:b.Boolean,defaultValue:Vt.CRITICAL})],Vt.prototype,"critical",void 0);f([y({type:he})],Vt.prototype,"extnValue",void 0);let Dr=Hu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Hu.prototype)}};Dr=Hu=f([j({type:R.Sequence,itemType:Vt})],Dr);var mn;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2",t[t.v3=2]="v3"})(mn||(mn={}));class At{version=mn.v1;serialNumber=new ArrayBuffer(0);signature=new W;issuer=new Re;validity=new Ls;subject=new Re;subjectPublicKeyInfo=new Ot;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,context:0,defaultValue:mn.v1})],At.prototype,"version",void 0);f([y({type:b.Integer,converter:xe})],At.prototype,"serialNumber",void 0);f([y({type:W})],At.prototype,"signature",void 0);f([y({type:Re})],At.prototype,"issuer",void 0);f([y({type:Ls})],At.prototype,"validity",void 0);f([y({type:Re})],At.prototype,"subject",void 0);f([y({type:Ot})],At.prototype,"subjectPublicKeyInfo",void 0);f([y({type:b.BitString,context:1,implicit:!0,optional:!0})],At.prototype,"issuerUniqueID",void 0);f([y({type:b.BitString,context:2,implicit:!0,optional:!0})],At.prototype,"subjectUniqueID",void 0);f([y({type:Dr,context:3,optional:!0})],At.prototype,"extensions",void 0);class yn{tbsCertificate=new At;tbsCertificateRaw;signatureAlgorithm=new W;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:At,raw:!0})],yn.prototype,"tbsCertificate",void 0);f([y({type:W})],yn.prototype,"signatureAlgorithm",void 0);f([y({type:b.BitString})],yn.prototype,"signatureValue",void 0);class Xa{userCertificate=new ArrayBuffer(0);revocationDate=new We;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,converter:xe})],Xa.prototype,"userCertificate",void 0);f([y({type:We})],Xa.prototype,"revocationDate",void 0);f([y({type:Vt,optional:!0,repeated:"sequence"})],Xa.prototype,"crlEntryExtensions",void 0);class xr{version;signature=new W;issuer=new Re;thisUpdate=new We;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,optional:!0})],xr.prototype,"version",void 0);f([y({type:W})],xr.prototype,"signature",void 0);f([y({type:Re})],xr.prototype,"issuer",void 0);f([y({type:We})],xr.prototype,"thisUpdate",void 0);f([y({type:We,optional:!0})],xr.prototype,"nextUpdate",void 0);f([y({type:Xa,repeated:"sequence",optional:!0})],xr.prototype,"revokedCertificates",void 0);f([y({type:Vt,optional:!0,context:0,repeated:"sequence"})],xr.prototype,"crlExtensions",void 0);class Vd{tbsCertList=new xr;tbsCertListRaw;signatureAlgorithm=new W;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:xr,raw:!0})],Vd.prototype,"tbsCertList",void 0);f([y({type:W})],Vd.prototype,"signatureAlgorithm",void 0);f([y({type:b.BitString})],Vd.prototype,"signature",void 0);class vo{issuer=new Re;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:Re})],vo.prototype,"issuer",void 0);f([y({type:b.Integer,converter:xe})],vo.prototype,"serialNumber",void 0);let no=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([y({type:Mr,context:0,implicit:!0})],no.prototype,"subjectKeyIdentifier",void 0);f([y({type:vo})],no.prototype,"issuerAndSerialNumber",void 0);no=f([j({type:R.Choice})],no);var vr;(function(t){t[t.v0=0]="v0",t[t.v1=1]="v1",t[t.v2=2]="v2",t[t.v3=3]="v3",t[t.v4=4]="v4",t[t.v5=5]="v5"})(vr||(vr={}));let bs=class extends W{};bs=f([j({type:R.Sequence})],bs);let Ui=class extends W{};Ui=f([j({type:R.Sequence})],Ui);let Qt=class extends W{};Qt=f([j({type:R.Sequence})],Qt);let Vi=class extends W{};Vi=f([j({type:R.Sequence})],Vi);let Qp=class extends W{};Qp=f([j({type:R.Sequence})],Qp);let Fu=class extends W{};Fu=f([j({type:R.Sequence})],Fu);let bo=class{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}};f([y({type:b.ObjectIdentifier})],bo.prototype,"attrType",void 0);f([y({type:b.Any,repeated:"set"})],bo.prototype,"attrValues",void 0);var Wu;class sr{version=vr.v0;sid=new no;digestAlgorithm=new bs;signedAttrs;signedAttrsRaw;signatureAlgorithm=new Ui;signature=new he;unsignedAttrs;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],sr.prototype,"version",void 0);f([y({type:no})],sr.prototype,"sid",void 0);f([y({type:bs})],sr.prototype,"digestAlgorithm",void 0);f([y({type:bo,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],sr.prototype,"signedAttrs",void 0);f([y({type:Ui})],sr.prototype,"signatureAlgorithm",void 0);f([y({type:he})],sr.prototype,"signature",void 0);f([y({type:bo,repeated:"set",context:1,implicit:!0,optional:!0})],sr.prototype,"unsignedAttrs",void 0);let Hi=Wu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Wu.prototype)}};Hi=Wu=f([j({type:R.Set,itemType:sr})],Hi);let eh=class extends sr{};eh=f([j({type:R.Sequence})],eh);let th=class extends We{};th=f([j({type:R.Choice})],th);class Hd{acIssuer=new ie;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}}f([y({type:ie})],Hd.prototype,"acIssuer",void 0);f([y({type:b.Integer})],Hd.prototype,"acSerial",void 0);f([y({type:gr,repeated:"sequence"})],Hd.prototype,"attrs",void 0);var Ku;let Fi=Ku=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Ku.prototype)}};Fi=Ku=f([j({type:R.Sequence,itemType:b.ObjectIdentifier})],Fi);class Ja{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,optional:!0})],Ja.prototype,"pathLenConstraint",void 0);f([y({type:Fi,implicit:!0,context:0,optional:!0})],Ja.prototype,"permittedAttrs",void 0);f([y({type:Fi,implicit:!0,context:1,optional:!0})],Ja.prototype,"excludedAttrs",void 0);f([y({type:b.Boolean,defaultValue:!0})],Ja.prototype,"permitUnSpecified",void 0);class Cn{issuer=new Ye;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:Ye})],Cn.prototype,"issuer",void 0);f([y({type:b.Integer,converter:xe})],Cn.prototype,"serial",void 0);f([y({type:b.BitString,optional:!0})],Cn.prototype,"issuerUID",void 0);var Gu;(function(t){t[t.publicKey=0]="publicKey",t[t.publicKeyCert=1]="publicKeyCert",t[t.otherObjectTypes=2]="otherObjectTypes"})(Gu||(Gu={}));class Nn{digestedObjectType=Gu.publicKey;otherObjectTypeID;digestAlgorithm=new W;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.Enumerated})],Nn.prototype,"digestedObjectType",void 0);f([y({type:b.ObjectIdentifier,optional:!0})],Nn.prototype,"otherObjectTypeID",void 0);f([y({type:W})],Nn.prototype,"digestAlgorithm",void 0);f([y({type:b.BitString})],Nn.prototype,"objectDigest",void 0);class Za{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}f([y({type:Ye,optional:!0})],Za.prototype,"issuerName",void 0);f([y({type:Cn,context:0,implicit:!0,optional:!0})],Za.prototype,"baseCertificateID",void 0);f([y({type:Nn,context:1,implicit:!0,optional:!0})],Za.prototype,"objectDigestInfo",void 0);let oo=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};f([y({type:ie,repeated:"sequence"})],oo.prototype,"v1Form",void 0);f([y({type:Za,context:0,implicit:!0})],oo.prototype,"v2Form",void 0);oo=f([j({type:R.Choice})],oo);class Qa{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}}f([y({type:b.GeneralizedTime})],Qa.prototype,"notBeforeTime",void 0);f([y({type:b.GeneralizedTime})],Qa.prototype,"notAfterTime",void 0);class Ps{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}f([y({type:Cn,implicit:!0,context:0,optional:!0})],Ps.prototype,"baseCertificateID",void 0);f([y({type:Ye,implicit:!0,context:1,optional:!0})],Ps.prototype,"entityName",void 0);f([y({type:Nn,implicit:!0,context:2,optional:!0})],Ps.prototype,"objectDigestInfo",void 0);var qu;(function(t){t[t.v2=1]="v2"})(qu||(qu={}));class Ft{version=qu.v2;holder=new Ps;issuer=new oo;signature=new W;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new Qa;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Ft.prototype,"version",void 0);f([y({type:Ps})],Ft.prototype,"holder",void 0);f([y({type:oo})],Ft.prototype,"issuer",void 0);f([y({type:W})],Ft.prototype,"signature",void 0);f([y({type:b.Integer,converter:xe})],Ft.prototype,"serialNumber",void 0);f([y({type:Qa})],Ft.prototype,"attrCertValidityPeriod",void 0);f([y({type:gr,repeated:"sequence"})],Ft.prototype,"attributes",void 0);f([y({type:b.BitString,optional:!0})],Ft.prototype,"issuerUniqueID",void 0);f([y({type:Dr,optional:!0})],Ft.prototype,"extensions",void 0);class ec{acinfo=new Ft;signatureAlgorithm=new W;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:Ft})],ec.prototype,"acinfo",void 0);f([y({type:W})],ec.prototype,"signatureAlgorithm",void 0);f([y({type:b.BitString})],ec.prototype,"signatureValue",void 0);var Wi;(function(t){t[t.unmarked=1]="unmarked",t[t.unclassified=2]="unclassified",t[t.restricted=4]="restricted",t[t.confidential=8]="confidential",t[t.secret=16]="secret",t[t.topSecret=32]="topSecret"})(Wi||(Wi={}));class zu extends Ka{}class Fd{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier,implicit:!0,context:0})],Fd.prototype,"type",void 0);f([y({type:b.Any,implicit:!0,context:1})],Fd.prototype,"value",void 0);class Wd{policyId="";classList=new zu(Wi.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Wd.prototype,"policyId",void 0);f([y({type:zu,defaultValue:new zu(Wi.unclassified)})],Wd.prototype,"classList",void 0);f([y({type:Fd,repeated:"set"})],Wd.prototype,"securityCategories",void 0);class tc{cotets;oid;string;constructor(e={}){Object.assign(this,e)}}f([y({type:he})],tc.prototype,"cotets",void 0);f([y({type:b.ObjectIdentifier})],tc.prototype,"oid",void 0);f([y({type:b.Utf8String})],tc.prototype,"string",void 0);class Pv{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}}f([y({type:Ye,implicit:!0,context:0,optional:!0})],Pv.prototype,"policyAuthority",void 0);f([y({type:tc,repeated:"sequence"})],Pv.prototype,"values",void 0);var Yu;class rc{targetCertificate=new Cn;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}}f([y({type:Cn})],rc.prototype,"targetCertificate",void 0);f([y({type:ie,optional:!0})],rc.prototype,"targetName",void 0);f([y({type:Nn,optional:!0})],rc.prototype,"certDigestInfo",void 0);let so=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};f([y({type:ie,context:0,implicit:!0})],so.prototype,"targetName",void 0);f([y({type:ie,context:1,implicit:!0})],so.prototype,"targetGroup",void 0);f([y({type:rc,context:2,implicit:!0})],so.prototype,"targetCert",void 0);so=f([j({type:R.Choice})],so);let Xu=Yu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Yu.prototype)}};Xu=Yu=f([j({type:R.Sequence,itemType:so})],Xu);var Ju;let rh=Ju=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Ju.prototype)}};rh=Ju=f([j({type:R.Sequence,itemType:Xu})],rh);class Uv{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}}f([y({type:Ye,implicit:!0,context:0,optional:!0})],Uv.prototype,"roleAuthority",void 0);f([y({type:ie,implicit:!0,context:1})],Uv.prototype,"roleName",void 0);class Kd{service=new ie;ident=new ie;authInfo;constructor(e={}){Object.assign(this,e)}}f([y({type:ie})],Kd.prototype,"service",void 0);f([y({type:ie})],Kd.prototype,"ident",void 0);f([y({type:he,optional:!0})],Kd.prototype,"authInfo",void 0);var Zu;class Gd{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Gd.prototype,"otherCertFormat",void 0);f([y({type:b.Any})],Gd.prototype,"otherCert",void 0);let io=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};f([y({type:yn})],io.prototype,"certificate",void 0);f([y({type:ec,context:2,implicit:!0})],io.prototype,"v2AttrCert",void 0);f([y({type:Gd,context:3,implicit:!0})],io.prototype,"other",void 0);io=f([j({type:R.Choice})],io);let Ki=Zu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Zu.prototype)}};Ki=Zu=f([j({type:R.Set,itemType:io})],Ki);class wo{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],wo.prototype,"contentType",void 0);f([y({type:b.Any,context:0})],wo.prototype,"content",void 0);let ws=class{single;any;constructor(e={}){Object.assign(this,e)}};f([y({type:he})],ws.prototype,"single",void 0);f([y({type:b.Any})],ws.prototype,"any",void 0);ws=f([j({type:R.Choice})],ws);class nc{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],nc.prototype,"eContentType",void 0);f([y({type:ws,context:0,optional:!0})],nc.prototype,"eContent",void 0);let As=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};f([y({type:he,context:0,implicit:!0,optional:!0})],As.prototype,"value",void 0);f([y({type:he,converter:HE,context:0,implicit:!0,optional:!0,repeated:"sequence"})],As.prototype,"constructedValue",void 0);As=f([j({type:R.Choice})],As);class Us{contentType="";contentEncryptionAlgorithm=new Vi;encryptedContent;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Us.prototype,"contentType",void 0);f([y({type:Vi})],Us.prototype,"contentEncryptionAlgorithm",void 0);f([y({type:As,optional:!0})],Us.prototype,"encryptedContent",void 0);class oc{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],oc.prototype,"keyAttrId",void 0);f([y({type:b.Any,optional:!0})],oc.prototype,"keyAttr",void 0);var Qu;class sc{subjectKeyIdentifier=new Mr;date;other;constructor(e={}){Object.assign(this,e)}}f([y({type:Mr})],sc.prototype,"subjectKeyIdentifier",void 0);f([y({type:b.GeneralizedTime,optional:!0})],sc.prototype,"date",void 0);f([y({type:oc,optional:!0})],sc.prototype,"other",void 0);let ao=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([y({type:sc,context:0,implicit:!0,optional:!0})],ao.prototype,"rKeyId",void 0);f([y({type:vo,optional:!0})],ao.prototype,"issuerAndSerialNumber",void 0);ao=f([j({type:R.Choice})],ao);class qd{rid=new ao;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:ao})],qd.prototype,"rid",void 0);f([y({type:he})],qd.prototype,"encryptedKey",void 0);let Gi=Qu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Qu.prototype)}};Gi=Qu=f([j({type:R.Sequence,itemType:qd})],Gi);class zd{algorithm=new W;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:W})],zd.prototype,"algorithm",void 0);f([y({type:b.BitString})],zd.prototype,"publicKey",void 0);let gn=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([y({type:Mr,context:0,implicit:!0,optional:!0})],gn.prototype,"subjectKeyIdentifier",void 0);f([y({type:zd,context:1,implicit:!0,optional:!0})],gn.prototype,"originatorKey",void 0);f([y({type:vo,optional:!0})],gn.prototype,"issuerAndSerialNumber",void 0);gn=f([j({type:R.Choice})],gn);class Ao{version=vr.v3;originator=new gn;ukm;keyEncryptionAlgorithm=new Qt;recipientEncryptedKeys=new Gi;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Ao.prototype,"version",void 0);f([y({type:gn,context:0})],Ao.prototype,"originator",void 0);f([y({type:he,context:1,optional:!0})],Ao.prototype,"ukm",void 0);f([y({type:Qt})],Ao.prototype,"keyEncryptionAlgorithm",void 0);f([y({type:Gi})],Ao.prototype,"recipientEncryptedKeys",void 0);let co=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([y({type:Mr,context:0,implicit:!0})],co.prototype,"subjectKeyIdentifier",void 0);f([y({type:vo})],co.prototype,"issuerAndSerialNumber",void 0);co=f([j({type:R.Choice})],co);class Vs{version=vr.v0;rid=new co;keyEncryptionAlgorithm=new Qt;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Vs.prototype,"version",void 0);f([y({type:co})],Vs.prototype,"rid",void 0);f([y({type:Qt})],Vs.prototype,"keyEncryptionAlgorithm",void 0);f([y({type:he})],Vs.prototype,"encryptedKey",void 0);class Hs{keyIdentifier=new he;date;other;constructor(e={}){Object.assign(this,e)}}f([y({type:he})],Hs.prototype,"keyIdentifier",void 0);f([y({type:b.GeneralizedTime,optional:!0})],Hs.prototype,"date",void 0);f([y({type:oc,optional:!0})],Hs.prototype,"other",void 0);class Fs{version=vr.v4;kekid=new Hs;keyEncryptionAlgorithm=new Qt;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Fs.prototype,"version",void 0);f([y({type:Hs})],Fs.prototype,"kekid",void 0);f([y({type:Qt})],Fs.prototype,"keyEncryptionAlgorithm",void 0);f([y({type:he})],Fs.prototype,"encryptedKey",void 0);class Ws{version=vr.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new Qt;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Ws.prototype,"version",void 0);f([y({type:Fu,context:0,optional:!0})],Ws.prototype,"keyDerivationAlgorithm",void 0);f([y({type:Qt})],Ws.prototype,"keyEncryptionAlgorithm",void 0);f([y({type:he})],Ws.prototype,"encryptedKey",void 0);class Yd{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Yd.prototype,"oriType",void 0);f([y({type:b.Any})],Yd.prototype,"oriValue",void 0);let Lr=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};f([y({type:Vs,optional:!0})],Lr.prototype,"ktri",void 0);f([y({type:Ao,context:1,implicit:!0,optional:!0})],Lr.prototype,"kari",void 0);f([y({type:Fs,context:2,implicit:!0,optional:!0})],Lr.prototype,"kekri",void 0);f([y({type:Ws,context:3,implicit:!0,optional:!0})],Lr.prototype,"pwri",void 0);f([y({type:Yd,context:4,implicit:!0,optional:!0})],Lr.prototype,"ori",void 0);Lr=f([j({type:R.Choice})],Lr);var el;let qi=el=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,el.prototype)}};qi=el=f([j({type:R.Set,itemType:Lr})],qi);var tl;class ic{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],ic.prototype,"otherRevInfoFormat",void 0);f([y({type:b.Any})],ic.prototype,"otherRevInfo",void 0);let zi=class{other=new ic;constructor(e={}){Object.assign(this,e)}};f([y({type:ic,context:1,implicit:!0})],zi.prototype,"other",void 0);zi=f([j({type:R.Choice})],zi);let Yi=tl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,tl.prototype)}};Yi=tl=f([j({type:R.Set,itemType:zi})],Yi);class Xd{certs;crls;constructor(e={}){Object.assign(this,e)}}f([y({type:Ki,context:0,implicit:!0,optional:!0})],Xd.prototype,"certs",void 0);f([y({type:Yi,context:1,implicit:!0,optional:!0})],Xd.prototype,"crls",void 0);var rl;let nl=rl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,rl.prototype)}};nl=rl=f([j({type:R.Set,itemType:bo})],nl);class Ks{version=vr.v0;originatorInfo;recipientInfos=new qi;encryptedContentInfo=new Us;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Ks.prototype,"version",void 0);f([y({type:Xd,context:0,implicit:!0,optional:!0})],Ks.prototype,"originatorInfo",void 0);f([y({type:qi})],Ks.prototype,"recipientInfos",void 0);f([y({type:Us})],Ks.prototype,"encryptedContentInfo",void 0);f([y({type:nl,context:1,implicit:!0,optional:!0})],Ks.prototype,"unprotectedAttrs",void 0);const hx="1.2.840.113549.1.7.2";var ol;let Xi=ol=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,ol.prototype)}};Xi=ol=f([j({type:R.Set,itemType:bs})],Xi);class So{version=vr.v0;digestAlgorithms=new Xi;encapContentInfo=new nc;certificates;crls;signerInfos=new Hi;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],So.prototype,"version",void 0);f([y({type:Xi})],So.prototype,"digestAlgorithms",void 0);f([y({type:nc})],So.prototype,"encapContentInfo",void 0);f([y({type:Ki,context:0,implicit:!0,optional:!0})],So.prototype,"certificates",void 0);f([y({type:Yi,context:1,implicit:!0,optional:!0})],So.prototype,"crls",void 0);f([y({type:Hi})],So.prototype,"signerInfos",void 0);const Ss="1.2.840.10045.2.1",Jd="1.2.840.10045.4.1",Vv="1.2.840.10045.4.3.1",Zd="1.2.840.10045.4.3.2",Qd="1.2.840.10045.4.3.3",ef="1.2.840.10045.4.3.4",nh="1.2.840.10045.3.1.7",oh="1.3.132.0.34",sh="1.3.132.0.35";function Gs(t){return new W({algorithm:t})}const mx=Gs(Jd);Gs(Vv);const yx=Gs(Zd),gx=Gs(Qd),vx=Gs(ef);let ks=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};f([y({type:b.ObjectIdentifier})],ks.prototype,"fieldType",void 0);f([y({type:b.Any})],ks.prototype,"parameters",void 0);ks=f([j({type:R.Sequence})],ks);class bx extends he{}let uo=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};f([y({type:b.OctetString})],uo.prototype,"a",void 0);f([y({type:b.OctetString})],uo.prototype,"b",void 0);f([y({type:b.BitString,optional:!0})],uo.prototype,"seed",void 0);uo=f([j({type:R.Sequence})],uo);var sl;(function(t){t[t.ecpVer1=1]="ecpVer1"})(sl||(sl={}));let br=class{version=sl.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};f([y({type:b.Integer})],br.prototype,"version",void 0);f([y({type:ks})],br.prototype,"fieldID",void 0);f([y({type:uo})],br.prototype,"curve",void 0);f([y({type:bx})],br.prototype,"base",void 0);f([y({type:b.Integer,converter:xe})],br.prototype,"order",void 0);f([y({type:b.Integer,optional:!0})],br.prototype,"cofactor",void 0);br=f([j({type:R.Sequence})],br);let Pr=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};f([y({type:b.ObjectIdentifier})],Pr.prototype,"namedCurve",void 0);f([y({type:b.Null})],Pr.prototype,"implicitCurve",void 0);f([y({type:br})],Pr.prototype,"specifiedCurve",void 0);Pr=f([j({type:R.Choice})],Pr);class ac{version=1;privateKey=new he;parameters;publicKey;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],ac.prototype,"version",void 0);f([y({type:he})],ac.prototype,"privateKey",void 0);f([y({type:Pr,context:0,optional:!0})],ac.prototype,"parameters",void 0);f([y({type:b.BitString,context:1,optional:!0})],ac.prototype,"publicKey",void 0);class Ji{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,converter:xe})],Ji.prototype,"r",void 0);f([y({type:b.Integer,converter:xe})],Ji.prototype,"s",void 0);const ut="1.2.840.113549.1.1",vn=`${ut}.1`,wx=`${ut}.7`,Ax=`${ut}.9`,ss=`${ut}.10`,Sx=`${ut}.2`,kx=`${ut}.4`,Zi=`${ut}.5`,Ex=`${ut}.14`,il=`${ut}.11`,Qi=`${ut}.12`,ea=`${ut}.13`,Hv=`${ut}.15`,Fv=`${ut}.16`,ta="1.3.14.3.2.26",Wv="2.16.840.1.101.3.4.2.4",ra="2.16.840.1.101.3.4.2.1",na="2.16.840.1.101.3.4.2.2",oa="2.16.840.1.101.3.4.2.3",xx="2.16.840.1.101.3.4.2.5",Ix="2.16.840.1.101.3.4.2.6",Ox="1.2.840.113549.2.2",Cx="1.2.840.113549.2.5",cc=`${ut}.8`;function Pe(t){return new W({algorithm:t,parameters:null})}Pe(Ox);Pe(Cx);const bn=Pe(ta);Pe(Wv);Pe(ra);Pe(na);Pe(oa);Pe(xx);Pe(Ix);const Kv=new W({algorithm:cc,parameters:H.serialize(bn)}),Gv=new W({algorithm:Ax,parameters:H.serialize(Ri.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});Pe(vn);Pe(Sx);Pe(kx);Pe(Zi);Pe(Hv);Pe(Fv);Pe(Qi);Pe(ea);Pe(Hv);Pe(Fv);class uc{hashAlgorithm=new W(bn);maskGenAlgorithm=new W({algorithm:cc,parameters:H.serialize(bn)});pSourceAlgorithm=new W(Gv);constructor(e={}){Object.assign(this,e)}}f([y({type:W,context:0,defaultValue:bn})],uc.prototype,"hashAlgorithm",void 0);f([y({type:W,context:1,defaultValue:Kv})],uc.prototype,"maskGenAlgorithm",void 0);f([y({type:W,context:2,defaultValue:Gv})],uc.prototype,"pSourceAlgorithm",void 0);new W({algorithm:wx,parameters:H.serialize(new uc)});class wn{hashAlgorithm=new W(bn);maskGenAlgorithm=new W({algorithm:cc,parameters:H.serialize(bn)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}}f([y({type:W,context:0,defaultValue:bn})],wn.prototype,"hashAlgorithm",void 0);f([y({type:W,context:1,defaultValue:Kv})],wn.prototype,"maskGenAlgorithm",void 0);f([y({type:b.Integer,context:2,defaultValue:20})],wn.prototype,"saltLength",void 0);f([y({type:b.Integer,context:3,defaultValue:1})],wn.prototype,"trailerField",void 0);new W({algorithm:ss,parameters:H.serialize(new wn)});class lc{digestAlgorithm=new W;digest=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:W})],lc.prototype,"digestAlgorithm",void 0);f([y({type:he})],lc.prototype,"digest",void 0);var al;class dc{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,converter:xe})],dc.prototype,"prime",void 0);f([y({type:b.Integer,converter:xe})],dc.prototype,"exponent",void 0);f([y({type:b.Integer,converter:xe})],dc.prototype,"coefficient",void 0);let cl=al=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,al.prototype)}};cl=al=f([j({type:R.Sequence,itemType:dc})],cl);class ir{version=0;modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);privateExponent=new ArrayBuffer(0);prime1=new ArrayBuffer(0);prime2=new ArrayBuffer(0);exponent1=new ArrayBuffer(0);exponent2=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);otherPrimeInfos;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],ir.prototype,"version",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"modulus",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"publicExponent",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"privateExponent",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"prime1",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"prime2",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"exponent1",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"exponent2",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"coefficient",void 0);f([y({type:cl,optional:!0})],ir.prototype,"otherPrimeInfos",void 0);class tf{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,converter:xe})],tf.prototype,"modulus",void 0);f([y({type:b.Integer,converter:xe})],tf.prototype,"publicExponent",void 0);var ul;(function(t){t[t.Transient=0]="Transient",t[t.Singleton=1]="Singleton",t[t.ResolutionScoped=2]="ResolutionScoped",t[t.ContainerScoped=3]="ContainerScoped"})(ul||(ul={}));const nt=ul;var ll=function(t,e){return ll=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)n.hasOwnProperty(o)&&(r[o]=n[o])},ll(t,e)};function rf(t,e){ll(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Nx(t,e,r,n){function o(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function a(d){try{u(n.next(d))}catch(l){i(l)}}function c(d){try{u(n.throw(d))}catch(l){i(l)}}function u(d){d.done?s(d.value):o(d.value).then(a,c)}u((n=n.apply(t,[])).next())})}function Tx(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i;return i={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(u){return function(d){return c([u,d])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,o=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(d){u=[6,d],o=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function oi(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function sa(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s}function Zr(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(sa(arguments[e]));return t}var $x="injectionTokens";function Bx(t){var e=Reflect.getMetadata("design:paramtypes",t)||[],r=Reflect.getOwnMetadata($x,t)||{};return Object.keys(r).forEach(function(n){e[+n]=r[n]}),e}function qv(t){return!!t.useClass}function dl(t){return!!t.useFactory}var zv=(function(){function t(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return t.prototype.createProxy=function(e){var r=this,n={},o=!1,s,i=function(){return o||(s=e(r.wrap()),o=!0),s};return new Proxy(n,this.createHandler(i))},t.prototype.createHandler=function(e){var r={},n=function(o){r[o]=function(){for(var s=[],i=0;i<arguments.length;i++)s[i]=arguments[i];s[0]=e();var a=Reflect[o];return a.apply(void 0,Zr(s))}};return this.reflectMethods.forEach(n),r},t})();function Mn(t){return typeof t=="string"||typeof t=="symbol"}function Rx(t){return typeof t=="object"&&"token"in t&&"multiple"in t}function ih(t){return typeof t=="object"&&"token"in t&&"transform"in t}function Mx(t){return typeof t=="function"||t instanceof zv}function hi(t){return!!t.useToken}function mi(t){return t.useValue!=null}function _x(t){return qv(t)||mi(t)||hi(t)||dl(t)}var nf=(function(){function t(){this._registryMap=new Map}return t.prototype.entries=function(){return this._registryMap.entries()},t.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},t.prototype.get=function(e){this.ensure(e);var r=this._registryMap.get(e);return r[r.length-1]||null},t.prototype.set=function(e,r){this.ensure(e),this._registryMap.get(e).push(r)},t.prototype.setAll=function(e,r){this._registryMap.set(e,r)},t.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},t.prototype.clear=function(){this._registryMap.clear()},t.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},t})(),jx=(function(t){rf(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(nf),si=(function(){function t(){this.scopedResolutions=new Map}return t})();function Dx(t,e){if(t===null)return"at position #"+e;var r=t.split(",")[e].trim();return'"'+r+'" at position #'+e}function Lx(t,e,r){return r===void 0&&(r=" "),Zr([t],e.message.split(`
98
116
  `).map(function(n){return r+n})).join(`
99
- `)}function wE(t,e,r){var n=Gi(t.toString().match(/constructor\(([\w, ]+)\)/)||[],2),s=n[1],o=s===void 0?null:s,i=vE(o,e);return bE("Cannot inject the dependency "+i+' of "'+t.name+'" constructor. Reason:',r)}function AE(t){if(typeof t.dispose!="function")return!1;var e=t.dispose;return!(e.length>0)}var SE=(function(t){Rd(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(_d),kE=(function(t){Rd(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(_d),xE=(function(){function t(){this.preResolution=new SE,this.postResolution=new kE}return t})(),hv=new Map,EE=(function(){function t(e){this.parent=e,this._registry=new gE,this.interceptors=new xE,this.disposed=!1,this.disposables=new Set}return t.prototype.register=function(e,r,n){n===void 0&&(n={lifecycle:Xe.Transient}),this.ensureNotDisposed();var s;if(yE(r)?s=r:s={useClass:r},ri(s))for(var o=[e],i=s;i!=null;){var a=i.useToken;if(o.includes(a))throw new Error("Token registration cycle detected! "+Fr(o,[a]).join(" -> "));o.push(a);var c=this._registry.get(a);c&&ri(c.provider)?i=c.provider:i=null}if((n.lifecycle===Xe.Singleton||n.lifecycle==Xe.ContainerScoped||n.lifecycle==Xe.ResolutionScoped)&&(ni(s)||Gu(s)))throw new Error('Cannot use lifecycle "'+Xe[n.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:s,options:n}),this},t.prototype.registerType=function(e,r){return this.ensureNotDisposed(),Sn(r)?this.register(e,{useToken:r}):this.register(e,{useClass:r})},t.prototype.registerInstance=function(e,r){return this.ensureNotDisposed(),this.register(e,{useValue:r})},t.prototype.registerSingleton=function(e,r){if(this.ensureNotDisposed(),Sn(e)){if(Sn(r))return this.register(e,{useToken:r},{lifecycle:Xe.Singleton});if(r)return this.register(e,{useClass:r},{lifecycle:Xe.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var n=e;return r&&!Sn(r)&&(n=r),this.register(e,{useClass:n},{lifecycle:Xe.Singleton})},t.prototype.resolve=function(e,r,n){r===void 0&&(r=new qo),n===void 0&&(n=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&Sn(e)){if(n)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),s){var o=this.resolveRegistration(s,r);return this.executePostResolutionInterceptor(e,o,"Single"),o}if(mE(e)){var o=this.construct(e,r);return this.executePostResolutionInterceptor(e,o,"Single"),o}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},t.prototype.executePreResolutionInterceptor=function(e,r){var n,s;if(this.interceptors.preResolution.has(e)){var o=[];try{for(var i=Go(this.interceptors.preResolution.getAll(e)),a=i.next();!a.done;a=i.next()){var c=a.value;c.options.frequency!="Once"&&o.push(c),c.callback(e,r)}}catch(u){n={error:u}}finally{try{a&&!a.done&&(s=i.return)&&s.call(i)}finally{if(n)throw n.error}}this.interceptors.preResolution.setAll(e,o)}},t.prototype.executePostResolutionInterceptor=function(e,r,n){var s,o;if(this.interceptors.postResolution.has(e)){var i=[];try{for(var a=Go(this.interceptors.postResolution.getAll(e)),c=a.next();!c.done;c=a.next()){var u=c.value;u.options.frequency!="Once"&&i.push(u),u.callback(e,r,n)}}catch(l){s={error:l}}finally{try{c&&!c.done&&(o=a.return)&&o.call(a)}finally{if(s)throw s.error}}this.interceptors.postResolution.setAll(e,i)}},t.prototype.resolveRegistration=function(e,r){if(this.ensureNotDisposed(),e.options.lifecycle===Xe.ResolutionScoped&&r.scopedResolutions.has(e))return r.scopedResolutions.get(e);var n=e.options.lifecycle===Xe.Singleton,s=e.options.lifecycle===Xe.ContainerScoped,o=n||s,i;return ni(e.provider)?i=e.provider.useValue:ri(e.provider)?i=o?e.instance||(e.instance=this.resolve(e.provider.useToken,r)):this.resolve(e.provider.useToken,r):fv(e.provider)?i=o?e.instance||(e.instance=this.construct(e.provider.useClass,r)):this.construct(e.provider.useClass,r):Gu(e.provider)?i=e.provider.useFactory(this):i=this.construct(e.provider,r),e.options.lifecycle===Xe.ResolutionScoped&&r.scopedResolutions.set(e,i),i},t.prototype.resolveAll=function(e,r,n){var s=this;r===void 0&&(r=new qo),n===void 0&&(n=!1),this.ensureNotDisposed();var o=this.getAllRegistrations(e);if(!o&&Sn(e)){if(n)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),o){var i=o.map(function(c){return s.resolveRegistration(c,r)});return this.executePostResolutionInterceptor(e,i,"All"),i}var a=[this.construct(e,r)];return this.executePostResolutionInterceptor(e,a,"All"),a},t.prototype.isRegistered=function(e,r){return r===void 0&&(r=!1),this.ensureNotDisposed(),this._registry.has(e)||r&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},t.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},t.prototype.clearInstances=function(){var e,r;this.ensureNotDisposed();try{for(var n=Go(this._registry.entries()),s=n.next();!s.done;s=n.next()){var o=Gi(s.value,2),i=o[0],a=o[1];this._registry.setAll(i,a.filter(function(c){return!ni(c.provider)}).map(function(c){return c.instance=void 0,c}))}}catch(c){e={error:c}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}},t.prototype.createChildContainer=function(){var e,r;this.ensureNotDisposed();var n=new t(this);try{for(var s=Go(this._registry.entries()),o=s.next();!o.done;o=s.next()){var i=Gi(o.value,2),a=i[0],c=i[1];c.some(function(u){var l=u.options;return l.lifecycle===Xe.ContainerScoped})&&n._registry.setAll(a,c.map(function(u){return u.options.lifecycle===Xe.ContainerScoped?{provider:u.provider,options:u.options}:u}))}}catch(u){e={error:u}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.error}}return n},t.prototype.beforeResolution=function(e,r,n){n===void 0&&(n={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:r,options:n})},t.prototype.afterResolution=function(e,r,n){n===void 0&&(n={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:r,options:n})},t.prototype.dispose=function(){return lE(this,void 0,void 0,function(){var e;return dE(this,function(r){switch(r.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(n){var s=n.dispose();s&&e.push(s)}),[4,Promise.all(e)];case 1:return r.sent(),[2]}})})},t.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},t.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},t.prototype.construct=function(e,r){var n=this;if(e instanceof pv)return e.createProxy(function(o){return n.resolve(o,r)});var s=(function(){var o=hv.get(e);if(!o||o.length===0){if(e.length===0)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var i=o.map(n.resolveParams(r,e));return new(e.bind.apply(e,Fr([void 0],i)))})();return AE(s)&&this.disposables.add(s),s},t.prototype.resolveParams=function(e,r){var n=this;return function(s,o){var i,a,c;try{return hE(s)?Mp(s)?s.multiple?(i=n.resolve(s.transform)).transform.apply(i,Fr([n.resolveAll(s.token,new qo,s.isOptional)],s.transformArgs)):(a=n.resolve(s.transform)).transform.apply(a,Fr([n.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?n.resolveAll(s.token,new qo,s.isOptional):n.resolve(s.token,e,s.isOptional):Mp(s)?(c=n.resolve(s.transform,e)).transform.apply(c,Fr([n.resolve(s.token,e)],s.transformArgs)):n.resolve(s,e)}catch(u){throw new Error(wE(r,o,u))}}},t.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},t})(),Te=new EE;function us(t){return function(e){hv.set(e,pE(e))}}if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var qu;class Za{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}}f([h({type:b.ObjectIdentifier})],Za.prototype,"attrId",void 0);f([h({type:b.Any,repeated:"set"})],Za.prototype,"attrValues",void 0);let jp=qu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,qu.prototype)}};jp=qu=f([$({type:O.Sequence,itemType:Za})],jp);var zu;let Dp=zu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,zu.prototype)}};Dp=zu=f([$({type:O.Sequence,itemType:is})],Dp);class mv{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],mv.prototype,"certId",void 0);f([h({type:b.Any,context:0})],mv.prototype,"certValue",void 0);class yv{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],yv.prototype,"crlId",void 0);f([h({type:b.Any,context:0})],yv.prototype,"crltValue",void 0);class gv extends ue{}let Qa=class{encryptionAlgorithm=new L;encryptedData=new gv;constructor(e={}){Object.assign(this,e)}};f([h({type:L})],Qa.prototype,"encryptionAlgorithm",void 0);f([h({type:gv})],Qa.prototype,"encryptedData",void 0);var Yu,Xu;(function(t){t[t.v1=0]="v1"})(Xu||(Xu={}));class vv extends ue{}let qi=Yu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Yu.prototype)}};qi=Yu=f([$({type:O.Sequence,itemType:fr})],qi);let $o=class{version=Xu.v1;privateKeyAlgorithm=new L;privateKey=new vv;attributes;constructor(e={}){Object.assign(this,e)}};f([h({type:b.Integer})],$o.prototype,"version",void 0);f([h({type:L})],$o.prototype,"privateKeyAlgorithm",void 0);f([h({type:vv})],$o.prototype,"privateKey",void 0);f([h({type:qi,implicit:!0,context:0,optional:!0})],$o.prototype,"attributes",void 0);let Pp=class extends $o{};Pp=f([$({type:O.Sequence})],Pp);let Lp=class extends Qa{};Lp=f([$({type:O.Sequence})],Lp);class bv{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],bv.prototype,"secretTypeId",void 0);f([h({type:b.Any,context:0})],bv.prototype,"secretValue",void 0);class Ro{mac=new Xa;macSalt=new ue;iterations=1;constructor(e={}){Object.assign(this,e)}}f([h({type:Xa})],Ro.prototype,"mac",void 0);f([h({type:ue})],Ro.prototype,"macSalt",void 0);f([h({type:b.Integer,defaultValue:1})],Ro.prototype,"iterations",void 0);class ec{version=3;authSafe=new is;macData=new Ro;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],ec.prototype,"version",void 0);f([h({type:is})],ec.prototype,"authSafe",void 0);f([h({type:Ro,optional:!0})],ec.prototype,"macData",void 0);var Ju;class tc{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],tc.prototype,"bagId",void 0);f([h({type:b.Any,context:0})],tc.prototype,"bagValue",void 0);f([h({type:Za,repeated:"set",optional:!0})],tc.prototype,"bagAttributes",void 0);let Up=Ju=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Ju.prototype)}};Up=Ju=f([$({type:O.Sequence,itemType:tc})],Up);var Zu,Qu,el;const wv="1.2.840.113549.1.9",Av=`${wv}.7`,Md=`${wv}.14`;let zi=class extends Ve{ia5String;constructor(e={}){super(e)}toString(){return this.ia5String||super.toString()}};f([h({type:b.IA5String})],zi.prototype,"ia5String",void 0);zi=f([$({type:O.Choice})],zi);let Vp=class extends is{};Vp=f([$({type:O.Sequence})],Vp);let Hp=class extends ec{};Hp=f([$({type:O.Sequence})],Hp);let Fp=class extends Qa{};Fp=f([$({type:O.Sequence})],Fp);let tl=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([h({type:b.IA5String})],tl.prototype,"value",void 0);tl=f([$({type:O.Choice})],tl);let Wp=class extends zi{};Wp=f([$({type:O.Choice})],Wp);let Kp=class extends Ve{};Kp=f([$({type:O.Choice})],Kp);let rl=class{value;constructor(e=new Date){this.value=e}};f([h({type:b.GeneralizedTime})],rl.prototype,"value",void 0);rl=f([$({type:O.Choice})],rl);let Gp=class extends Ve{};Gp=f([$({type:O.Choice})],Gp);let nl=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};f([h({type:b.PrintableString})],nl.prototype,"value",void 0);nl=f([$({type:O.Choice})],nl);let Yi=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([h({type:b.PrintableString})],Yi.prototype,"value",void 0);Yi=f([$({type:O.Choice})],Yi);let qp=class extends Yi{};qp=f([$({type:O.Choice})],qp);let zp=class extends Ve{};zp=f([$({type:O.Choice})],zp);let sl=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([h({type:b.ObjectIdentifier})],sl.prototype,"value",void 0);sl=f([$({type:O.Choice})],sl);let Yp=class extends Le{};Yp=f([$({type:O.Choice})],Yp);let ol=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};f([h({type:b.Integer})],ol.prototype,"value",void 0);ol=f([$({type:O.Choice})],ol);let Xp=class extends Jt{};Xp=f([$({type:O.Sequence})],Xp);let Xi=class extends Ve{};Xi=f([$({type:O.Choice})],Xi);let Jp=Zu=class extends Tr{constructor(e){super(e),Object.setPrototypeOf(this,Zu.prototype)}};Jp=Zu=f([$({type:O.Sequence})],Jp);let Zp=Qu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Qu.prototype)}};Zp=Qu=f([$({type:O.Set,itemType:os})],Zp);let il=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([h({type:b.BmpString})],il.prototype,"value",void 0);il=f([$({type:O.Choice})],il);let al=class extends L{};al=f([$({type:O.Sequence})],al);let Qp=el=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,el.prototype)}};Qp=el=f([$({type:O.Sequence,itemType:al})],Qp);var cl,ul;let eh=cl=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,cl.prototype)}};eh=cl=f([$({type:O.Sequence,itemType:L})],eh);let th=ul=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,ul.prototype)}};th=ul=f([$({type:O.Sequence,itemType:b.BitString})],th);var ll,dl;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2"})(dl||(dl={}));let rh=class extends L{};rh=f([$({type:O.Sequence})],rh);let Gt=class{version=dl.v1;privateKeyAlgorithm=new L;privateKey=new ArrayBuffer(0);attributes;publicKey};f([h({type:b.Integer})],Gt.prototype,"version",void 0);f([h({type:L})],Gt.prototype,"privateKeyAlgorithm",void 0);f([h({type:b.OctetString})],Gt.prototype,"privateKey",void 0);f([h({type:qi,context:0,implicit:!0,optional:!0})],Gt.prototype,"attributes",void 0);f([h({type:b.BitString,context:1,implicit:!0,optional:!0})],Gt.prototype,"publicKey",void 0);Gt=f([$({type:O.Sequence})],Gt);let nh=class extends Gt{};nh=f([$({type:O.Sequence})],nh);let sh=ll=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,ll.prototype)}};sh=ll=f([$({type:O.Sequence,itemType:Gt})],sh);var fl,pl;let oh=class extends L{};oh=f([$({type:O.Sequence})],oh);let ih=fl=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,fl.prototype)}};ih=fl=f([$({type:O.Sequence,itemType:bt})],ih);let ah=pl=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,pl.prototype)}};ah=pl=f([$({type:O.Sequence,itemType:Gt})],ah);const Ye="2.16.840.1.101.3.4.3",ch=`${Ye}.17`,uh=`${Ye}.18`,lh=`${Ye}.19`,dh=`${Ye}.20`,fh=`${Ye}.21`,ph=`${Ye}.22`,hh=`${Ye}.23`,mh=`${Ye}.24`,yh=`${Ye}.25`,gh=`${Ye}.26`,vh=`${Ye}.27`,bh=`${Ye}.28`,wh=`${Ye}.29`,Ah=`${Ye}.30`,Sh=`${Ye}.31`;var hl;let Ji=hl=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,hl.prototype)}};Ji=hl=f([$({type:O.Sequence,itemType:fr})],Ji);class ls{version=0;subject=new Ie;subjectPKInfo=new bt;attributes=new Ji;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],ls.prototype,"version",void 0);f([h({type:Ie})],ls.prototype,"subject",void 0);f([h({type:bt})],ls.prototype,"subjectPKInfo",void 0);f([h({type:Ji,implicit:!0,context:0,optional:!0})],ls.prototype,"attributes",void 0);class co{certificationRequestInfo=new ls;certificationRequestInfoRaw;signatureAlgorithm=new L;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:ls,raw:!0})],co.prototype,"certificationRequestInfo",void 0);f([h({type:L})],co.prototype,"signatureAlgorithm",void 0);f([h({type:b.BitString})],co.prototype,"signature",void 0);const bn="crypto.algorithm";class IE{getAlgorithms(){return Te.resolveAll(bn)}toAsnAlgorithm(e){const r={...e};r.hash&&typeof r.hash=="string"&&(r.hash={name:r.hash});for(const n of this.getAlgorithms()){const s=n.toAsnAlgorithm(r);if(s)return s}if(/^[0-9.]+$/.test(e.name)){const n=new L({algorithm:e.name});if("parameters"in e){const s=e;n.parameters=s.parameters}return n}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(const n of this.getAlgorithms()){const s=n.toWebAlgorithm(e);if(s)return s}return{name:e.algorithm,parameters:e.parameters}}}const ln="crypto.algorithmProvider";Te.registerSingleton(ln,IE);var si;const st="1.3.36.3.3.2.8.1.1",kh=`${st}.1`,xh=`${st}.2`,Eh=`${st}.3`,Ih=`${st}.4`,Ch=`${st}.5`,Oh=`${st}.6`,Nh=`${st}.7`,Th=`${st}.8`,Bh=`${st}.9`,$h=`${st}.10`,Rh=`${st}.11`,_h=`${st}.12`,Mh=`${st}.13`,jh=`${st}.14`,Dh="brainpoolP160r1",Ph="brainpoolP160t1",Lh="brainpoolP192r1",Uh="brainpoolP192t1",Vh="brainpoolP224r1",Hh="brainpoolP224t1",Fh="brainpoolP256r1",Wh="brainpoolP256t1",Kh="brainpoolP320r1",Gh="brainpoolP320t1",qh="brainpoolP384r1",zh="brainpoolP384t1",Yh="brainpoolP512r1",Xh="brainpoolP512t1",we="ECDSA";let uo=si=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case we.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return Xx;case"sha-256":return Jx;case"sha-384":return Zx;case"sha-512":return Qx}else if("namedCurve"in e){let r="";switch(e.namedCurve){case"P-256":r=$p;break;case"K-256":r=si.SECP256K1;break;case"P-384":r=Rp;break;case"P-521":r=_p;break;case Dh:r=kh;break;case Ph:r=xh;break;case Lh:r=Eh;break;case Uh:r=Ih;break;case Vh:r=Ch;break;case Hh:r=Oh;break;case Fh:r=Nh;break;case Wh:r=Th;break;case Kh:r=Bh;break;case Gh:r=$h;break;case qh:r=Rh;break;case zh:r=_h;break;case Yh:r=Mh;break;case Xh:r=jh;break}if(r)return new L({algorithm:io,parameters:D.serialize(new $r({namedCurve:r}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case Od:return{name:we,hash:{name:"SHA-1"}};case Nd:return{name:we,hash:{name:"SHA-256"}};case Td:return{name:we,hash:{name:"SHA-384"}};case Bd:return{name:we,hash:{name:"SHA-512"}};case io:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(D.parse(e.parameters,$r).namedCurve){case $p:return{name:we,namedCurve:"P-256"};case si.SECP256K1:return{name:we,namedCurve:"K-256"};case Rp:return{name:we,namedCurve:"P-384"};case _p:return{name:we,namedCurve:"P-521"};case kh:return{name:we,namedCurve:Dh};case xh:return{name:we,namedCurve:Ph};case Eh:return{name:we,namedCurve:Lh};case Ih:return{name:we,namedCurve:Uh};case Ch:return{name:we,namedCurve:Vh};case Oh:return{name:we,namedCurve:Hh};case Nh:return{name:we,namedCurve:Fh};case Th:return{name:we,namedCurve:Wh};case Bh:return{name:we,namedCurve:Kh};case $h:return{name:we,namedCurve:Gh};case Rh:return{name:we,namedCurve:qh};case _h:return{name:we,namedCurve:zh};case Mh:return{name:we,namedCurve:Yh};case jh:return{name:we,namedCurve:Xh}}}}return null}};uo.SECP256K1="1.3.132.0.10";uo=si=f([us()],uo);Te.registerSingleton(bn,uo);const Sv=Symbol("name"),kv=Symbol("value");class de{constructor(e,r={},n=""){this[Sv]=e,this[kv]=n;for(const s in r)this[s]=r[s]}}de.NAME=Sv;de.VALUE=kv;class CE{static toTextObject(e){const r=new de("Algorithm Identifier",{},Dr.toString(e.algorithm));if(e.parameters)if(e.algorithm===io){const n=new uo().toWebAlgorithm(e);n&&"namedCurve"in n?r["Named Curve"]=n.namedCurve:r.Parameters=e.parameters}else r.Parameters=e.parameters;return r}}class Dr{static toString(e){const r=this.items[e];return r||e}}Dr.items={[Hi]:"sha1",[uv]:"sha224",[Fi]:"sha256",[Wi]:"sha384",[Ki]:"sha512",[an]:"rsaEncryption",[Li]:"sha1WithRSAEncryption",[oE]:"sha224WithRSAEncryption",[Vu]:"sha256WithRSAEncryption",[Ui]:"sha384WithRSAEncryption",[Vi]:"sha512WithRSAEncryption",[io]:"ecPublicKey",[Od]:"ecdsaWithSHA1",[iv]:"ecdsaWithSHA224",[Nd]:"ecdsaWithSHA256",[Td]:"ecdsaWithSHA384",[Bd]:"ecdsaWithSHA512",[Fx]:"TLS WWW server authentication",[Wx]:"TLS WWW client authentication",[Kx]:"Code Signing",[Gx]:"E-mail Protection",[qx]:"Time Stamping",[zx]:"OCSP Signing",[Yx]:"Signed Data"};class dn{static serialize(e){return this.serializeObj(e).join(`
100
- `)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,r=0){const n=[];let s=this.pad(r++),o="";const i=e[de.VALUE];i&&(o=` ${i}`),n.push(`${s}${e[de.NAME]}:${o}`),s=this.pad(r);for(const a in e){if(typeof a=="symbol")continue;const c=e[a],u=a?`${a}: `:"";if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")n.push(`${s}${u}${c}`);else if(c instanceof Date)n.push(`${s}${u}${c.toUTCString()}`);else if(Array.isArray(c))for(const l of c)l[de.NAME]=a,n.push(...this.serializeObj(l,r));else if(c instanceof de)c[de.NAME]=a,n.push(...this.serializeObj(c,r));else if(U.isBufferSource(c))a?(n.push(`${s}${u}`),n.push(...this.serializeBufferSource(c,r+1))):n.push(...this.serializeBufferSource(c,r));else if("toTextObject"in c){const l=c.toTextObject();l[de.NAME]=a,n.push(...this.serializeObj(l,r))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return n}static serializeBufferSource(e,r=0){const n=this.pad(r),s=U.toUint8Array(e),o=[];for(let i=0;i<s.length;){const a=[];for(let c=0;c<16&&i<s.length;c++){c===8&&a.push("");const u=s[i++].toString(16).padStart(2,"0");a.push(u)}o.push(`${n}${a.join(" ")}`)}return o}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}dn.oidSerializer=Dr;dn.algorithmSerializer=CE;var xn,En;class Pr{get parseOptions(){return te(this,En,"f")}get rawData(){return te(this,xn,"f")||ge(this,xn,D.serialize(this.asn),"f"),te(this,xn,"f")}constructor(...e){xn.set(this,void 0),En.set(this,void 0),U.isBufferSource(e[0])?(ge(this,En,e[2],"f"),this.asn=D.parse(e[0],e[1],e[2]),ge(this,xn,U.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(ge(this,En,e[1],"f"),this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof Pr?ek(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return D.toString(this.rawData,te(this,En,"f"));case"text":return dn.serialize(this.toTextObject());case"hex":return Y.ToHex(this.rawData);case"base64":return Y.ToBase64(this.rawData);case"base64url":return Y.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new de(this.getTextName(),{},e)}}xn=new WeakMap,En=new WeakMap;Pr.NAME="ASN";class ht extends Pr{constructor(...e){let r,n;U.isBufferSource(e[0])?(r=U.toArrayBuffer(e[0]),n=e[1]):r=D.serialize(new _t({extnID:e[0],critical:e[1],extnValue:new ue(U.toArrayBuffer(e[2]))})),super(r,_t,n)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[de.NAME]===ht.NAME&&(e[de.NAME]=Dr.toString(this.type)),e}}var xv;class Er{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[xv]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set(Er.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set(Er.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,r){return this.items.forEach(e,r)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=Er.DEFAULT){const r=this.items.get(e.toLowerCase());if(!r)throw new Error(`Cannot get Crypto by name '${e}'`);return r}set(e,r){if(typeof e=="string"){if(!r)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),r)}else this.items.set(Er.DEFAULT,e);return this}}xv=Symbol.toStringTag;Er.DEFAULT="default";const tt=new Er,OE=/^[0-2](?:\.[1-9][0-9]*)+$/;function NE(t){return new RegExp(OE).test(t)}class Ev{constructor(e={}){this.items={};for(const r in e)this.register(r,e[r])}get(e){return this.items[e]||null}findId(e){return NE(e)?e:this.get(e)}register(e,r){this.items[e]=r,this.items[r]=e}}const rt=new Ev;rt.register("CN","2.5.4.3");rt.register("L","2.5.4.7");rt.register("ST","2.5.4.8");rt.register("O","2.5.4.10");rt.register("OU","2.5.4.11");rt.register("C","2.5.4.6");rt.register("DC","0.9.2342.19200300.100.1.25");rt.register("E","1.2.840.113549.1.9.1");rt.register("G","2.5.4.42");rt.register("I","2.5.4.43");rt.register("SN","2.5.4.4");rt.register("T","2.5.4.12");function TE(t,e){return`\\${Y.ToHex(Y.FromUtf8String(e)).toUpperCase()}`}function BE(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,TE)}class Tt{static isASCII(e){for(let r=0;r<e.length;r++)if(e.charCodeAt(r)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,r={}){this.extraNames=new Ev,this.asn=new Ie;for(const n in r)if(Object.prototype.hasOwnProperty.call(r,n)){const s=r[n];this.extraNames.register(n,s)}typeof e=="string"?this.asn=this.fromString(e):e instanceof Ie?this.asn=e:U.isBufferSource(e)?this.asn=D.parse(e,Ie):this.asn=this.fromJSON(e)}getField(e){const r=this.extraNames.findId(e)||rt.findId(e),n=[];for(const s of this.asn)for(const o of s)o.type===r&&n.push(o.value.toString());return n}getName(e){return this.extraNames.get(e)||rt.get(e)}toString(){return this.asn.map(e=>e.map(r=>{const n=this.getName(r.type)||r.type,s=r.value.anyValue?`#${Y.ToHex(r.value.anyValue)}`:BE(r.value.toString());return`${n}=${s}`}).join("+")).join(", ")}toJSON(){var e;const r=[];for(const n of this.asn){const s={};for(const o of n){const i=this.getName(o.type)||o.type;(e=s[i])!==null&&e!==void 0||(s[i]=[]),s[i].push(o.value.anyValue?`#${Y.ToHex(o.value.anyValue)}`:o.value.toString())}r.push(s)}return r}fromString(e){const r=new Ie,n=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let s=null,o=",";for(;s=n.exec(`${e},`);){let[,i,a]=s;const c=a[a.length-1];(c===","||c==="+")&&(a=a.slice(0,a.length-1),s[3]=c);const u=s[3];i=this.getTypeOid(i);const l=this.createAttribute(i,a);o==="+"?r[r.length-1].push(l):r.push(new Wn([l])),o=u}return r}fromJSON(e){const r=new Ie;for(const n of e){const s=new Wn;for(const o in n){const i=this.getTypeOid(o),a=n[o];for(const c of a){const u=this.createAttribute(i,c);s.push(u)}}r.push(s)}return r}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,r){const n=new $a({type:e});if(typeof r=="object")for(const s in r)switch(s){case"ia5String":n.value.ia5String=r[s];break;case"utf8String":n.value.utf8String=r[s];break;case"universalString":n.value.universalString=r[s];break;case"bmpString":n.value.bmpString=r[s];break;case"printableString":n.value.printableString=r[s];break}else if(r[0]==="#")n.value.anyValue=Y.FromHex(r.slice(1));else{const s=this.processStringValue(r);e===this.getName("E")||e===this.getName("DC")?n.value.ia5String=s:Tt.isPrintableString(s)?n.value.printableString=s:n.value.utf8String=s}return n}processStringValue(e){const r=/"(.*?[^\\])?"/.exec(e);return r&&(e=r[1]),e.replace(/\\0a/gi,`
101
- `).replace(/\\0d/gi,"\r").replace(/\\0g/gi," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return D.serialize(this.asn)}async getThumbprint(e,r){let n,s="SHA-1";return e&&(typeof e=="object"&&"subtle"in e?n=e:(s=e,n=r)),n??(n=tt.get()),await n.subtle.digest(s,this.toArrayBuffer())}}const Iv="Cannot initialize GeneralName from ASN.1 data.",Jh=`${Iv} Unsupported string format in use.`,$E=`${Iv} Value doesn't match to GUID regular expression.`,Zh=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Qh="1.3.6.1.4.1.311.25.1",em="1.3.6.1.4.1.311.20.2.3",Cc="dns",Oc="dn",Nc="email",Tc="ip",Bc="url",$c="guid",Rc="upn",zo="id";class Ir extends Pr{constructor(...e){let r;if(e.length===2)switch(e[0]){case Oc:{const n=new Tt(e[1]).toArrayBuffer(),s=D.parse(n,Ie);r=new ne({directoryName:s});break}case Cc:r=new ne({dNSName:e[1]});break;case Nc:r=new ne({rfc822Name:e[1]});break;case $c:{const n=new RegExp(Zh,"i").exec(e[1]);if(!n)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const s=n.slice(1).map((o,i)=>i<3?Y.ToHex(new Uint8Array(Y.FromHex(o)).reverse()):o).join("");r=new ne({otherName:new ro({typeId:Qh,value:D.serialize(new ue(Y.FromHex(s)))})});break}case Tc:r=new ne({iPAddress:e[1]});break;case zo:r=new ne({registeredID:e[1]});break;case Rc:{r=new ne({otherName:new ro({typeId:em,value:D.serialize(Hg.toASN(e[1]))})});break}case Bc:r=new ne({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else U.isBufferSource(e[0])?r=D.parse(e[0],ne):r=e[0];super(r)}onInit(e){if(e.dNSName!=null)this.type=Cc,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Nc,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=Tc,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=Bc,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=zo,this.value=e.registeredID;else if(e.directoryName!=null)this.type=Oc,this.value=new Tt(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===Qh){this.type=$c;const r=D.parse(e.otherName.value,ue),n=new RegExp(Zh,"i").exec(Y.ToHex(r));if(!n)throw new Error($E);this.value=n.slice(1).map((s,o)=>o<3?Y.ToHex(new Uint8Array(Y.FromHex(s)).reverse()):s).join("-")}else if(e.otherName.typeId===em)this.type=Rc,this.value=D.parse(e.otherName.value,Ve).toString();else throw new Error(Jh);else throw new Error(Jh)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case Oc:case Cc:case $c:case Tc:case zo:case Rc:case Bc:e=this.type.toUpperCase();break;case Nc:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let r=this.value;return this.type===zo&&(r=Dr.toString(r)),new de(e,void 0,r)}}class fn extends Pr{constructor(e){let r;if(e instanceof He)r=e;else if(Array.isArray(e)){const n=[];for(const s of e)if(s instanceof ne)n.push(s);else{const o=D.parse(new Ir(s.type,s.value).rawData,ne);n.push(o)}r=new He(n)}else if(U.isBufferSource(e))r=D.parse(e,He);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(r)}onInit(e){const r=[];for(const n of e){let s=null;try{s=new Ir(n)}catch{continue}r.push(s)}this.items=r}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){const e=super.toTextObjectEmpty();for(const r of this.items){const n=r.toTextObject();let s=e[n[de.NAME]];Array.isArray(s)||(s=[],e[n[de.NAME]]=s),s.push(n)}return e}}fn.NAME="GeneralNames";const Ks="-{5}",lo="\\n",RE=`[^${lo}]+`,_E=`${Ks}BEGIN (${RE}(?=${Ks}))${Ks}`,ME=`${Ks}END \\1${Ks}`,Zn="\\n",jE=`[^:${lo}]+`,DE=`(?:[^${lo}]+${Zn}(?: +[^${lo}]+${Zn})*)`,PE="[a-zA-Z0-9=+/]+",LE=`(?:${PE}${Zn})+`,tm=`${_E}${Zn}(?:((?:${jE}: ${DE})+))?${Zn}?(${LE})${ME}`,UE=new RegExp(`[${lo}]+`,"g");class lt{static isPem(e){return typeof e=="string"&&new RegExp(tm,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const r=new RegExp(tm,"g"),n=[];let s=null;for(;s=r.exec(e);){const o=s[3].replace(UE,""),i={type:s[1],headers:[],rawData:Y.FromBase64(o)},a=s[2];if(a){const c=a.split(new RegExp(Zn,"g"));let u=null;for(const l of c){const[d,m]=l.split(/:(.*)/);if(m===void 0){if(!u)throw new Error("Cannot parse PEM string. Incorrect header value");u.value+=d.trim()}else u&&i.headers.push(u),u={key:d,value:m.trim()}}u&&i.headers.push(u)}n.push(i)}return n}static decode(e){return this.decodeWithHeaders(e).map(n=>n.rawData)}static decodeFirst(e){const r=this.decode(e);if(!r.length)throw new RangeError("PEM string doesn't contain any objects");return r[0]}static encode(e,r){if(Array.isArray(e)){const n=new Array;return r?e.forEach(s=>{if(!U.isBufferSource(s))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");n.push(this.encodeStruct({type:r,rawData:U.toArrayBuffer(s)}))}):e.forEach(s=>{if(!("type"in s))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");n.push(this.encodeStruct(s))}),n.join(`
102
- `)}else{if(!r)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:r,rawData:U.toArrayBuffer(e)})}}static encodeStruct(e){var r;const n=e.type.toLocaleUpperCase(),s=[];if(s.push(`-----BEGIN ${n}-----`),!((r=e.headers)===null||r===void 0)&&r.length){for(const i of e.headers)s.push(`${i.key}: ${i.value}`);s.push("")}const o=Y.ToBase64(e.rawData);for(let i=0;i<o.length;i+=64)s.push(o.substring(i,i+64));return s.push(`-----END ${n}-----`),s.join(`
103
- `)}}lt.CertificateTag="CERTIFICATE";lt.CrlTag="CRL";lt.CertificateRequestTag="CERTIFICATE REQUEST";lt.PublicKeyTag="PUBLIC KEY";lt.PrivateKeyTag="PRIVATE KEY";class mr extends Pr{static isAsnEncoded(e){return U.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(lt.isPem(e))return lt.decode(e)[0];if(Y.isHex(e))return Y.FromHex(e);if(Y.isBase64(e))return Y.FromBase64(e);if(Y.isBase64Url(e))return Y.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{const r=U.toUint8Array(e);if(r.length>0&&r[0]===48)return U.toArrayBuffer(e);const n=Y.ToBinary(e);if(lt.isPem(n))return lt.decode(n)[0];if(Y.isHex(n))return Y.FromHex(n);if(Y.isBase64(n))return Y.FromBase64(n);if(Y.isBase64Url(n))return Y.FromBase64Url(n);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){mr.isAsnEncoded(e[0])?super(mr.toArrayBuffer(e[0]),e[1],e[2]):super(e[0],e[1])}toString(e="pem"){return e==="pem"?lt.encode(this.rawData,this.tag):super.toString(e)}}class Rt extends mr{static async create(e,r=tt.get()){if(e instanceof Rt)return e;if(Er.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");const n=await r.subtle.exportKey("spki",e);return new Rt(n)}else{if(e.publicKey)return e.publicKey;if(U.isBufferSource(e))return new Rt(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e,r){mr.isAsnEncoded(e)?super(e,bt,r):super(e,r),this.tag=lt.PublicKeyTag}async export(e,r,n){let s,o=["verify"],i={hash:"SHA-256",...this.algorithm};r?(i=e,o=r,s=n):s=e,s??(s=tt.get());let a=this.rawData;const c=D.parse(this.rawData,bt,this.parseOptions);return c.algorithm.algorithm===Ws&&(a=VE(c,a)),s.subtle.importKey("spki",a,i,!0,o)}onInit(e){const r=Te.resolve(ln),n=this.algorithm=r.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===an){const s=D.parse(e.subjectPublicKey,$d,this.parseOptions),o=U.toUint8Array(s.modulus);n.publicExponent=U.toUint8Array(s.publicExponent),n.modulusLength=(o[0]?o:o.slice(1)).byteLength<<3}}async getThumbprint(e,r){let n,s="SHA-1";return e&&(typeof e=="object"&&"subtle"in e?n=e:(s=e,n=r)),n??(n=tt.get()),await n.subtle.digest(s,this.rawData)}async getKeyIdentifier(e,r){let n,s="SHA-1";e&&(typeof e=="object"&&"subtle"in e?n=e:(s=e,n=r)),n??(n=tt.get());const o=D.parse(this.rawData,bt,this.parseOptions);return await n.subtle.digest(s,o.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),r=D.parse(this.rawData,bt,this.parseOptions);switch(e.Algorithm=dn.serializeAlgorithm(r.algorithm),r.algorithm.algorithm){case io:e["EC Point"]=r.subjectPublicKey;break;case an:default:e["Raw Data"]=r.subjectPublicKey}return e}}function VE(t,e){return t.algorithm=new L({algorithm:an,parameters:null}),e=D.serialize(t),e}class pn extends ht{static async create(e,r=!1,n=tt.get()){if("name"in e&&"serialNumber"in e)return new pn(e,r);const o=await(await Rt.create(e,n)).getKeyIdentifier(n);return new pn(Y.ToHex(o),r)}constructor(...e){if(U.isBufferSource(e[0]))super(e[0],e[1]);else if(typeof e[0]=="string"){const r=new Wr({keyIdentifier:new pd(Y.FromHex(e[0]))});super(ou,e[1],D.serialize(r))}else{const r=e[0],n=r.name instanceof fn?D.parse(r.name.rawData,He):r.name,s=new Wr({authorityCertIssuer:n,authorityCertSerialNumber:Y.FromHex(r.serialNumber)});super(ou,e[1],D.serialize(s))}}onInit(e){super.onInit(e);const r=D.parse(e.extnValue,Wr,this.parseOptions);r.keyIdentifier&&(this.keyId=Y.ToHex(r.keyIdentifier)),(r.authorityCertIssuer||r.authorityCertSerialNumber)&&(this.certId={name:r.authorityCertIssuer||[],serialNumber:r.authorityCertSerialNumber?Y.ToHex(r.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),r=D.parse(this.value,Wr,this.parseOptions);return r.authorityCertIssuer&&(e["Authority Issuer"]=new fn(r.authorityCertIssuer).toTextObject()),r.authorityCertSerialNumber&&(e["Authority Serial Number"]=r.authorityCertSerialNumber),r.keyIdentifier&&(e[""]=r.keyIdentifier),e}}pn.NAME="Authority Key Identifier";class fo extends ht{constructor(...e){if(U.isBufferSource(e[0])){super(e[0],e[1]);const r=D.parse(this.value,Ai,this.parseOptions);this.ca=r.cA,this.pathLength=r.pathLenConstraint}else{const r=new Ai({cA:e[0],pathLenConstraint:e[1]});super(Wg,e[2],D.serialize(r)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}}fo.NAME="Basic Constraints";var rm;(function(t){t.serverAuth="1.3.6.1.5.5.7.3.1",t.clientAuth="1.3.6.1.5.5.7.3.2",t.codeSigning="1.3.6.1.5.5.7.3.3",t.emailProtection="1.3.6.1.5.5.7.3.4",t.timeStamping="1.3.6.1.5.5.7.3.8",t.ocspSigning="1.3.6.1.5.5.7.3.9"})(rm||(rm={}));class rc extends ht{constructor(...e){if(U.isBufferSource(e[0])){super(e[0],e[1]);const r=D.parse(this.value,Ei,this.parseOptions);this.usages=r.map(n=>n)}else{const r=new Ei(e[0]);super(qg,e[1],D.serialize(r)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(r=>Dr.toString(r)).join(", "),e}}rc.NAME="Extended Key Usages";var jn;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(jn||(jn={}));class po extends ht{constructor(...e){if(U.isBufferSource(e[0])){super(e[0],e[1]);const r=D.parse(this.value,Ic,this.parseOptions);this.usages=r.toNumber()}else{const r=new Ic(e[0]);super(Yg,e[1],D.serialize(r)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=D.parse(this.value,Ic,this.parseOptions);return e[""]=r.toJSON().join(", "),e}}po.NAME="Key Usages";class _o extends ht{static async create(e,r=!1,n=tt.get()){const o=await(await Rt.create(e,n)).getKeyIdentifier(n);return new _o(Y.ToHex(o),r)}constructor(...e){if(U.isBufferSource(e[0])){super(e[0],e[1]);const r=D.parse(this.value,Or,this.parseOptions);this.keyId=Y.ToHex(r)}else{const r=typeof e[0]=="string"?Y.FromHex(e[0]):e[0],n=new Or(r);super(Qg,e[1],D.serialize(n)),this.keyId=Y.ToHex(r)}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=D.parse(this.value,Or,this.parseOptions);return e[""]=r,e}}_o.NAME="Subject Key Identifier";class jd extends ht{constructor(...e){U.isBufferSource(e[0])?super(e[0],e[1]):super(Zg,e[1],new fn(e[0]||[]).rawData)}onInit(e){super.onInit(e);const r=D.parse(e.extnValue,wu,this.parseOptions);this.names=new fn(r)}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(const n in r)e[n]=r[n];return e}}jd.NAME="Subject Alternative Name";class mt{static register(e,r){this.items.set(e,r)}static create(e,r){const n=new ht(e,r),s=this.items.get(n.type);return s?new s(e,r):n}}mt.items=new Map;class Cv extends ht{constructor(...e){var r;if(U.isBufferSource(e[0])){super(e[0],e[1]);const n=D.parse(this.value,ki,this.parseOptions);this.policies=n.map(s=>s.policyIdentifier)}else{const n=e[0],s=(r=e[1])!==null&&r!==void 0?r:!1,o=new ki(n.map(i=>new _a({policyIdentifier:i})));super(Kg,s,D.serialize(o)),this.policies=n}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(r=>new de("",{},Dr.toString(r))),e}}Cv.NAME="Certificate Policies";mt.register(Kg,Cv);class Ov extends ht{constructor(...e){var r;if(U.isBufferSource(e[0]))super(e[0],e[1]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){const s=e[0].map(i=>new ns({distributionPoint:new rn({fullName:[new ne({uniformResourceIdentifier:i})]})})),o=new Mn(s);super(lu,e[1],D.serialize(o))}else{const n=new Mn(e[0]);super(lu,e[1],D.serialize(n))}(r=this.distributionPoints)!==null&&r!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);const r=D.parse(e.extnValue,Mn,this.parseOptions);this.distributionPoints=r}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(r=>{var n;const s=new de("");return!((n=r.distributionPoint)===null||n===void 0)&&n.fullName&&(s[""]=r.distributionPoint.fullName.map(o=>new Ir(o).toString()).join(", ")),r.reasons&&(s.Reasons=r.reasons.toString()),r.cRLIssuer&&(s["CRL Issuer"]=r.cRLIssuer.map(o=>o.toString()).join(", ")),s}),e}}Ov.NAME="CRL Distribution Points";class Nv extends ht{constructor(...e){var r,n,s,o;if(U.isBufferSource(e[0]))super(e[0],e[1]);else if(e[0]instanceof Tn){const i=new Tn(e[0]);super(su,e[1],D.serialize(i))}else{const i=e[0],a=new Tn;Xo(a,i,gp,"ocsp"),Xo(a,i,vp,"caIssuers"),Xo(a,i,bp,"timeStamping"),Xo(a,i,wp,"caRepository"),super(su,e[1],D.serialize(a))}(r=this.ocsp)!==null&&r!==void 0||(this.ocsp=[]),(n=this.caIssuers)!==null&&n!==void 0||(this.caIssuers=[]),(s=this.timeStamping)!==null&&s!==void 0||(this.timeStamping=[]),(o=this.caRepository)!==null&&o!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],D.parse(e.extnValue,Tn,this.parseOptions).forEach(n=>{switch(n.accessMethod){case gp:this.ocsp.push(new Ir(n.accessLocation));break;case vp:this.caIssuers.push(new Ir(n.accessLocation));break;case bp:this.timeStamping.push(new Ir(n.accessLocation));break;case wp:this.caRepository.push(new Ir(n.accessLocation));break}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&Yo(e,"OCSP",this.ocsp),this.caIssuers.length&&Yo(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Yo(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Yo(e,"CA Repository",this.caRepository),e}}Nv.NAME="Authority Info Access";function Yo(t,e,r){if(r.length===1)t[e]=r[0].toTextObject();else{const n=new de("");r.forEach((s,o)=>{const i=s.toTextObject(),a=`${i[de.NAME]} ${o+1}`;let c=n[a];Array.isArray(c)||(c=[],n[a]=c),c.push(i)}),t[e]=n}}function Xo(t,e,r,n){const s=e[n];s&&(Array.isArray(s)?s:[s]).forEach(i=>{typeof i=="string"&&(i=new Ir("url",i)),t.push(new So({accessMethod:r,accessLocation:D.parse(i.rawData,ne)}))})}class Tv extends ht{constructor(...e){U.isBufferSource(e[0])?super(e[0],e[1]):super(zg,e[1],new fn(e[0]||[]).rawData)}onInit(e){super.onInit(e);const r=D.parse(e.extnValue,He,this.parseOptions);this.names=new fn(r)}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(const n in r)e[n]=r[n];return e}}Tv.NAME="Issuer Alternative Name";class ds extends Pr{constructor(...e){let r,n;if(U.isBufferSource(e[0]))r=U.toArrayBuffer(e[0]),n=e[1];else{const s=e[0],o=Array.isArray(e[1])?e[1].map(i=>U.toArrayBuffer(i)):[];r=D.serialize(new fr({type:s,values:o}))}super(r,fr,n)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(r=>new de("",{"":r})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[de.NAME]===ds.NAME&&(e[de.NAME]=Dr.toString(this.type)),e}}ds.NAME="Attribute";class Bv extends ds{constructor(...e){var r;if(U.isBufferSource(e[0]))super(e[0],e[1]);else{const n=new Xi({printableString:e[0]});super(Av,[D.serialize(n)])}(r=this.password)!==null&&r!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const r=D.parse(this.values[0],Xi,this.parseOptions);this.password=r.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[de.VALUE]=this.password,e}}Bv.NAME="Challenge Password";class Dd extends ds{constructor(...e){var r;if(U.isBufferSource(e[0]))super(e[0],e[1]);else{const n=e[0],s=new Tr;for(const o of n)s.push(D.parse(o.rawData,_t));super(Md,[D.serialize(s)])}(r=this.items)!==null&&r!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const r=D.parse(this.values[0],Tr,this.parseOptions);this.items=r.map(n=>mt.create(D.serialize(n),this.parseOptions))}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.items.map(n=>n.toTextObject());for(const n of r)e[n[de.NAME]]=n;return e}}Dd.NAME="Extensions";class nc{static register(e,r){this.items.set(e,r)}static create(e,r){const n=new ds(e,r),s=this.items.get(n.type);return s?new s(e,r):n}}nc.items=new Map;const Mo="crypto.signatureFormatter";class HE{toAsnSignature(e,r){return U.toArrayBuffer(r)}toWebSignature(e,r){return U.toArrayBuffer(r)}}var oi;let ml=oi=class{static createPssParams(e,r){const n=oi.getHashAlgorithm(e);return n?new un({hashAlgorithm:n,maskGenAlgorithm:new L({algorithm:za,parameters:D.serialize(n)}),saltLength:r}):null}static getHashAlgorithm(e){const r=Te.resolve(ln);return typeof e=="string"?r.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?r.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let r;if(typeof e.hash=="string")r=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")r=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(r.toLowerCase()){case"sha-1":return new L({algorithm:Li,parameters:null});case"sha-256":return new L({algorithm:Vu,parameters:null});case"sha-384":return new L({algorithm:Ui,parameters:null});case"sha-512":return new L({algorithm:Vi,parameters:null})}}else return new L({algorithm:an,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");const r=oi.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new L({algorithm:Ws,parameters:D.serialize(r)})}else return new L({algorithm:Ws,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case an:return{name:"RSASSA-PKCS1-v1_5"};case Li:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case Vu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case Ui:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case Vi:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case Ws:if(e.parameters){const r=D.parse(e.parameters,un);return{name:"RSA-PSS",hash:Te.resolve(ln).toWebAlgorithm(r.hashAlgorithm),saltLength:r.saltLength}}else return{name:"RSA-PSS"}}return null}};ml=oi=f([us()],ml);Te.registerSingleton(bn,ml);let yl=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new L({algorithm:Hi});case"sha-256":return new L({algorithm:Fi});case"sha-384":return new L({algorithm:Wi});case"sha-512":return new L({algorithm:Ki})}return null}toWebAlgorithm(e){switch(e.algorithm){case Hi:return{name:"SHA-1"};case Fi:return{name:"SHA-256"};case Wi:return{name:"SHA-384"};case Ki:return{name:"SHA-512"}}return null}};yl=f([us()],yl);Te.registerSingleton(bn,yl);class wt{addPadding(e,r){const n=U.toUint8Array(r),s=new Uint8Array(e);return s.set(n,e-n.length),s.buffer}removePadding(e,r=!1){let n=U.toUint8Array(e);for(let s=0;s<n.length;s++)if(n[s]){n=n.slice(s);break}if(r&&n[0]>127){const s=new Uint8Array(n.length+1);return s.set(n,1),s.buffer}return n.buffer}toAsnSignature(e,r){if(e.name==="ECDSA"){const n=e.namedCurve,s=wt.namedCurveSize.get(n)||wt.defaultNamedCurveSize,o=new Pi,i=U.toUint8Array(r);return o.r=this.removePadding(i.slice(0,s),!0),o.s=this.removePadding(i.slice(s,s+s),!0),D.serialize(o)}return null}toWebSignature(e,r){if(e.name==="ECDSA"){const n=D.parse(r,Pi),s=e.namedCurve,o=wt.namedCurveSize.get(s)||wt.defaultNamedCurveSize,i=this.addPadding(o,this.removePadding(n.r)),a=this.addPadding(o,this.removePadding(n.s));return QS(i,a)}return null}}wt.namedCurveSize=new Map;wt.defaultNamedCurveSize=32;const _c="1.3.101.110",nm="1.3.101.111",Mc="1.3.101.112",sm="1.3.101.113";let gl=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ed25519":r=Mc;break;case"x25519":r=_c;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":r=Mc;break;case"ed448":r=sm;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":r=_c;break;case"x448":r=nm;break}}return r?new L({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case Mc:return{name:"Ed25519"};case sm:return{name:"EdDSA",namedCurve:"Ed448"};case _c:return{name:"X25519"};case nm:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};gl=f([us()],gl);Te.registerSingleton(bn,gl);let vl=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ml-dsa-44":r=ch;break;case"ml-dsa-65":r=uh;break;case"ml-dsa-87":r=lh;break}return r?new L({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case ch:return{name:"ML-DSA-44"};case uh:return{name:"ML-DSA-65"};case lh:return{name:"ML-DSA-87"}}return null}};vl=f([us()],vl);Te.registerSingleton(bn,vl);let bl=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"slh-dsa-sha2-128s":r=dh;break;case"slh-dsa-sha2-128f":r=fh;break;case"slh-dsa-sha2-192s":r=ph;break;case"slh-dsa-sha2-192f":r=hh;break;case"slh-dsa-sha2-256s":r=mh;break;case"slh-dsa-sha2-256f":r=yh;break;case"slh-dsa-shake-128s":r=gh;break;case"slh-dsa-shake-128f":r=vh;break;case"slh-dsa-shake-192s":r=bh;break;case"slh-dsa-shake-192f":r=wh;break;case"slh-dsa-shake-256s":r=Ah;break;case"slh-dsa-shake-256f":r=Sh;break}return r?new L({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case dh:return{name:"SLH-DSA-SHA2-128s"};case fh:return{name:"SLH-DSA-SHA2-128f"};case ph:return{name:"SLH-DSA-SHA2-192s"};case hh:return{name:"SLH-DSA-SHA2-192f"};case mh:return{name:"SLH-DSA-SHA2-256s"};case yh:return{name:"SLH-DSA-SHA2-256f"};case gh:return{name:"SLH-DSA-SHAKE-128s"};case vh:return{name:"SLH-DSA-SHAKE-128f"};case bh:return{name:"SLH-DSA-SHAKE-192s"};case wh:return{name:"SLH-DSA-SHAKE-192f"};case Ah:return{name:"SLH-DSA-SHAKE-256s"};case Sh:return{name:"SLH-DSA-SHAKE-256f"}}return null}};bl=f([us()],bl);Te.registerSingleton(bn,bl);var vs,bs,ws,As,Ss,ks,xs,In;class FE extends mr{get subjectName(){return te(this,bs,"f")||ge(this,bs,new Tt(this.asn.certificationRequestInfo.subject),"f"),te(this,bs,"f")}get subject(){return te(this,ws,"f")||ge(this,ws,this.subjectName.toString(),"f"),te(this,ws,"f")}get signatureAlgorithm(){if(!te(this,As,"f")){const e=Te.resolve(ln);ge(this,As,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return te(this,As,"f")}get signature(){return te(this,Ss,"f")||ge(this,Ss,this.asn.signature,"f"),te(this,Ss,"f")}get publicKey(){return te(this,ks,"f")||ge(this,ks,new Rt(this.asn.certificationRequestInfo.subjectPKInfo,this.parseOptions),"f"),te(this,ks,"f")}get attributes(){return te(this,xs,"f")||ge(this,xs,this.asn.certificationRequestInfo.attributes.map(e=>nc.create(D.serialize(e),this.parseOptions)),"f"),te(this,xs,"f")}get extensions(){if(!te(this,In,"f")){ge(this,In,[],"f");const e=this.getAttribute(Md);e instanceof Dd&&ge(this,In,e.items,"f")}return te(this,In,"f")}get tbs(){return te(this,vs,"f")||ge(this,vs,this.asn.certificationRequestInfoRaw||D.serialize(this.asn.certificationRequestInfo),"f"),te(this,vs,"f")}constructor(e,r){const n=mr.isAsnEncoded(e)?[e,co,r]:[e,r];super(n[0],n[1],n[2]),vs.set(this,void 0),bs.set(this,void 0),ws.set(this,void 0),As.set(this,void 0),Ss.set(this,void 0),ks.set(this,void 0),xs.set(this,void 0),In.set(this,void 0),this.tag=lt.CertificateRequestTag}onInit(e){}getAttribute(e){for(const r of this.attributes)if(r.type===e)return r;return null}getAttributes(e){return this.attributes.filter(r=>r.type===e)}getExtension(e){for(const r of this.extensions)if(r.type===e)return r;return null}getExtensions(e){return this.extensions.filter(r=>r.type===e)}async verify(e=tt.get()){const r={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(r,["verify"],e),s=Te.resolveAll(Mo).reverse();let o=null;for(const a of s)if(o=a.toWebSignature(r,this.signature),o)break;if(!o)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,n,o,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty(),r=D.parse(this.rawData,co,this.parseOptions),n=r.certificationRequestInfo,s=new de("",{Version:`${nn[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const o=new de("");for(const i of this.attributes){const a=i.toTextObject();o[a[de.NAME]]=a}s.Attributes=o}return e.Data=s,e.Signature=new de("",{Algorithm:dn.serializeAlgorithm(r.signatureAlgorithm),"":r.signature}),e}}vs=new WeakMap,bs=new WeakMap,ws=new WeakMap,As=new WeakMap,Ss=new WeakMap,ks=new WeakMap,xs=new WeakMap,In=new WeakMap;FE.NAME="PKCS#10 Certificate Request";function WE(t){let e=0;for(;e<t.length-1&&t[e]===0;)e++;let r=t.slice(e);if(r.length||(r=new Uint8Array([0])),r[0]>127){const n=new Uint8Array(r.length+1);n[0]=0,n.set(r,1),r=n}return r.buffer}function KE(t,e=tt.get()){const r=U.toUint8Array(Y.FromHex(t||"")),n=r.length&&r.some(s=>s>0)?r:e.getRandomValues(new Uint8Array(16));return WE(n)}function GE(t){let e=U.toUint8Array(t);return e.length>1&&e[0]===0&&e[1]>127&&(e=e.slice(1)),Y.ToHex(e)}var Es,Is,Cs,Os,Ns,Ts,Bs,$s,Rs,_s,Cn,Ms;class $v extends mr{get publicKey(){return te(this,Ms,"f")||ge(this,Ms,new Rt(this.asn.tbsCertificate.subjectPublicKeyInfo,this.parseOptions),"f"),te(this,Ms,"f")}get serialNumber(){return te(this,Is,"f")||ge(this,Is,GE(this.asn.tbsCertificate.serialNumber),"f"),te(this,Is,"f")}get subjectName(){return te(this,Cs,"f")||ge(this,Cs,new Tt(this.asn.tbsCertificate.subject),"f"),te(this,Cs,"f")}get subject(){return te(this,Os,"f")||ge(this,Os,this.subjectName.toString(),"f"),te(this,Os,"f")}get issuerName(){return te(this,Ns,"f")||ge(this,Ns,new Tt(this.asn.tbsCertificate.issuer),"f"),te(this,Ns,"f")}get issuer(){return te(this,Ts,"f")||ge(this,Ts,this.issuerName.toString(),"f"),te(this,Ts,"f")}get notBefore(){if(!te(this,Bs,"f")){const e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");ge(this,Bs,e,"f")}return te(this,Bs,"f")}get notAfter(){if(!te(this,$s,"f")){const e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");ge(this,$s,e,"f")}return te(this,$s,"f")}get signatureAlgorithm(){if(!te(this,Rs,"f")){const e=Te.resolve(ln);ge(this,Rs,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return te(this,Rs,"f")}get signature(){return te(this,_s,"f")||ge(this,_s,this.asn.signatureValue,"f"),te(this,_s,"f")}get extensions(){return te(this,Cn,"f")||(ge(this,Cn,[],"f"),this.asn.tbsCertificate.extensions&&ge(this,Cn,this.asn.tbsCertificate.extensions.map(e=>mt.create(D.serialize(e),this.parseOptions)),"f")),te(this,Cn,"f")}get tbs(){return te(this,Es,"f")||ge(this,Es,this.asn.tbsCertificateRaw||D.serialize(this.asn.tbsCertificate),"f"),te(this,Es,"f")}constructor(e,r){const n=mr.isAsnEncoded(e)?[e,sn,r]:[e,r];super(n[0],n[1],n[2]),Es.set(this,void 0),Is.set(this,void 0),Cs.set(this,void 0),Os.set(this,void 0),Ns.set(this,void 0),Ts.set(this,void 0),Bs.set(this,void 0),$s.set(this,void 0),Rs.set(this,void 0),_s.set(this,void 0),Cn.set(this,void 0),Ms.set(this,void 0),this.tag=lt.CertificateTag}onInit(e){}getExtension(e){for(const r of this.extensions)if(typeof e=="string"){if(r.type===e)return r}else if(r instanceof e)return r;return null}getExtensions(e){return this.extensions.filter(r=>typeof e=="string"?r.type===e:r instanceof e)}async verify(e={},r=tt.get()){let n,s;const o=e.publicKey;try{if(!o)n={...this.publicKey.algorithm,...this.signatureAlgorithm},s=await this.publicKey.export(n,["verify"],r);else if("publicKey"in o)n={...o.publicKey.algorithm,...this.signatureAlgorithm},s=await o.publicKey.export(n,["verify"],r);else if(o instanceof Rt)n={...o.algorithm,...this.signatureAlgorithm},s=await o.export(n,["verify"],r);else if(U.isBufferSource(o)){const u=new Rt(o);n={...u.algorithm,...this.signatureAlgorithm},s=await u.export(n,["verify"],r)}else n={...o.algorithm,...this.signatureAlgorithm},s=o}catch{return!1}const i=Te.resolveAll(Mo).reverse();let a=null;for(const u of i)if(a=u.toWebSignature(n,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const c=await r.subtle.verify(this.signatureAlgorithm,s,a,this.tbs);if(e.signatureOnly)return c;{const l=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<l&&l<this.notAfter.getTime()}}async getThumbprint(e,r){let n,s="SHA-1";return e&&(typeof e=="object"&&"subtle"in e?n=e:(s=e,n=r)),n??(n=tt.get()),await n.subtle.digest(s,this.rawData)}async isSelfSigned(e=tt.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),r=D.parse(this.rawData,sn,this.parseOptions),n=r.tbsCertificate,s=new de("",{Version:`${nn[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":dn.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new de("",{"Not Before":n.validity.notBefore.getTime(),"Not After":n.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(n.issuerUniqueID&&(s["Issuer Unique ID"]=n.issuerUniqueID),n.subjectUniqueID&&(s["Subject Unique ID"]=n.subjectUniqueID),this.extensions.length){const o=new de("");for(const i of this.extensions){const a=i.toTextObject();o[a[de.NAME]]=a}s.Extensions=o}return e.Data=s,e.Signature=new de("",{Algorithm:dn.serializeAlgorithm(r.signatureAlgorithm),"":r.signatureValue}),e}}Es=new WeakMap,Is=new WeakMap,Cs=new WeakMap,Os=new WeakMap,Ns=new WeakMap,Ts=new WeakMap,Bs=new WeakMap,$s=new WeakMap,Rs=new WeakMap,_s=new WeakMap,Cn=new WeakMap,Ms=new WeakMap;$v.NAME="Certificate";class wl{static async createSelfSigned(e,r=tt.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},r)}static async create(e,r=tt.get()){var n;let s;e.publicKey instanceof Rt?s=e.publicKey.rawData:"publicKey"in e.publicKey?s=e.publicKey.publicKey.rawData:U.isBufferSource(e.publicKey)?s=e.publicKey:s=await r.subtle.exportKey("spki",e.publicKey);const o=KE(e.serialNumber,r),i=e.notBefore||new Date,a=e.notAfter||new Date(i.getTime()+31536e6),c=new sn({tbsCertificate:new pt({version:nn.v3,serialNumber:o,validity:new ko({notBefore:i,notAfter:a}),extensions:new Tr(((n=e.extensions)===null||n===void 0?void 0:n.map(g=>D.parse(g.rawData,_t)))||[]),subjectPublicKeyInfo:D.parse(s,bt)})});if(e.subject){const g=e.subject instanceof Tt?e.subject:new Tt(e.subject);c.tbsCertificate.subject=D.parse(g.toArrayBuffer(),Ie)}if(e.issuer){const g=e.issuer instanceof Tt?e.issuer:new Tt(e.issuer);c.tbsCertificate.issuer=D.parse(g.toArrayBuffer(),Ie)}const u={hash:"SHA-256"},l="signingKey"in e?{...u,...e.signingAlgorithm,...e.signingKey.algorithm}:{...u,...e.signingAlgorithm},d=Te.resolve(ln);c.tbsCertificate.signature=c.signatureAlgorithm=d.toAsnAlgorithm(l);const m=D.serialize(c.tbsCertificate),p="signingKey"in e?await r.subtle.sign(l,e.signingKey,m):e.signature,y=Te.resolveAll(Mo).reverse();let v=null;for(const g of y)if(v=g.toAsnSignature(l,p),v)break;if(!v)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=v,new $v(D.serialize(c))}}var om;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(om||(om={}));mt.register(Wg,fo);mt.register(qg,rc);mt.register(Yg,po);mt.register(Qg,_o);mt.register(ou,pn);mt.register(Zg,jd);mt.register(lu,Ov);mt.register(su,Nv);mt.register(zg,Tv);nc.register(Av,Bv);nc.register(Md,Dd);Te.registerSingleton(Mo,HE);Te.registerSingleton(Mo,wt);wt.namedCurveSize.set("P-256",32);wt.namedCurveSize.set("K-256",32);wt.namedCurveSize.set("P-384",48);wt.namedCurveSize.set("P-521",66);const Ze=tb,Al={name:"ECDSA",namedCurve:"P-256",hash:"SHA-256"},ho={name:"ECDSA",namedCurve:"P-256"},qE="1.3.6.1.5.5.7.3.1",zE="1.3.6.1.5.5.7.3.2",Sl=6e4,kl=864e5;function Rv(t){return`${t}.display`}function YE(t,e){const r=Buffer.from(e).toString("base64").match(/.{1,64}/g)?.join(`
117
+ `)}function Px(t,e,r){var n=sa(t.toString().match(/constructor\(([\w, ]+)\)/)||[],2),o=n[1],s=o===void 0?null:o,i=Dx(s,e);return Lx("Cannot inject the dependency "+i+' of "'+t.name+'" constructor. Reason:',r)}function Ux(t){if(typeof t.dispose!="function")return!1;var e=t.dispose;return!(e.length>0)}var Vx=(function(t){rf(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(nf),Hx=(function(t){rf(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(nf),Fx=(function(){function t(){this.preResolution=new Vx,this.postResolution=new Hx}return t})(),Yv=new Map,Wx=(function(){function t(e){this.parent=e,this._registry=new jx,this.interceptors=new Fx,this.disposed=!1,this.disposables=new Set}return t.prototype.register=function(e,r,n){n===void 0&&(n={lifecycle:nt.Transient}),this.ensureNotDisposed();var o;if(_x(r)?o=r:o={useClass:r},hi(o))for(var s=[e],i=o;i!=null;){var a=i.useToken;if(s.includes(a))throw new Error("Token registration cycle detected! "+Zr(s,[a]).join(" -> "));s.push(a);var c=this._registry.get(a);c&&hi(c.provider)?i=c.provider:i=null}if((n.lifecycle===nt.Singleton||n.lifecycle==nt.ContainerScoped||n.lifecycle==nt.ResolutionScoped)&&(mi(o)||dl(o)))throw new Error('Cannot use lifecycle "'+nt[n.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:o,options:n}),this},t.prototype.registerType=function(e,r){return this.ensureNotDisposed(),Mn(r)?this.register(e,{useToken:r}):this.register(e,{useClass:r})},t.prototype.registerInstance=function(e,r){return this.ensureNotDisposed(),this.register(e,{useValue:r})},t.prototype.registerSingleton=function(e,r){if(this.ensureNotDisposed(),Mn(e)){if(Mn(r))return this.register(e,{useToken:r},{lifecycle:nt.Singleton});if(r)return this.register(e,{useClass:r},{lifecycle:nt.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var n=e;return r&&!Mn(r)&&(n=r),this.register(e,{useClass:n},{lifecycle:nt.Singleton})},t.prototype.resolve=function(e,r,n){r===void 0&&(r=new si),n===void 0&&(n=!1),this.ensureNotDisposed();var o=this.getRegistration(e);if(!o&&Mn(e)){if(n)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),o){var s=this.resolveRegistration(o,r);return this.executePostResolutionInterceptor(e,s,"Single"),s}if(Mx(e)){var s=this.construct(e,r);return this.executePostResolutionInterceptor(e,s,"Single"),s}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},t.prototype.executePreResolutionInterceptor=function(e,r){var n,o;if(this.interceptors.preResolution.has(e)){var s=[];try{for(var i=oi(this.interceptors.preResolution.getAll(e)),a=i.next();!a.done;a=i.next()){var c=a.value;c.options.frequency!="Once"&&s.push(c),c.callback(e,r)}}catch(u){n={error:u}}finally{try{a&&!a.done&&(o=i.return)&&o.call(i)}finally{if(n)throw n.error}}this.interceptors.preResolution.setAll(e,s)}},t.prototype.executePostResolutionInterceptor=function(e,r,n){var o,s;if(this.interceptors.postResolution.has(e)){var i=[];try{for(var a=oi(this.interceptors.postResolution.getAll(e)),c=a.next();!c.done;c=a.next()){var u=c.value;u.options.frequency!="Once"&&i.push(u),u.callback(e,r,n)}}catch(d){o={error:d}}finally{try{c&&!c.done&&(s=a.return)&&s.call(a)}finally{if(o)throw o.error}}this.interceptors.postResolution.setAll(e,i)}},t.prototype.resolveRegistration=function(e,r){if(this.ensureNotDisposed(),e.options.lifecycle===nt.ResolutionScoped&&r.scopedResolutions.has(e))return r.scopedResolutions.get(e);var n=e.options.lifecycle===nt.Singleton,o=e.options.lifecycle===nt.ContainerScoped,s=n||o,i;return mi(e.provider)?i=e.provider.useValue:hi(e.provider)?i=s?e.instance||(e.instance=this.resolve(e.provider.useToken,r)):this.resolve(e.provider.useToken,r):qv(e.provider)?i=s?e.instance||(e.instance=this.construct(e.provider.useClass,r)):this.construct(e.provider.useClass,r):dl(e.provider)?i=e.provider.useFactory(this):i=this.construct(e.provider,r),e.options.lifecycle===nt.ResolutionScoped&&r.scopedResolutions.set(e,i),i},t.prototype.resolveAll=function(e,r,n){var o=this;r===void 0&&(r=new si),n===void 0&&(n=!1),this.ensureNotDisposed();var s=this.getAllRegistrations(e);if(!s&&Mn(e)){if(n)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),s){var i=s.map(function(c){return o.resolveRegistration(c,r)});return this.executePostResolutionInterceptor(e,i,"All"),i}var a=[this.construct(e,r)];return this.executePostResolutionInterceptor(e,a,"All"),a},t.prototype.isRegistered=function(e,r){return r===void 0&&(r=!1),this.ensureNotDisposed(),this._registry.has(e)||r&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},t.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},t.prototype.clearInstances=function(){var e,r;this.ensureNotDisposed();try{for(var n=oi(this._registry.entries()),o=n.next();!o.done;o=n.next()){var s=sa(o.value,2),i=s[0],a=s[1];this._registry.setAll(i,a.filter(function(c){return!mi(c.provider)}).map(function(c){return c.instance=void 0,c}))}}catch(c){e={error:c}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}},t.prototype.createChildContainer=function(){var e,r;this.ensureNotDisposed();var n=new t(this);try{for(var o=oi(this._registry.entries()),s=o.next();!s.done;s=o.next()){var i=sa(s.value,2),a=i[0],c=i[1];c.some(function(u){var d=u.options;return d.lifecycle===nt.ContainerScoped})&&n._registry.setAll(a,c.map(function(u){return u.options.lifecycle===nt.ContainerScoped?{provider:u.provider,options:u.options}:u}))}}catch(u){e={error:u}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return n},t.prototype.beforeResolution=function(e,r,n){n===void 0&&(n={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:r,options:n})},t.prototype.afterResolution=function(e,r,n){n===void 0&&(n={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:r,options:n})},t.prototype.dispose=function(){return Nx(this,void 0,void 0,function(){var e;return Tx(this,function(r){switch(r.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(n){var o=n.dispose();o&&e.push(o)}),[4,Promise.all(e)];case 1:return r.sent(),[2]}})})},t.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},t.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},t.prototype.construct=function(e,r){var n=this;if(e instanceof zv)return e.createProxy(function(s){return n.resolve(s,r)});var o=(function(){var s=Yv.get(e);if(!s||s.length===0){if(e.length===0)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var i=s.map(n.resolveParams(r,e));return new(e.bind.apply(e,Zr([void 0],i)))})();return Ux(o)&&this.disposables.add(o),o},t.prototype.resolveParams=function(e,r){var n=this;return function(o,s){var i,a,c;try{return Rx(o)?ih(o)?o.multiple?(i=n.resolve(o.transform)).transform.apply(i,Zr([n.resolveAll(o.token,new si,o.isOptional)],o.transformArgs)):(a=n.resolve(o.transform)).transform.apply(a,Zr([n.resolve(o.token,e,o.isOptional)],o.transformArgs)):o.multiple?n.resolveAll(o.token,new si,o.isOptional):n.resolve(o.token,e,o.isOptional):ih(o)?(c=n.resolve(o.transform,e)).transform.apply(c,Zr([n.resolve(o.token,e)],o.transformArgs)):n.resolve(o,e)}catch(u){throw new Error(Px(r,s,u))}}},t.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},t})(),Le=new Wx;function ko(t){return function(e){Yv.set(e,Bx(e))}}if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var fl;class fc{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}}f([y({type:b.ObjectIdentifier})],fc.prototype,"attrId",void 0);f([y({type:b.Any,repeated:"set"})],fc.prototype,"attrValues",void 0);let ah=fl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,fl.prototype)}};ah=fl=f([j({type:R.Sequence,itemType:fc})],ah);var pl;let ch=pl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,pl.prototype)}};ch=pl=f([j({type:R.Sequence,itemType:wo})],ch);class Xv{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Xv.prototype,"certId",void 0);f([y({type:b.Any,context:0})],Xv.prototype,"certValue",void 0);class Jv{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Jv.prototype,"crlId",void 0);f([y({type:b.Any,context:0})],Jv.prototype,"crltValue",void 0);class Zv extends he{}let pc=class{encryptionAlgorithm=new W;encryptedData=new Zv;constructor(e={}){Object.assign(this,e)}};f([y({type:W})],pc.prototype,"encryptionAlgorithm",void 0);f([y({type:Zv})],pc.prototype,"encryptedData",void 0);var hl,ml;(function(t){t[t.v1=0]="v1"})(ml||(ml={}));class Qv extends he{}let ia=hl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,hl.prototype)}};ia=hl=f([j({type:R.Sequence,itemType:gr})],ia);let qs=class{version=ml.v1;privateKeyAlgorithm=new W;privateKey=new Qv;attributes;constructor(e={}){Object.assign(this,e)}};f([y({type:b.Integer})],qs.prototype,"version",void 0);f([y({type:W})],qs.prototype,"privateKeyAlgorithm",void 0);f([y({type:Qv})],qs.prototype,"privateKey",void 0);f([y({type:ia,implicit:!0,context:0,optional:!0})],qs.prototype,"attributes",void 0);let uh=class extends qs{};uh=f([j({type:R.Sequence})],uh);let lh=class extends pc{};lh=f([j({type:R.Sequence})],lh);class eb{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],eb.prototype,"secretTypeId",void 0);f([y({type:b.Any,context:0})],eb.prototype,"secretValue",void 0);class zs{mac=new lc;macSalt=new he;iterations=1;constructor(e={}){Object.assign(this,e)}}f([y({type:lc})],zs.prototype,"mac",void 0);f([y({type:he})],zs.prototype,"macSalt",void 0);f([y({type:b.Integer,defaultValue:1})],zs.prototype,"iterations",void 0);class hc{version=3;authSafe=new wo;macData=new zs;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],hc.prototype,"version",void 0);f([y({type:wo})],hc.prototype,"authSafe",void 0);f([y({type:zs,optional:!0})],hc.prototype,"macData",void 0);var yl;class mc{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],mc.prototype,"bagId",void 0);f([y({type:b.Any,context:0})],mc.prototype,"bagValue",void 0);f([y({type:fc,repeated:"set",optional:!0})],mc.prototype,"bagAttributes",void 0);let dh=yl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,yl.prototype)}};dh=yl=f([j({type:R.Sequence,itemType:mc})],dh);var gl,vl,bl;const tb="1.2.840.113549.1.9",rb=`${tb}.7`,of=`${tb}.14`;let aa=class extends Ge{ia5String;constructor(e={}){super(e)}toString(){return this.ia5String||super.toString()}};f([y({type:b.IA5String})],aa.prototype,"ia5String",void 0);aa=f([j({type:R.Choice})],aa);let fh=class extends wo{};fh=f([j({type:R.Sequence})],fh);let ph=class extends hc{};ph=f([j({type:R.Sequence})],ph);let hh=class extends pc{};hh=f([j({type:R.Sequence})],hh);let wl=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([y({type:b.IA5String})],wl.prototype,"value",void 0);wl=f([j({type:R.Choice})],wl);let mh=class extends aa{};mh=f([j({type:R.Choice})],mh);let yh=class extends Ge{};yh=f([j({type:R.Choice})],yh);let Al=class{value;constructor(e=new Date){this.value=e}};f([y({type:b.GeneralizedTime})],Al.prototype,"value",void 0);Al=f([j({type:R.Choice})],Al);let gh=class extends Ge{};gh=f([j({type:R.Choice})],gh);let Sl=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};f([y({type:b.PrintableString})],Sl.prototype,"value",void 0);Sl=f([j({type:R.Choice})],Sl);let ca=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([y({type:b.PrintableString})],ca.prototype,"value",void 0);ca=f([j({type:R.Choice})],ca);let vh=class extends ca{};vh=f([j({type:R.Choice})],vh);let bh=class extends Ge{};bh=f([j({type:R.Choice})],bh);let kl=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([y({type:b.ObjectIdentifier})],kl.prototype,"value",void 0);kl=f([j({type:R.Choice})],kl);let wh=class extends We{};wh=f([j({type:R.Choice})],wh);let El=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};f([y({type:b.Integer})],El.prototype,"value",void 0);El=f([j({type:R.Choice})],El);let Ah=class extends sr{};Ah=f([j({type:R.Sequence})],Ah);let ua=class extends Ge{};ua=f([j({type:R.Choice})],ua);let Sh=gl=class extends Dr{constructor(e){super(e),Object.setPrototypeOf(this,gl.prototype)}};Sh=gl=f([j({type:R.Sequence})],Sh);let kh=vl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,vl.prototype)}};kh=vl=f([j({type:R.Set,itemType:bo})],kh);let xl=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([y({type:b.BmpString})],xl.prototype,"value",void 0);xl=f([j({type:R.Choice})],xl);let Il=class extends W{};Il=f([j({type:R.Sequence})],Il);let Eh=bl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,bl.prototype)}};Eh=bl=f([j({type:R.Sequence,itemType:Il})],Eh);var Ol,Cl;let xh=Ol=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Ol.prototype)}};xh=Ol=f([j({type:R.Sequence,itemType:W})],xh);let Ih=Cl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Cl.prototype)}};Ih=Cl=f([j({type:R.Sequence,itemType:b.BitString})],Ih);var Nl,Tl;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2"})(Tl||(Tl={}));let Oh=class extends W{};Oh=f([j({type:R.Sequence})],Oh);let er=class{version=Tl.v1;privateKeyAlgorithm=new W;privateKey=new ArrayBuffer(0);attributes;publicKey};f([y({type:b.Integer})],er.prototype,"version",void 0);f([y({type:W})],er.prototype,"privateKeyAlgorithm",void 0);f([y({type:b.OctetString})],er.prototype,"privateKey",void 0);f([y({type:ia,context:0,implicit:!0,optional:!0})],er.prototype,"attributes",void 0);f([y({type:b.BitString,context:1,implicit:!0,optional:!0})],er.prototype,"publicKey",void 0);er=f([j({type:R.Sequence})],er);let Ch=class extends er{};Ch=f([j({type:R.Sequence})],Ch);let Nh=Nl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Nl.prototype)}};Nh=Nl=f([j({type:R.Sequence,itemType:er})],Nh);var $l,Bl;let Th=class extends W{};Th=f([j({type:R.Sequence})],Th);let $h=$l=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,$l.prototype)}};$h=$l=f([j({type:R.Sequence,itemType:Ot})],$h);let Bh=Bl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Bl.prototype)}};Bh=Bl=f([j({type:R.Sequence,itemType:er})],Bh);const tt="2.16.840.1.101.3.4.3",Rh=`${tt}.17`,Mh=`${tt}.18`,_h=`${tt}.19`,jh=`${tt}.20`,Dh=`${tt}.21`,Lh=`${tt}.22`,Ph=`${tt}.23`,Uh=`${tt}.24`,Vh=`${tt}.25`,Hh=`${tt}.26`,Fh=`${tt}.27`,Wh=`${tt}.28`,Kh=`${tt}.29`,Gh=`${tt}.30`,qh=`${tt}.31`;var Rl;let la=Rl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Rl.prototype)}};la=Rl=f([j({type:R.Sequence,itemType:gr})],la);class Eo{version=0;subject=new Re;subjectPKInfo=new Ot;attributes=new la;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Eo.prototype,"version",void 0);f([y({type:Re})],Eo.prototype,"subject",void 0);f([y({type:Ot})],Eo.prototype,"subjectPKInfo",void 0);f([y({type:la,implicit:!0,context:0,optional:!0})],Eo.prototype,"attributes",void 0);class Es{certificationRequestInfo=new Eo;certificationRequestInfoRaw;signatureAlgorithm=new W;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:Eo,raw:!0})],Es.prototype,"certificationRequestInfo",void 0);f([y({type:W})],Es.prototype,"signatureAlgorithm",void 0);f([y({type:b.BitString})],Es.prototype,"signature",void 0);const Tn="crypto.algorithm";class Kx{getAlgorithms(){return Le.resolveAll(Tn)}toAsnAlgorithm(e){const r={...e};r.hash&&typeof r.hash=="string"&&(r.hash={name:r.hash});for(const n of this.getAlgorithms()){const o=n.toAsnAlgorithm(r);if(o)return o}if(/^[0-9.]+$/.test(e.name)){const n=new W({algorithm:e.name});if("parameters"in e){const o=e;n.parameters=o.parameters}return n}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(const n of this.getAlgorithms()){const o=n.toWebAlgorithm(e);if(o)return o}return{name:e.algorithm,parameters:e.parameters}}}const An="crypto.algorithmProvider";Le.registerSingleton(An,Kx);var yi;const lt="1.3.36.3.3.2.8.1.1",zh=`${lt}.1`,Yh=`${lt}.2`,Xh=`${lt}.3`,Jh=`${lt}.4`,Zh=`${lt}.5`,Qh=`${lt}.6`,em=`${lt}.7`,tm=`${lt}.8`,rm=`${lt}.9`,nm=`${lt}.10`,om=`${lt}.11`,sm=`${lt}.12`,im=`${lt}.13`,am=`${lt}.14`,cm="brainpoolP160r1",um="brainpoolP160t1",lm="brainpoolP192r1",dm="brainpoolP192t1",fm="brainpoolP224r1",pm="brainpoolP224t1",hm="brainpoolP256r1",mm="brainpoolP256t1",ym="brainpoolP320r1",gm="brainpoolP320t1",vm="brainpoolP384r1",bm="brainpoolP384t1",wm="brainpoolP512r1",Am="brainpoolP512t1",Oe="ECDSA";let xs=yi=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case Oe.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return mx;case"sha-256":return yx;case"sha-384":return gx;case"sha-512":return vx}else if("namedCurve"in e){let r="";switch(e.namedCurve){case"P-256":r=nh;break;case"K-256":r=yi.SECP256K1;break;case"P-384":r=oh;break;case"P-521":r=sh;break;case cm:r=zh;break;case um:r=Yh;break;case lm:r=Xh;break;case dm:r=Jh;break;case fm:r=Zh;break;case pm:r=Qh;break;case hm:r=em;break;case mm:r=tm;break;case ym:r=rm;break;case gm:r=nm;break;case vm:r=om;break;case bm:r=sm;break;case wm:r=im;break;case Am:r=am;break}if(r)return new W({algorithm:Ss,parameters:H.serialize(new Pr({namedCurve:r}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case Jd:return{name:Oe,hash:{name:"SHA-1"}};case Zd:return{name:Oe,hash:{name:"SHA-256"}};case Qd:return{name:Oe,hash:{name:"SHA-384"}};case ef:return{name:Oe,hash:{name:"SHA-512"}};case Ss:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(H.parse(e.parameters,Pr).namedCurve){case nh:return{name:Oe,namedCurve:"P-256"};case yi.SECP256K1:return{name:Oe,namedCurve:"K-256"};case oh:return{name:Oe,namedCurve:"P-384"};case sh:return{name:Oe,namedCurve:"P-521"};case zh:return{name:Oe,namedCurve:cm};case Yh:return{name:Oe,namedCurve:um};case Xh:return{name:Oe,namedCurve:lm};case Jh:return{name:Oe,namedCurve:dm};case Zh:return{name:Oe,namedCurve:fm};case Qh:return{name:Oe,namedCurve:pm};case em:return{name:Oe,namedCurve:hm};case tm:return{name:Oe,namedCurve:mm};case rm:return{name:Oe,namedCurve:ym};case nm:return{name:Oe,namedCurve:gm};case om:return{name:Oe,namedCurve:vm};case sm:return{name:Oe,namedCurve:bm};case im:return{name:Oe,namedCurve:wm};case am:return{name:Oe,namedCurve:Am}}}}return null}};xs.SECP256K1="1.3.132.0.10";xs=yi=f([ko()],xs);Le.registerSingleton(Tn,xs);const nb=Symbol("name"),ob=Symbol("value");class me{constructor(e,r={},n=""){this[nb]=e,this[ob]=n;for(const o in r)this[o]=r[o]}}me.NAME=nb;me.VALUE=ob;class Gx{static toTextObject(e){const r=new me("Algorithm Identifier",{},Wr.toString(e.algorithm));if(e.parameters)if(e.algorithm===Ss){const n=new xs().toWebAlgorithm(e);n&&"namedCurve"in n?r["Named Curve"]=n.namedCurve:r.Parameters=e.parameters}else r.Parameters=e.parameters;return r}}class Wr{static toString(e){const r=this.items[e];return r||e}}Wr.items={[ta]:"sha1",[Wv]:"sha224",[ra]:"sha256",[na]:"sha384",[oa]:"sha512",[vn]:"rsaEncryption",[Zi]:"sha1WithRSAEncryption",[Ex]:"sha224WithRSAEncryption",[il]:"sha256WithRSAEncryption",[Qi]:"sha384WithRSAEncryption",[ea]:"sha512WithRSAEncryption",[Ss]:"ecPublicKey",[Jd]:"ecdsaWithSHA1",[Vv]:"ecdsaWithSHA224",[Zd]:"ecdsaWithSHA256",[Qd]:"ecdsaWithSHA384",[ef]:"ecdsaWithSHA512",[cx]:"TLS WWW server authentication",[ux]:"TLS WWW client authentication",[lx]:"Code Signing",[dx]:"E-mail Protection",[fx]:"Time Stamping",[px]:"OCSP Signing",[hx]:"Signed Data"};class Sn{static serialize(e){return this.serializeObj(e).join(`
118
+ `)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,r=0){const n=[];let o=this.pad(r++),s="";const i=e[me.VALUE];i&&(s=` ${i}`),n.push(`${o}${e[me.NAME]}:${s}`),o=this.pad(r);for(const a in e){if(typeof a=="symbol")continue;const c=e[a],u=a?`${a}: `:"";if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")n.push(`${o}${u}${c}`);else if(c instanceof Date)n.push(`${o}${u}${c.toUTCString()}`);else if(Array.isArray(c))for(const d of c)d[me.NAME]=a,n.push(...this.serializeObj(d,r));else if(c instanceof me)c[me.NAME]=a,n.push(...this.serializeObj(c,r));else if(K.isBufferSource(c))a?(n.push(`${o}${u}`),n.push(...this.serializeBufferSource(c,r+1))):n.push(...this.serializeBufferSource(c,r));else if("toTextObject"in c){const d=c.toTextObject();d[me.NAME]=a,n.push(...this.serializeObj(d,r))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return n}static serializeBufferSource(e,r=0){const n=this.pad(r),o=K.toUint8Array(e),s=[];for(let i=0;i<o.length;){const a=[];for(let c=0;c<16&&i<o.length;c++){c===8&&a.push("");const u=o[i++].toString(16).padStart(2,"0");a.push(u)}s.push(`${n}${a.join(" ")}`)}return s}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}Sn.oidSerializer=Wr;Sn.algorithmSerializer=Gx;var _n,jn;class Kr{get parseOptions(){return oe(this,jn,"f")}get rawData(){return oe(this,_n,"f")||ke(this,_n,H.serialize(this.asn),"f"),oe(this,_n,"f")}constructor(...e){_n.set(this,void 0),jn.set(this,void 0),K.isBufferSource(e[0])?(ke(this,jn,e[2],"f"),this.asn=H.parse(e[0],e[1],e[2]),ke(this,_n,K.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(ke(this,jn,e[1],"f"),this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof Kr?bk(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return H.toString(this.rawData,oe(this,jn,"f"));case"text":return Sn.serialize(this.toTextObject());case"hex":return ee.ToHex(this.rawData);case"base64":return ee.ToBase64(this.rawData);case"base64url":return ee.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new me(this.getTextName(),{},e)}}_n=new WeakMap,jn=new WeakMap;Kr.NAME="ASN";class St extends Kr{constructor(...e){let r,n;K.isBufferSource(e[0])?(r=K.toArrayBuffer(e[0]),n=e[1]):r=H.serialize(new Vt({extnID:e[0],critical:e[1],extnValue:new he(K.toArrayBuffer(e[2]))})),super(r,Vt,n)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[me.NAME]===St.NAME&&(e[me.NAME]=Wr.toString(this.type)),e}}var sb;class $r{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[sb]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set($r.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set($r.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,r){return this.items.forEach(e,r)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=$r.DEFAULT){const r=this.items.get(e.toLowerCase());if(!r)throw new Error(`Cannot get Crypto by name '${e}'`);return r}set(e,r){if(typeof e=="string"){if(!r)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),r)}else this.items.set($r.DEFAULT,e);return this}}sb=Symbol.toStringTag;$r.DEFAULT="default";const at=new $r,qx=/^[0-2](?:\.[1-9][0-9]*)+$/;function zx(t){return new RegExp(qx).test(t)}class ib{constructor(e={}){this.items={};for(const r in e)this.register(r,e[r])}get(e){return this.items[e]||null}findId(e){return zx(e)?e:this.get(e)}register(e,r){this.items[e]=r,this.items[r]=e}}const ct=new ib;ct.register("CN","2.5.4.3");ct.register("L","2.5.4.7");ct.register("ST","2.5.4.8");ct.register("O","2.5.4.10");ct.register("OU","2.5.4.11");ct.register("C","2.5.4.6");ct.register("DC","0.9.2342.19200300.100.1.25");ct.register("E","1.2.840.113549.1.9.1");ct.register("G","2.5.4.42");ct.register("I","2.5.4.43");ct.register("SN","2.5.4.4");ct.register("T","2.5.4.12");function Yx(t,e){return`\\${ee.ToHex(ee.FromUtf8String(e)).toUpperCase()}`}function Xx(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,Yx)}class Dt{static isASCII(e){for(let r=0;r<e.length;r++)if(e.charCodeAt(r)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,r={}){this.extraNames=new ib,this.asn=new Re;for(const n in r)if(Object.prototype.hasOwnProperty.call(r,n)){const o=r[n];this.extraNames.register(n,o)}typeof e=="string"?this.asn=this.fromString(e):e instanceof Re?this.asn=e:K.isBufferSource(e)?this.asn=H.parse(e,Re):this.asn=this.fromJSON(e)}getField(e){const r=this.extraNames.findId(e)||ct.findId(e),n=[];for(const o of this.asn)for(const s of o)s.type===r&&n.push(s.value.toString());return n}getName(e){return this.extraNames.get(e)||ct.get(e)}toString(){return this.asn.map(e=>e.map(r=>{const n=this.getName(r.type)||r.type,o=r.value.anyValue?`#${ee.ToHex(r.value.anyValue)}`:Xx(r.value.toString());return`${n}=${o}`}).join("+")).join(", ")}toJSON(){var e;const r=[];for(const n of this.asn){const o={};for(const s of n){const i=this.getName(s.type)||s.type;(e=o[i])!==null&&e!==void 0||(o[i]=[]),o[i].push(s.value.anyValue?`#${ee.ToHex(s.value.anyValue)}`:s.value.toString())}r.push(o)}return r}fromString(e){const r=new Re,n=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let o=null,s=",";for(;o=n.exec(`${e},`);){let[,i,a]=o;const c=a[a.length-1];(c===","||c==="+")&&(a=a.slice(0,a.length-1),o[3]=c);const u=o[3];i=this.getTypeOid(i);const d=this.createAttribute(i,a);s==="+"?r[r.length-1].push(d):r.push(new ro([d])),s=u}return r}fromJSON(e){const r=new Re;for(const n of e){const o=new ro;for(const s in n){const i=this.getTypeOid(s),a=n[s];for(const c of a){const u=this.createAttribute(i,c);o.push(u)}}r.push(o)}return r}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,r){const n=new Ga({type:e});if(typeof r=="object")for(const o in r)switch(o){case"ia5String":n.value.ia5String=r[o];break;case"utf8String":n.value.utf8String=r[o];break;case"universalString":n.value.universalString=r[o];break;case"bmpString":n.value.bmpString=r[o];break;case"printableString":n.value.printableString=r[o];break}else if(r[0]==="#")n.value.anyValue=ee.FromHex(r.slice(1));else{const o=this.processStringValue(r);e===this.getName("E")||e===this.getName("DC")?n.value.ia5String=o:Dt.isPrintableString(o)?n.value.printableString=o:n.value.utf8String=o}return n}processStringValue(e){const r=/"(.*?[^\\])?"/.exec(e);return r&&(e=r[1]),e.replace(/\\0a/gi,`
119
+ `).replace(/\\0d/gi,"\r").replace(/\\0g/gi," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return H.serialize(this.asn)}async getThumbprint(e,r){let n,o="SHA-1";return e&&(typeof e=="object"&&"subtle"in e?n=e:(o=e,n=r)),n??(n=at.get()),await n.subtle.digest(o,this.toArrayBuffer())}}const ab="Cannot initialize GeneralName from ASN.1 data.",Sm=`${ab} Unsupported string format in use.`,Jx=`${ab} Value doesn't match to GUID regular expression.`,km=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Em="1.3.6.1.4.1.311.25.1",xm="1.3.6.1.4.1.311.20.2.3",Wc="dns",Kc="dn",Gc="email",qc="ip",zc="url",Yc="guid",Xc="upn",ii="id";class Br extends Kr{constructor(...e){let r;if(e.length===2)switch(e[0]){case Kc:{const n=new Dt(e[1]).toArrayBuffer(),o=H.parse(n,Re);r=new ie({directoryName:o});break}case Wc:r=new ie({dNSName:e[1]});break;case Gc:r=new ie({rfc822Name:e[1]});break;case Yc:{const n=new RegExp(km,"i").exec(e[1]);if(!n)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const o=n.slice(1).map((s,i)=>i<3?ee.ToHex(new Uint8Array(ee.FromHex(s)).reverse()):s).join("");r=new ie({otherName:new vs({typeId:Em,value:H.serialize(new he(ee.FromHex(o)))})});break}case qc:r=new ie({iPAddress:e[1]});break;case ii:r=new ie({registeredID:e[1]});break;case Xc:{r=new ie({otherName:new vs({typeId:xm,value:H.serialize(kv.toASN(e[1]))})});break}case zc:r=new ie({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else K.isBufferSource(e[0])?r=H.parse(e[0],ie):r=e[0];super(r)}onInit(e){if(e.dNSName!=null)this.type=Wc,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Gc,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=qc,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=zc,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=ii,this.value=e.registeredID;else if(e.directoryName!=null)this.type=Kc,this.value=new Dt(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===Em){this.type=Yc;const r=H.parse(e.otherName.value,he),n=new RegExp(km,"i").exec(ee.ToHex(r));if(!n)throw new Error(Jx);this.value=n.slice(1).map((o,s)=>s<3?ee.ToHex(new Uint8Array(ee.FromHex(o)).reverse()):o).join("-")}else if(e.otherName.typeId===xm)this.type=Xc,this.value=H.parse(e.otherName.value,Ge).toString();else throw new Error(Sm);else throw new Error(Sm)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case Kc:case Wc:case Yc:case qc:case ii:case Xc:case zc:e=this.type.toUpperCase();break;case Gc:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let r=this.value;return this.type===ii&&(r=Wr.toString(r)),new me(e,void 0,r)}}class kn extends Kr{constructor(e){let r;if(e instanceof Ye)r=e;else if(Array.isArray(e)){const n=[];for(const o of e)if(o instanceof ie)n.push(o);else{const s=H.parse(new Br(o.type,o.value).rawData,ie);n.push(s)}r=new Ye(n)}else if(K.isBufferSource(e))r=H.parse(e,Ye);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(r)}onInit(e){const r=[];for(const n of e){let o=null;try{o=new Br(n)}catch{continue}r.push(o)}this.items=r}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){const e=super.toTextObjectEmpty();for(const r of this.items){const n=r.toTextObject();let o=e[n[me.NAME]];Array.isArray(o)||(o=[],e[n[me.NAME]]=o),o.push(n)}return e}}kn.NAME="GeneralNames";const is="-{5}",Is="\\n",Zx=`[^${Is}]+`,Qx=`${is}BEGIN (${Zx}(?=${is}))${is}`,eI=`${is}END \\1${is}`,lo="\\n",tI=`[^:${Is}]+`,rI=`(?:[^${Is}]+${lo}(?: +[^${Is}]+${lo})*)`,nI="[a-zA-Z0-9=+/]+",oI=`(?:${nI}${lo})+`,Im=`${Qx}${lo}(?:((?:${tI}: ${rI})+))?${lo}?(${oI})${eI}`,sI=new RegExp(`[${Is}]+`,"g");class gt{static isPem(e){return typeof e=="string"&&new RegExp(Im,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const r=new RegExp(Im,"g"),n=[];let o=null;for(;o=r.exec(e);){const s=o[3].replace(sI,""),i={type:o[1],headers:[],rawData:ee.FromBase64(s)},a=o[2];if(a){const c=a.split(new RegExp(lo,"g"));let u=null;for(const d of c){const[l,m]=d.split(/:(.*)/);if(m===void 0){if(!u)throw new Error("Cannot parse PEM string. Incorrect header value");u.value+=l.trim()}else u&&i.headers.push(u),u={key:l,value:m.trim()}}u&&i.headers.push(u)}n.push(i)}return n}static decode(e){return this.decodeWithHeaders(e).map(n=>n.rawData)}static decodeFirst(e){const r=this.decode(e);if(!r.length)throw new RangeError("PEM string doesn't contain any objects");return r[0]}static encode(e,r){if(Array.isArray(e)){const n=new Array;return r?e.forEach(o=>{if(!K.isBufferSource(o))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");n.push(this.encodeStruct({type:r,rawData:K.toArrayBuffer(o)}))}):e.forEach(o=>{if(!("type"in o))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");n.push(this.encodeStruct(o))}),n.join(`
120
+ `)}else{if(!r)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:r,rawData:K.toArrayBuffer(e)})}}static encodeStruct(e){var r;const n=e.type.toLocaleUpperCase(),o=[];if(o.push(`-----BEGIN ${n}-----`),!((r=e.headers)===null||r===void 0)&&r.length){for(const i of e.headers)o.push(`${i.key}: ${i.value}`);o.push("")}const s=ee.ToBase64(e.rawData);for(let i=0;i<s.length;i+=64)o.push(s.substring(i,i+64));return o.push(`-----END ${n}-----`),o.join(`
121
+ `)}}gt.CertificateTag="CERTIFICATE";gt.CrlTag="CRL";gt.CertificateRequestTag="CERTIFICATE REQUEST";gt.PublicKeyTag="PUBLIC KEY";gt.PrivateKeyTag="PRIVATE KEY";class wr extends Kr{static isAsnEncoded(e){return K.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(gt.isPem(e))return gt.decode(e)[0];if(ee.isHex(e))return ee.FromHex(e);if(ee.isBase64(e))return ee.FromBase64(e);if(ee.isBase64Url(e))return ee.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{const r=K.toUint8Array(e);if(r.length>0&&r[0]===48)return K.toArrayBuffer(e);const n=ee.ToBinary(e);if(gt.isPem(n))return gt.decode(n)[0];if(ee.isHex(n))return ee.FromHex(n);if(ee.isBase64(n))return ee.FromBase64(n);if(ee.isBase64Url(n))return ee.FromBase64Url(n);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){wr.isAsnEncoded(e[0])?super(wr.toArrayBuffer(e[0]),e[1],e[2]):super(e[0],e[1])}toString(e="pem"){return e==="pem"?gt.encode(this.rawData,this.tag):super.toString(e)}}class Ut extends wr{static async create(e,r=at.get()){if(e instanceof Ut)return e;if($r.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");const n=await r.subtle.exportKey("spki",e);return new Ut(n)}else{if(e.publicKey)return e.publicKey;if(K.isBufferSource(e))return new Ut(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e,r){wr.isAsnEncoded(e)?super(e,Ot,r):super(e,r),this.tag=gt.PublicKeyTag}async export(e,r,n){let o,s=["verify"],i={hash:"SHA-256",...this.algorithm};r?(i=e,s=r,o=n):o=e,o??(o=at.get());let a=this.rawData;const c=H.parse(this.rawData,Ot,this.parseOptions);return c.algorithm.algorithm===ss&&(a=iI(c,a)),o.subtle.importKey("spki",a,i,!0,s)}onInit(e){const r=Le.resolve(An),n=this.algorithm=r.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===vn){const o=H.parse(e.subjectPublicKey,tf,this.parseOptions),s=K.toUint8Array(o.modulus);n.publicExponent=K.toUint8Array(o.publicExponent),n.modulusLength=(s[0]?s:s.slice(1)).byteLength<<3}}async getThumbprint(e,r){let n,o="SHA-1";return e&&(typeof e=="object"&&"subtle"in e?n=e:(o=e,n=r)),n??(n=at.get()),await n.subtle.digest(o,this.rawData)}async getKeyIdentifier(e,r){let n,o="SHA-1";e&&(typeof e=="object"&&"subtle"in e?n=e:(o=e,n=r)),n??(n=at.get());const s=H.parse(this.rawData,Ot,this.parseOptions);return await n.subtle.digest(o,s.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),r=H.parse(this.rawData,Ot,this.parseOptions);switch(e.Algorithm=Sn.serializeAlgorithm(r.algorithm),r.algorithm.algorithm){case Ss:e["EC Point"]=r.subjectPublicKey;break;case vn:default:e["Raw Data"]=r.subjectPublicKey}return e}}function iI(t,e){return t.algorithm=new W({algorithm:vn,parameters:null}),e=H.serialize(t),e}class En extends St{static async create(e,r=!1,n=at.get()){if("name"in e&&"serialNumber"in e)return new En(e,r);const s=await(await Ut.create(e,n)).getKeyIdentifier(n);return new En(ee.ToHex(s),r)}constructor(...e){if(K.isBufferSource(e[0]))super(e[0],e[1]);else if(typeof e[0]=="string"){const r=new Qr({keyIdentifier:new jd(ee.FromHex(e[0]))});super(Eu,e[1],H.serialize(r))}else{const r=e[0],n=r.name instanceof kn?H.parse(r.name.rawData,Ye):r.name,o=new Qr({authorityCertIssuer:n,authorityCertSerialNumber:ee.FromHex(r.serialNumber)});super(Eu,e[1],H.serialize(o))}}onInit(e){super.onInit(e);const r=H.parse(e.extnValue,Qr,this.parseOptions);r.keyIdentifier&&(this.keyId=ee.ToHex(r.keyIdentifier)),(r.authorityCertIssuer||r.authorityCertSerialNumber)&&(this.certId={name:r.authorityCertIssuer||[],serialNumber:r.authorityCertSerialNumber?ee.ToHex(r.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),r=H.parse(this.value,Qr,this.parseOptions);return r.authorityCertIssuer&&(e["Authority Issuer"]=new kn(r.authorityCertIssuer).toTextObject()),r.authorityCertSerialNumber&&(e["Authority Serial Number"]=r.authorityCertSerialNumber),r.keyIdentifier&&(e[""]=r.keyIdentifier),e}}En.NAME="Authority Key Identifier";class Os extends St{constructor(...e){if(K.isBufferSource(e[0])){super(e[0],e[1]);const r=H.parse(this.value,Mi,this.parseOptions);this.ca=r.cA,this.pathLength=r.pathLenConstraint}else{const r=new Mi({cA:e[0],pathLenConstraint:e[1]});super(xv,e[2],H.serialize(r)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}}Os.NAME="Basic Constraints";var Om;(function(t){t.serverAuth="1.3.6.1.5.5.7.3.1",t.clientAuth="1.3.6.1.5.5.7.3.2",t.codeSigning="1.3.6.1.5.5.7.3.3",t.emailProtection="1.3.6.1.5.5.7.3.4",t.timeStamping="1.3.6.1.5.5.7.3.8",t.ocspSigning="1.3.6.1.5.5.7.3.9"})(Om||(Om={}));class yc extends St{constructor(...e){if(K.isBufferSource(e[0])){super(e[0],e[1]);const r=H.parse(this.value,Li,this.parseOptions);this.usages=r.map(n=>n)}else{const r=new Li(e[0]);super(Cv,e[1],H.serialize(r)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(r=>Wr.toString(r)).join(", "),e}}yc.NAME="Extended Key Usages";var zn;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(zn||(zn={}));class Cs extends St{constructor(...e){if(K.isBufferSource(e[0])){super(e[0],e[1]);const r=H.parse(this.value,Fc,this.parseOptions);this.usages=r.toNumber()}else{const r=new Fc(e[0]);super(Tv,e[1],H.serialize(r)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=H.parse(this.value,Fc,this.parseOptions);return e[""]=r.toJSON().join(", "),e}}Cs.NAME="Key Usages";class Ys extends St{static async create(e,r=!1,n=at.get()){const s=await(await Ut.create(e,n)).getKeyIdentifier(n);return new Ys(ee.ToHex(s),r)}constructor(...e){if(K.isBufferSource(e[0])){super(e[0],e[1]);const r=H.parse(this.value,Mr,this.parseOptions);this.keyId=ee.ToHex(r)}else{const r=typeof e[0]=="string"?ee.FromHex(e[0]):e[0],n=new Mr(r);super(Mv,e[1],H.serialize(n)),this.keyId=ee.ToHex(r)}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=H.parse(this.value,Mr,this.parseOptions);return e[""]=r,e}}Ys.NAME="Subject Key Identifier";class sf extends St{constructor(...e){K.isBufferSource(e[0])?super(e[0],e[1]):super(Rv,e[1],new kn(e[0]||[]).rawData)}onInit(e){super.onInit(e);const r=H.parse(e.extnValue,Pu,this.parseOptions);this.names=new kn(r)}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(const n in r)e[n]=r[n];return e}}sf.NAME="Subject Alternative Name";class kt{static register(e,r){this.items.set(e,r)}static create(e,r){const n=new St(e,r),o=this.items.get(n.type);return o?new o(e,r):n}}kt.items=new Map;class cb extends St{constructor(...e){var r;if(K.isBufferSource(e[0])){super(e[0],e[1]);const n=H.parse(this.value,ji,this.parseOptions);this.policies=n.map(o=>o.policyIdentifier)}else{const n=e[0],o=(r=e[1])!==null&&r!==void 0?r:!1,s=new ji(n.map(i=>new za({policyIdentifier:i})));super(Iv,o,H.serialize(s)),this.policies=n}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(r=>new me("",{},Wr.toString(r))),e}}cb.NAME="Certificate Policies";kt.register(Iv,cb);class ub extends St{constructor(...e){var r;if(K.isBufferSource(e[0]))super(e[0],e[1]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){const o=e[0].map(i=>new go({distributionPoint:new hn({fullName:[new ie({uniformResourceIdentifier:i})]})})),s=new qn(o);super(Nu,e[1],H.serialize(s))}else{const n=new qn(e[0]);super(Nu,e[1],H.serialize(n))}(r=this.distributionPoints)!==null&&r!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);const r=H.parse(e.extnValue,qn,this.parseOptions);this.distributionPoints=r}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(r=>{var n;const o=new me("");return!((n=r.distributionPoint)===null||n===void 0)&&n.fullName&&(o[""]=r.distributionPoint.fullName.map(s=>new Br(s).toString()).join(", ")),r.reasons&&(o.Reasons=r.reasons.toString()),r.cRLIssuer&&(o["CRL Issuer"]=r.cRLIssuer.map(s=>s.toString()).join(", ")),o}),e}}ub.NAME="CRL Distribution Points";class lb extends St{constructor(...e){var r,n,o,s;if(K.isBufferSource(e[0]))super(e[0],e[1]);else if(e[0]instanceof Hn){const i=new Hn(e[0]);super(ku,e[1],H.serialize(i))}else{const i=e[0],a=new Hn;ci(a,i,Hp,"ocsp"),ci(a,i,Fp,"caIssuers"),ci(a,i,Wp,"timeStamping"),ci(a,i,Kp,"caRepository"),super(ku,e[1],H.serialize(a))}(r=this.ocsp)!==null&&r!==void 0||(this.ocsp=[]),(n=this.caIssuers)!==null&&n!==void 0||(this.caIssuers=[]),(o=this.timeStamping)!==null&&o!==void 0||(this.timeStamping=[]),(s=this.caRepository)!==null&&s!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],H.parse(e.extnValue,Hn,this.parseOptions).forEach(n=>{switch(n.accessMethod){case Hp:this.ocsp.push(new Br(n.accessLocation));break;case Fp:this.caIssuers.push(new Br(n.accessLocation));break;case Wp:this.timeStamping.push(new Br(n.accessLocation));break;case Kp:this.caRepository.push(new Br(n.accessLocation));break}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&ai(e,"OCSP",this.ocsp),this.caIssuers.length&&ai(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&ai(e,"Time Stamping",this.timeStamping),this.caRepository.length&&ai(e,"CA Repository",this.caRepository),e}}lb.NAME="Authority Info Access";function ai(t,e,r){if(r.length===1)t[e]=r[0].toTextObject();else{const n=new me("");r.forEach((o,s)=>{const i=o.toTextObject(),a=`${i[me.NAME]} ${s+1}`;let c=n[a];Array.isArray(c)||(c=[],n[a]=c),c.push(i)}),t[e]=n}}function ci(t,e,r,n){const o=e[n];o&&(Array.isArray(o)?o:[o]).forEach(i=>{typeof i=="string"&&(i=new Br("url",i)),t.push(new Ds({accessMethod:r,accessLocation:H.parse(i.rawData,ie)}))})}class db extends St{constructor(...e){K.isBufferSource(e[0])?super(e[0],e[1]):super(Nv,e[1],new kn(e[0]||[]).rawData)}onInit(e){super.onInit(e);const r=H.parse(e.extnValue,Ye,this.parseOptions);this.names=new kn(r)}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(const n in r)e[n]=r[n];return e}}db.NAME="Issuer Alternative Name";class xo extends Kr{constructor(...e){let r,n;if(K.isBufferSource(e[0]))r=K.toArrayBuffer(e[0]),n=e[1];else{const o=e[0],s=Array.isArray(e[1])?e[1].map(i=>K.toArrayBuffer(i)):[];r=H.serialize(new gr({type:o,values:s}))}super(r,gr,n)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(r=>new me("",{"":r})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[me.NAME]===xo.NAME&&(e[me.NAME]=Wr.toString(this.type)),e}}xo.NAME="Attribute";class fb extends xo{constructor(...e){var r;if(K.isBufferSource(e[0]))super(e[0],e[1]);else{const n=new ua({printableString:e[0]});super(rb,[H.serialize(n)])}(r=this.password)!==null&&r!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const r=H.parse(this.values[0],ua,this.parseOptions);this.password=r.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[me.VALUE]=this.password,e}}fb.NAME="Challenge Password";class af extends xo{constructor(...e){var r;if(K.isBufferSource(e[0]))super(e[0],e[1]);else{const n=e[0],o=new Dr;for(const s of n)o.push(H.parse(s.rawData,Vt));super(of,[H.serialize(o)])}(r=this.items)!==null&&r!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const r=H.parse(this.values[0],Dr,this.parseOptions);this.items=r.map(n=>kt.create(H.serialize(n),this.parseOptions))}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.items.map(n=>n.toTextObject());for(const n of r)e[n[me.NAME]]=n;return e}}af.NAME="Extensions";class gc{static register(e,r){this.items.set(e,r)}static create(e,r){const n=new xo(e,r),o=this.items.get(n.type);return o?new o(e,r):n}}gc.items=new Map;const Xs="crypto.signatureFormatter";class aI{toAsnSignature(e,r){return K.toArrayBuffer(r)}toWebSignature(e,r){return K.toArrayBuffer(r)}}var gi;let Ml=gi=class{static createPssParams(e,r){const n=gi.getHashAlgorithm(e);return n?new wn({hashAlgorithm:n,maskGenAlgorithm:new W({algorithm:cc,parameters:H.serialize(n)}),saltLength:r}):null}static getHashAlgorithm(e){const r=Le.resolve(An);return typeof e=="string"?r.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?r.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let r;if(typeof e.hash=="string")r=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")r=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(r.toLowerCase()){case"sha-1":return new W({algorithm:Zi,parameters:null});case"sha-256":return new W({algorithm:il,parameters:null});case"sha-384":return new W({algorithm:Qi,parameters:null});case"sha-512":return new W({algorithm:ea,parameters:null})}}else return new W({algorithm:vn,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");const r=gi.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new W({algorithm:ss,parameters:H.serialize(r)})}else return new W({algorithm:ss,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case vn:return{name:"RSASSA-PKCS1-v1_5"};case Zi:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case il:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case Qi:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case ea:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case ss:if(e.parameters){const r=H.parse(e.parameters,wn);return{name:"RSA-PSS",hash:Le.resolve(An).toWebAlgorithm(r.hashAlgorithm),saltLength:r.saltLength}}else return{name:"RSA-PSS"}}return null}};Ml=gi=f([ko()],Ml);Le.registerSingleton(Tn,Ml);let _l=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new W({algorithm:ta});case"sha-256":return new W({algorithm:ra});case"sha-384":return new W({algorithm:na});case"sha-512":return new W({algorithm:oa})}return null}toWebAlgorithm(e){switch(e.algorithm){case ta:return{name:"SHA-1"};case ra:return{name:"SHA-256"};case na:return{name:"SHA-384"};case oa:return{name:"SHA-512"}}return null}};_l=f([ko()],_l);Le.registerSingleton(Tn,_l);class Ct{addPadding(e,r){const n=K.toUint8Array(r),o=new Uint8Array(e);return o.set(n,e-n.length),o.buffer}removePadding(e,r=!1){let n=K.toUint8Array(e);for(let o=0;o<n.length;o++)if(n[o]){n=n.slice(o);break}if(r&&n[0]>127){const o=new Uint8Array(n.length+1);return o.set(n,1),o.buffer}return n.buffer}toAsnSignature(e,r){if(e.name==="ECDSA"){const n=e.namedCurve,o=Ct.namedCurveSize.get(n)||Ct.defaultNamedCurveSize,s=new Ji,i=K.toUint8Array(r);return s.r=this.removePadding(i.slice(0,o),!0),s.s=this.removePadding(i.slice(o,o+o),!0),H.serialize(s)}return null}toWebSignature(e,r){if(e.name==="ECDSA"){const n=H.parse(r,Ji),o=e.namedCurve,s=Ct.namedCurveSize.get(o)||Ct.defaultNamedCurveSize,i=this.addPadding(s,this.removePadding(n.r)),a=this.addPadding(s,this.removePadding(n.s));return vk(i,a)}return null}}Ct.namedCurveSize=new Map;Ct.defaultNamedCurveSize=32;const Jc="1.3.101.110",Cm="1.3.101.111",Zc="1.3.101.112",Nm="1.3.101.113";let jl=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ed25519":r=Zc;break;case"x25519":r=Jc;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":r=Zc;break;case"ed448":r=Nm;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":r=Jc;break;case"x448":r=Cm;break}}return r?new W({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case Zc:return{name:"Ed25519"};case Nm:return{name:"EdDSA",namedCurve:"Ed448"};case Jc:return{name:"X25519"};case Cm:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};jl=f([ko()],jl);Le.registerSingleton(Tn,jl);let Dl=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ml-dsa-44":r=Rh;break;case"ml-dsa-65":r=Mh;break;case"ml-dsa-87":r=_h;break}return r?new W({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case Rh:return{name:"ML-DSA-44"};case Mh:return{name:"ML-DSA-65"};case _h:return{name:"ML-DSA-87"}}return null}};Dl=f([ko()],Dl);Le.registerSingleton(Tn,Dl);let Ll=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"slh-dsa-sha2-128s":r=jh;break;case"slh-dsa-sha2-128f":r=Dh;break;case"slh-dsa-sha2-192s":r=Lh;break;case"slh-dsa-sha2-192f":r=Ph;break;case"slh-dsa-sha2-256s":r=Uh;break;case"slh-dsa-sha2-256f":r=Vh;break;case"slh-dsa-shake-128s":r=Hh;break;case"slh-dsa-shake-128f":r=Fh;break;case"slh-dsa-shake-192s":r=Wh;break;case"slh-dsa-shake-192f":r=Kh;break;case"slh-dsa-shake-256s":r=Gh;break;case"slh-dsa-shake-256f":r=qh;break}return r?new W({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case jh:return{name:"SLH-DSA-SHA2-128s"};case Dh:return{name:"SLH-DSA-SHA2-128f"};case Lh:return{name:"SLH-DSA-SHA2-192s"};case Ph:return{name:"SLH-DSA-SHA2-192f"};case Uh:return{name:"SLH-DSA-SHA2-256s"};case Vh:return{name:"SLH-DSA-SHA2-256f"};case Hh:return{name:"SLH-DSA-SHAKE-128s"};case Fh:return{name:"SLH-DSA-SHAKE-128f"};case Wh:return{name:"SLH-DSA-SHAKE-192s"};case Kh:return{name:"SLH-DSA-SHAKE-192f"};case Gh:return{name:"SLH-DSA-SHAKE-256s"};case qh:return{name:"SLH-DSA-SHAKE-256f"}}return null}};Ll=f([ko()],Ll);Le.registerSingleton(Tn,Ll);var Ro,Mo,_o,jo,Do,Lo,Po,Dn;class cI extends wr{get subjectName(){return oe(this,Mo,"f")||ke(this,Mo,new Dt(this.asn.certificationRequestInfo.subject),"f"),oe(this,Mo,"f")}get subject(){return oe(this,_o,"f")||ke(this,_o,this.subjectName.toString(),"f"),oe(this,_o,"f")}get signatureAlgorithm(){if(!oe(this,jo,"f")){const e=Le.resolve(An);ke(this,jo,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return oe(this,jo,"f")}get signature(){return oe(this,Do,"f")||ke(this,Do,this.asn.signature,"f"),oe(this,Do,"f")}get publicKey(){return oe(this,Lo,"f")||ke(this,Lo,new Ut(this.asn.certificationRequestInfo.subjectPKInfo,this.parseOptions),"f"),oe(this,Lo,"f")}get attributes(){return oe(this,Po,"f")||ke(this,Po,this.asn.certificationRequestInfo.attributes.map(e=>gc.create(H.serialize(e),this.parseOptions)),"f"),oe(this,Po,"f")}get extensions(){if(!oe(this,Dn,"f")){ke(this,Dn,[],"f");const e=this.getAttribute(of);e instanceof af&&ke(this,Dn,e.items,"f")}return oe(this,Dn,"f")}get tbs(){return oe(this,Ro,"f")||ke(this,Ro,this.asn.certificationRequestInfoRaw||H.serialize(this.asn.certificationRequestInfo),"f"),oe(this,Ro,"f")}constructor(e,r){const n=wr.isAsnEncoded(e)?[e,Es,r]:[e,r];super(n[0],n[1],n[2]),Ro.set(this,void 0),Mo.set(this,void 0),_o.set(this,void 0),jo.set(this,void 0),Do.set(this,void 0),Lo.set(this,void 0),Po.set(this,void 0),Dn.set(this,void 0),this.tag=gt.CertificateRequestTag}onInit(e){}getAttribute(e){for(const r of this.attributes)if(r.type===e)return r;return null}getAttributes(e){return this.attributes.filter(r=>r.type===e)}getExtension(e){for(const r of this.extensions)if(r.type===e)return r;return null}getExtensions(e){return this.extensions.filter(r=>r.type===e)}async verify(e=at.get()){const r={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(r,["verify"],e),o=Le.resolveAll(Xs).reverse();let s=null;for(const a of o)if(s=a.toWebSignature(r,this.signature),s)break;if(!s)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,n,s,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty(),r=H.parse(this.rawData,Es,this.parseOptions),n=r.certificationRequestInfo,o=new me("",{Version:`${mn[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const s=new me("");for(const i of this.attributes){const a=i.toTextObject();s[a[me.NAME]]=a}o.Attributes=s}return e.Data=o,e.Signature=new me("",{Algorithm:Sn.serializeAlgorithm(r.signatureAlgorithm),"":r.signature}),e}}Ro=new WeakMap,Mo=new WeakMap,_o=new WeakMap,jo=new WeakMap,Do=new WeakMap,Lo=new WeakMap,Po=new WeakMap,Dn=new WeakMap;cI.NAME="PKCS#10 Certificate Request";function uI(t){let e=0;for(;e<t.length-1&&t[e]===0;)e++;let r=t.slice(e);if(r.length||(r=new Uint8Array([0])),r[0]>127){const n=new Uint8Array(r.length+1);n[0]=0,n.set(r,1),r=n}return r.buffer}function lI(t,e=at.get()){const r=K.toUint8Array(ee.FromHex(t||"")),n=r.length&&r.some(o=>o>0)?r:e.getRandomValues(new Uint8Array(16));return uI(n)}function dI(t){let e=K.toUint8Array(t);return e.length>1&&e[0]===0&&e[1]>127&&(e=e.slice(1)),ee.ToHex(e)}var Uo,Vo,Ho,Fo,Wo,Ko,Go,qo,zo,Yo,Ln,Xo;class pb extends wr{get publicKey(){return oe(this,Xo,"f")||ke(this,Xo,new Ut(this.asn.tbsCertificate.subjectPublicKeyInfo,this.parseOptions),"f"),oe(this,Xo,"f")}get serialNumber(){return oe(this,Vo,"f")||ke(this,Vo,dI(this.asn.tbsCertificate.serialNumber),"f"),oe(this,Vo,"f")}get subjectName(){return oe(this,Ho,"f")||ke(this,Ho,new Dt(this.asn.tbsCertificate.subject),"f"),oe(this,Ho,"f")}get subject(){return oe(this,Fo,"f")||ke(this,Fo,this.subjectName.toString(),"f"),oe(this,Fo,"f")}get issuerName(){return oe(this,Wo,"f")||ke(this,Wo,new Dt(this.asn.tbsCertificate.issuer),"f"),oe(this,Wo,"f")}get issuer(){return oe(this,Ko,"f")||ke(this,Ko,this.issuerName.toString(),"f"),oe(this,Ko,"f")}get notBefore(){if(!oe(this,Go,"f")){const e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");ke(this,Go,e,"f")}return oe(this,Go,"f")}get notAfter(){if(!oe(this,qo,"f")){const e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");ke(this,qo,e,"f")}return oe(this,qo,"f")}get signatureAlgorithm(){if(!oe(this,zo,"f")){const e=Le.resolve(An);ke(this,zo,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return oe(this,zo,"f")}get signature(){return oe(this,Yo,"f")||ke(this,Yo,this.asn.signatureValue,"f"),oe(this,Yo,"f")}get extensions(){return oe(this,Ln,"f")||(ke(this,Ln,[],"f"),this.asn.tbsCertificate.extensions&&ke(this,Ln,this.asn.tbsCertificate.extensions.map(e=>kt.create(H.serialize(e),this.parseOptions)),"f")),oe(this,Ln,"f")}get tbs(){return oe(this,Uo,"f")||ke(this,Uo,this.asn.tbsCertificateRaw||H.serialize(this.asn.tbsCertificate),"f"),oe(this,Uo,"f")}constructor(e,r){const n=wr.isAsnEncoded(e)?[e,yn,r]:[e,r];super(n[0],n[1],n[2]),Uo.set(this,void 0),Vo.set(this,void 0),Ho.set(this,void 0),Fo.set(this,void 0),Wo.set(this,void 0),Ko.set(this,void 0),Go.set(this,void 0),qo.set(this,void 0),zo.set(this,void 0),Yo.set(this,void 0),Ln.set(this,void 0),Xo.set(this,void 0),this.tag=gt.CertificateTag}onInit(e){}getExtension(e){for(const r of this.extensions)if(typeof e=="string"){if(r.type===e)return r}else if(r instanceof e)return r;return null}getExtensions(e){return this.extensions.filter(r=>typeof e=="string"?r.type===e:r instanceof e)}async verify(e={},r=at.get()){let n,o;const s=e.publicKey;try{if(!s)n={...this.publicKey.algorithm,...this.signatureAlgorithm},o=await this.publicKey.export(n,["verify"],r);else if("publicKey"in s)n={...s.publicKey.algorithm,...this.signatureAlgorithm},o=await s.publicKey.export(n,["verify"],r);else if(s instanceof Ut)n={...s.algorithm,...this.signatureAlgorithm},o=await s.export(n,["verify"],r);else if(K.isBufferSource(s)){const u=new Ut(s);n={...u.algorithm,...this.signatureAlgorithm},o=await u.export(n,["verify"],r)}else n={...s.algorithm,...this.signatureAlgorithm},o=s}catch{return!1}const i=Le.resolveAll(Xs).reverse();let a=null;for(const u of i)if(a=u.toWebSignature(n,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const c=await r.subtle.verify(this.signatureAlgorithm,o,a,this.tbs);if(e.signatureOnly)return c;{const d=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<d&&d<this.notAfter.getTime()}}async getThumbprint(e,r){let n,o="SHA-1";return e&&(typeof e=="object"&&"subtle"in e?n=e:(o=e,n=r)),n??(n=at.get()),await n.subtle.digest(o,this.rawData)}async isSelfSigned(e=at.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),r=H.parse(this.rawData,yn,this.parseOptions),n=r.tbsCertificate,o=new me("",{Version:`${mn[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":Sn.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new me("",{"Not Before":n.validity.notBefore.getTime(),"Not After":n.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(n.issuerUniqueID&&(o["Issuer Unique ID"]=n.issuerUniqueID),n.subjectUniqueID&&(o["Subject Unique ID"]=n.subjectUniqueID),this.extensions.length){const s=new me("");for(const i of this.extensions){const a=i.toTextObject();s[a[me.NAME]]=a}o.Extensions=s}return e.Data=o,e.Signature=new me("",{Algorithm:Sn.serializeAlgorithm(r.signatureAlgorithm),"":r.signatureValue}),e}}Uo=new WeakMap,Vo=new WeakMap,Ho=new WeakMap,Fo=new WeakMap,Wo=new WeakMap,Ko=new WeakMap,Go=new WeakMap,qo=new WeakMap,zo=new WeakMap,Yo=new WeakMap,Ln=new WeakMap,Xo=new WeakMap;pb.NAME="Certificate";class Pl{static async createSelfSigned(e,r=at.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},r)}static async create(e,r=at.get()){var n;let o;e.publicKey instanceof Ut?o=e.publicKey.rawData:"publicKey"in e.publicKey?o=e.publicKey.publicKey.rawData:K.isBufferSource(e.publicKey)?o=e.publicKey:o=await r.subtle.exportKey("spki",e.publicKey);const s=lI(e.serialNumber,r),i=e.notBefore||new Date,a=e.notAfter||new Date(i.getTime()+31536e6),c=new yn({tbsCertificate:new At({version:mn.v3,serialNumber:s,validity:new Ls({notBefore:i,notAfter:a}),extensions:new Dr(((n=e.extensions)===null||n===void 0?void 0:n.map(g=>H.parse(g.rawData,Vt)))||[]),subjectPublicKeyInfo:H.parse(o,Ot)})});if(e.subject){const g=e.subject instanceof Dt?e.subject:new Dt(e.subject);c.tbsCertificate.subject=H.parse(g.toArrayBuffer(),Re)}if(e.issuer){const g=e.issuer instanceof Dt?e.issuer:new Dt(e.issuer);c.tbsCertificate.issuer=H.parse(g.toArrayBuffer(),Re)}const u={hash:"SHA-256"},d="signingKey"in e?{...u,...e.signingAlgorithm,...e.signingKey.algorithm}:{...u,...e.signingAlgorithm},l=Le.resolve(An);c.tbsCertificate.signature=c.signatureAlgorithm=l.toAsnAlgorithm(d);const m=H.serialize(c.tbsCertificate),p="signingKey"in e?await r.subtle.sign(d,e.signingKey,m):e.signature,h=Le.resolveAll(Xs).reverse();let v=null;for(const g of h)if(v=g.toAsnSignature(d,p),v)break;if(!v)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=v,new pb(H.serialize(c))}}var Tm;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(Tm||(Tm={}));kt.register(xv,Os);kt.register(Cv,yc);kt.register(Tv,Cs);kt.register(Mv,Ys);kt.register(Eu,En);kt.register(Rv,sf);kt.register(Nu,ub);kt.register(ku,lb);kt.register(Nv,db);gc.register(rb,fb);gc.register(of,af);Le.registerSingleton(Xs,aI);Le.registerSingleton(Xs,Ct);Ct.namedCurveSize.set("P-256",32);Ct.namedCurveSize.set("K-256",32);Ct.namedCurveSize.set("P-384",48);Ct.namedCurveSize.set("P-521",66);const st=Bb,Ul={name:"ECDSA",namedCurve:"P-256",hash:"SHA-256"},Ns={name:"ECDSA",namedCurve:"P-256"},fI="1.3.6.1.5.5.7.3.1",pI="1.3.6.1.5.5.7.3.2",Vl=6e4,Hl=864e5;function hb(t){return`${t}.display`}function hI(t,e){const r=Buffer.from(e).toString("base64").match(/.{1,64}/g)?.join(`
104
122
  `)??"";return`-----BEGIN ${t}-----
105
123
  ${r}
106
124
  -----END ${t}-----
107
- `}function XE(t,e){const r=`${t}.${process.pid}.tmp`;El(r,e,{mode:384}),Il(r,t),ea(t,384)}async function im(t){return{privateKey:await Ze.subtle.exportKey("jwk",t.privateKey),publicKey:await Ze.subtle.exportKey("jwk",t.publicKey)}}async function am(t){return{privateKey:await Ze.subtle.importKey("jwk",t.privateKey,ho,!0,["sign"]),publicKey:await Ze.subtle.importKey("jwk",t.publicKey,ho,!0,["verify"])}}function _v(t){const e=new js(t).publicKey.export({format:"jwk"});if(!e.x||!e.y)throw new Error("057 Display CA is not a P-256 key");const r=Buffer.concat([Buffer.from([4]),Buffer.from(e.x,"base64url"),Buffer.from(e.y,"base64url")]);return Qn("sha256").update(r).digest("base64url")}async function JE(){const t=Date.now(),e=await Ze.subtle.generateKey(ho,!0,["sign","verify"]),r=await wl.createSelfSigned({name:"CN=057 Display Core",keys:e,serialNumber:Dn(16).toString("hex"),notBefore:new Date(t-5*Sl),notAfter:new Date(t+10*365*kl),signingAlgorithm:Al,extensions:[new fo(!0,0,!0),new po(jn.keyCertSign|jn.cRLSign,!0),await _o.create(e.publicKey,!1,Ze)]},Ze),n=r.toString("pem"),s=_v(n),o=Qn("sha256").update(s).digest("hex").slice(0,20),i=await Ze.subtle.generateKey(ho,!0,["sign","verify"]),a=await wl.create({subject:`CN=057 Display ${o}`,issuer:r.subject,publicKey:i.publicKey,signingKey:e.privateKey,serialNumber:Dn(16).toString("hex"),notBefore:new Date(t-5*Sl),notAfter:new Date(t+2*365*kl),signingAlgorithm:Al,extensions:[new fo(!1,void 0,!0),new po(jn.digitalSignature,!0),new rc([qE],!0),new jd([{type:"dns",value:"057-display.local"},{type:"ip",value:"127.0.0.1"}]),await pn.create(e.publicKey,!1,Ze)]},Ze);return{version:1,coreId:o,caPin:s,caCertificate:n,serverCertificate:a.toString("pem"),caKeys:await im(e),serverKeys:await im(i)}}async function ZE(t){if(t.caPin!==_v(t.caCertificate))throw new Error("057 Display CA pin does not match its certificate");const e=await am(t.caKeys),r=await am(t.serverKeys),n=YE("PRIVATE KEY",await Ze.subtle.exportKey("pkcs8",r.privateKey));return{coreId:t.coreId,caPin:t.caPin,serverPin:Qn("sha256").update(new js(t.serverCertificate).raw).digest("base64url"),caCertificate:t.caCertificate,serverCertificate:t.serverCertificate,serverPrivateKey:n,async issueClient(s,o){const i=new ArrayBuffer(s.byteLength);new Uint8Array(i).set(s);const a=await Ze.subtle.importKey("raw",i,ho,!0,["verify"]),c=Date.now(),u=c+5*365*kl,d=(await wl.create({subject:`CN=${o.replace(/[,+\"\\<>;]/g," ").slice(0,80)||"057 Display"}`,issuer:new js(t.caCertificate).subject,publicKey:a,signingKey:e.privateKey,serialNumber:Dn(16).toString("hex"),notBefore:new Date(c-5*Sl),notAfter:new Date(u),signingAlgorithm:Al,extensions:[new fo(!1,void 0,!0),new po(jn.digitalSignature,!0),new rc([zE],!0),await pn.create(e.publicKey,!1,Ze)]},Ze)).toString("pem"),m=new js(d);return{certificate:d,certificateDer:Buffer.from(m.raw).toString("base64"),serial:m.serialNumber.toLowerCase(),fingerprint:m.fingerprint256.replaceAll(":","").toLowerCase(),expiresAt:u}}}}async function QE(t){const e=Rv(t),r=se(e,"identity.json");Dc(ii(e),{recursive:!0,mode:448}),Dc(e,{recursive:!0,mode:448}),ea(e,448);let n;if(fe(r)){if(n=JSON.parse(Cl(r,"utf8")),n.version!==1)throw new Error(`unsupported 057 Display identity version ${String(n.version)}`)}else n=await JE(),XE(r,`${JSON.stringify(n)}
108
- `);return ZE(n)}const e1=4e3,t1=8e3;function r1(t,e,r){t.statusCode=200,t.setHeader("content-type","text/event-stream; charset=utf-8"),t.setHeader("cache-control","no-store"),t.setHeader("connection","keep-alive"),t.setHeader("x-content-type-options","nosniff"),t.flushHeaders();let n=!1,s=!1,o;const i=()=>{n=!0,clearInterval(c),clearInterval(u)},a=async()=>{if(!(n||s)){s=!0;try{const l=await e();if(n)return;l.wire!==o&&(o=l.wire,t.write(`id: ${l.id}
125
+ `}function mI(t,e){const r=`${t}.${process.pid}.tmp`;Wl(r,e,{mode:384}),Kl(r,t),pa(t,384)}async function $m(t){return{privateKey:await st.subtle.exportKey("jwk",t.privateKey),publicKey:await st.subtle.exportKey("jwk",t.publicKey)}}async function Bm(t){return{privateKey:await st.subtle.importKey("jwk",t.privateKey,Ns,!0,["sign"]),publicKey:await st.subtle.importKey("jwk",t.publicKey,Ns,!0,["verify"])}}function mb(t){const e=new Jo(t).publicKey.export({format:"jwk"});if(!e.x||!e.y)throw new Error("057 Display CA is not a P-256 key");const r=Buffer.concat([Buffer.from([4]),Buffer.from(e.x,"base64url"),Buffer.from(e.y,"base64url")]);return fo("sha256").update(r).digest("base64url")}async function yI(){const t=Date.now(),e=await st.subtle.generateKey(Ns,!0,["sign","verify"]),r=await Pl.createSelfSigned({name:"CN=057 Display Core",keys:e,serialNumber:Yn(16).toString("hex"),notBefore:new Date(t-5*Vl),notAfter:new Date(t+10*365*Hl),signingAlgorithm:Ul,extensions:[new Os(!0,0,!0),new Cs(zn.keyCertSign|zn.cRLSign,!0),await Ys.create(e.publicKey,!1,st)]},st),n=r.toString("pem"),o=mb(n),s=fo("sha256").update(o).digest("hex").slice(0,20),i=await st.subtle.generateKey(Ns,!0,["sign","verify"]),a=await Pl.create({subject:`CN=057 Display ${s}`,issuer:r.subject,publicKey:i.publicKey,signingKey:e.privateKey,serialNumber:Yn(16).toString("hex"),notBefore:new Date(t-5*Vl),notAfter:new Date(t+2*365*Hl),signingAlgorithm:Ul,extensions:[new Os(!1,void 0,!0),new Cs(zn.digitalSignature,!0),new yc([fI],!0),new sf([{type:"dns",value:"057-display.local"},{type:"ip",value:"127.0.0.1"}]),await En.create(e.publicKey,!1,st)]},st);return{version:1,coreId:s,caPin:o,caCertificate:n,serverCertificate:a.toString("pem"),caKeys:await $m(e),serverKeys:await $m(i)}}async function gI(t){if(t.caPin!==mb(t.caCertificate))throw new Error("057 Display CA pin does not match its certificate");const e=await Bm(t.caKeys),r=await Bm(t.serverKeys),n=hI("PRIVATE KEY",await st.subtle.exportKey("pkcs8",r.privateKey));return{coreId:t.coreId,caPin:t.caPin,serverPin:fo("sha256").update(new Jo(t.serverCertificate).raw).digest("base64url"),caCertificate:t.caCertificate,serverCertificate:t.serverCertificate,serverPrivateKey:n,async issueClient(o,s){const i=new ArrayBuffer(o.byteLength);new Uint8Array(i).set(o);const a=await st.subtle.importKey("raw",i,Ns,!0,["verify"]),c=Date.now(),u=c+5*365*Hl,l=(await Pl.create({subject:`CN=${s.replace(/[,+\"\\<>;]/g," ").slice(0,80)||"057 Display"}`,issuer:new Jo(t.caCertificate).subject,publicKey:a,signingKey:e.privateKey,serialNumber:Yn(16).toString("hex"),notBefore:new Date(c-5*Vl),notAfter:new Date(u),signingAlgorithm:Ul,extensions:[new Os(!1,void 0,!0),new Cs(zn.digitalSignature,!0),new yc([pI],!0),await En.create(e.publicKey,!1,st)]},st)).toString("pem"),m=new Jo(l);return{certificate:l,certificateDer:Buffer.from(m.raw).toString("base64"),serial:m.serialNumber.toLowerCase(),fingerprint:m.fingerprint256.replaceAll(":","").toLowerCase(),expiresAt:u}}}}async function vI(t){const e=hb(t),r=ue(e,"identity.json");eu(vi(e),{recursive:!0,mode:448}),eu(e,{recursive:!0,mode:448}),pa(e,448);let n;if(ge(r)){if(n=JSON.parse(Gl(r,"utf8")),n.version!==1)throw new Error(`unsupported 057 Display identity version ${String(n.version)}`)}else n=await yI(),mI(r,`${JSON.stringify(n)}
126
+ `);return gI(n)}const bI=4e3,wI=8e3;function AI(t,e,r){t.statusCode=200,t.setHeader("content-type","text/event-stream; charset=utf-8"),t.setHeader("cache-control","no-store"),t.setHeader("connection","keep-alive"),t.setHeader("x-content-type-options","nosniff"),t.flushHeaders();let n=!1,o=!1,s;const i=()=>{n=!0,clearInterval(c),clearInterval(u)},a=async()=>{if(!(n||o)){o=!0;try{const d=await e();if(n)return;d.wire!==s&&(s=d.wire,t.write(`id: ${d.id}
109
127
  event: landscape
110
- data: ${l.wire}
128
+ data: ${d.wire}
111
129
 
112
- `))}catch(l){n||(r(l),i(),t.end())}finally{s=!1}}},c=setInterval(()=>{a()},e1),u=setInterval(()=>{n||t.write(`: 057
130
+ `))}catch(d){n||(r(d),i(),t.end())}finally{o=!1}}},c=setInterval(()=>{a()},bI),u=setInterval(()=>{n||t.write(`: 057
113
131
 
114
- `)},t1);t.once("close",i),a()}const Zi=1,n1=12e4;function s1(t,e){const r=`${t}.${process.pid}.tmp`;El(r,e,{mode:384}),Il(r,t),ea(t,384)}class o1{path;state;constructor(e){if(this.path=se(e,"trusted.json"),this.state=fe(this.path)?JSON.parse(Cl(this.path,"utf8")):{version:1,displays:[]},this.state.version!==1)throw new Error(`unsupported 057 Display trust version ${String(this.state.version)}`)}list(){return this.state.displays.map(e=>({...e}))}trusts(e){const r=e.replaceAll(":","").toLowerCase();return this.state.displays.some(n=>n.fingerprint===r&&n.revokedAt===void 0&&n.expiresAt>Date.now())}add(e,r){const n=this.state.displays.find(s=>s.deviceId===e.deviceId&&s.revokedAt===void 0);n&&(n.revokedAt=Date.now()),this.state.displays.push({deviceId:e.deviceId,name:e.deviceName.slice(0,80)||"iPhone",fingerprint:r.fingerprint,serial:r.serial,pairedAt:Date.now(),expiresAt:r.expiresAt}),this.save()}revoke(e){const r=this.state.displays.find(n=>n.deviceId===e&&n.revokedAt===void 0);return r?(r.revokedAt=Date.now(),this.save(),!0):!1}save(){s1(this.path,`${JSON.stringify(this.state,null,1)}
115
- `)}}function i1(t){return Buffer.concat([Buffer.from("057.display.pair.v1\0","utf8"),Buffer.from(t.grantId,"utf8"),Buffer.from([0]),Buffer.from(t.coreId,"utf8"),Buffer.from([0]),Buffer.from(t.deviceId,"utf8"),Buffer.from([0]),Buffer.from(t.publicKey,"base64")])}function a1(t){if(t.length!==65||t[0]!==4)throw new Error("the Display public key is not an uncompressed P-256 point");return sb({key:{kty:"EC",crv:"P-256",x:t.subarray(1,33).toString("base64url"),y:t.subarray(33,65).toString("base64url")},format:"jwk"})}class c1{constructor(e){this.identity=e}identity;grants=new Map;create(e=Date.now()){this.grants.clear();const r={id:Dn(18).toString("base64url"),secret:Dn(32),expiresAt:e+n1};this.grants.set(r.id,r);const n={p:Zi,id:this.identity.coreId,pin:this.identity.caPin,sp:this.identity.serverPin,grant:r.id,secret:Buffer.from(r.secret).toString("base64url"),expires:r.expiresAt};return{payload:n,uri:`o57-display://pair#${Buffer.from(JSON.stringify(n)).toString("base64url")}`}}async redeem(e,r,n=Date.now()){if(e.protocol!==Zi)throw new Error("unsupported pairing protocol");if(e.coreId!==this.identity.coreId)throw new Error("pairing grant belongs to another Core");const s=this.grants.get(e.grantId);if(!s||s.expiresAt<=n)throw this.grants.delete(e.grantId),new Error("pairing grant is missing or expired");const o=Buffer.from(e.secret,"base64url");if(o.length!==s.secret.length||!rb(o,s.secret))throw new Error("pairing grant is invalid");this.grants.delete(e.grantId);const i=Buffer.from(e.publicKey,"base64"),a=Buffer.from(e.signature,"base64");if(!nb("sha256",i1(e),a1(i),a))throw new Error("Display did not prove possession of its private key");const c=await this.identity.issueClient(i,e.deviceName);return r.add(e,c),c}}const xl="127.0.0.1",u1="0.0.0.0",l1=16*1024;function cm(t,e,r){return new Promise((n,s)=>{t.once("error",s),t.listen(e,r,()=>{t.off("error",s);const o=t.address();if(!o||typeof o=="string")return s(new Error("Display listener has no TCP address"));n(o.port)})})}function jc(t){return new Promise(e=>{t.close(()=>e()),t.closeAllConnections?.()})}function Lt(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json; charset=utf-8"),t.setHeader("cache-control","no-store"),t.setHeader("x-content-type-options","nosniff"),t.end(`${JSON.stringify(r)}
116
- `)}async function d1(t){let e=0;const r=[];for await(const n of t){const s=Buffer.isBuffer(n)?n:Buffer.from(n);if(e+=s.length,e>l1)throw new Error("request body is too large");r.push(s)}return JSON.parse(Buffer.concat(r).toString("utf8"))}function f1(t){if(!t||typeof t!="object")throw new Error("pairing request must be an object");const e=t;for(const r of["coreId","grantId","secret","deviceId","deviceName","publicKey","signature"])if(typeof e[r]!="string"||e[r].length===0)throw new Error(`pairing request has no ${r}`);if(typeof e.protocol!="number")throw new Error("pairing request has no protocol version");if(e.deviceId.length>128||e.deviceName.length>128)throw new Error("Display identity is too long");return e}function p1(t){const e=t.socket;return e.authorized?e.getPeerCertificate().fingerprint256?.replaceAll(":","").toLowerCase()??null:null}async function h1(t){const e=await fetch(`${t}/api/landscape?window=live`,{headers:{"x-057-client":"display-delivery"},signal:AbortSignal.timeout(6e4)});if(!e.ok)throw new Error(`private Core returned ${e.status}`);const r=await e.json();if(r.contract!==hi||r.version!==qs||!r.landscape)throw new Error("private Core returned an incompatible landscape envelope");const n={contract:hi,version:qs,landscape:r.landscape};return{wire:JSON.stringify(n),envelope:n}}function m1(t,e,r){r1(t,async()=>{const n=await h1(e),s=Qn("sha256").update(n.wire).digest("base64url").slice(0,16);return{wire:n.wire,id:s}},n=>r.warn(`[057] Display landscape delivery failed: ${String(n)}`))}function y1(t,e){const r=t.socket.remoteAddress;return(r===xl||r==="::1"||r==="::ffff:127.0.0.1")&&t.headers.authorization===`Bearer ${e}`}async function g1(t){const e=await QE(t.storePath),r=new o1(Rv(t.storePath)),n=new c1(e),s=cb({key:e.serverPrivateKey,cert:`${e.serverCertificate.trimEnd()}
117
- ${e.caCertificate.trimStart()}`,ca:e.caCertificate,minVersion:"TLSv1.3",maxVersion:"TLSv1.3",requestCert:!0,rejectUnauthorized:!1},(l,d)=>{(async()=>{const m=new URL(l.url??"/","https://057-display.local");if(l.method==="POST"&&m.pathname==="/v1/pair"){try{const p=f1(await d1(l)),y=await n.redeem(p,r);Lt(d,201,{protocol:Zi,coreId:e.coreId,caPin:e.caPin,caCertificate:Buffer.from(new js(e.caCertificate).raw).toString("base64"),clientCertificate:y.certificateDer,expiresAt:y.expiresAt})}catch(p){t.log.warn(`[057] Display pairing refused: ${String(p)}`),Lt(d,403,{error:p instanceof Error?p.message:String(p)})}return}if(l.method==="GET"&&m.pathname==="/v1/landscape"){const p=p1(l);if(!p||!r.trusts(p)){Lt(d,401,{error:"trusted Display certificate required"});return}m1(d,t.loopbackUrl,t.log);return}Lt(d,404,{error:"not found"})})().catch(m=>{t.log.error(`[057] Display request failed: ${String(m)}`),d.headersSent?d.end():Lt(d,500,{error:"Display request failed"})})});s.requestTimeout=15e3,s.headersTimeout=15e3;const o=await cm(s,t.port??0,u1),i=Dn(32).toString("base64url"),a=pm((l,d)=>{(async()=>{if(!y1(l,i)){Lt(d,403,{error:"local Display control token required"});return}const m=new URL(l.url??"/","http://localhost");if(l.method==="POST"&&m.pathname==="/v1/grants"){Lt(d,201,n.create());return}if(l.method==="GET"&&m.pathname==="/v1/displays"){Lt(d,200,{displays:r.list()});return}if(l.method==="DELETE"&&m.pathname.startsWith("/v1/displays/")){const p=decodeURIComponent(m.pathname.slice(13));Lt(d,r.revoke(p)?200:404,{revoked:p});return}Lt(d,404,{error:"not found"})})()}),c=await cm(a,0,xl).catch(async l=>{throw await jc(s),l}),u={protocol:Zi,landscape:qs,coreId:e.coreId,caPin:e.caPin,port:o,controlUrl:`http://${xl}:${c}`,controlToken:i};return t.log.info(`[057] Display delivery ${e.coreId} listening securely on port ${o}`),{info:u,async close(){await Promise.all([jc(a),jc(s)])}}}const Pd=5057,ar="127.0.0.1",v1=["localhost","127.0.0.1","[::1]","::1"],b1=10,w1={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".woff2":"font/woff2",".png":"image/png",".ico":"image/vnd.microsoft.icon"};function um(t,e,r){let n;try{n=decodeURIComponent(e)}catch{return!1}if(n.includes("\0"))return!1;const s=yo(t,`.${Xv(n)}`);if(s!==t&&!s.startsWith(t+Lc)||!fe(s)||!Qi(s).isFile())return!1;const o=w1[Jv(s).toLowerCase()]??"application/octet-stream";return r.statusCode=200,r.setHeader("content-type",o),r.setHeader("x-content-type-options","nosniff"),ql(r),r.setHeader("cache-control",e.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-store"),dm(s).pipe(r),!0}function A1(t,e,r,n){return new Promise((s,o)=>{let i=n,a=e;const c=u=>{if(u.code==="EADDRINUSE"&&i>1){i--,a++,t.listen(a,r);return}t.off("error",c),o(u)};t.on("error",c),t.once("listening",()=>{t.off("error",c);const u=t.address();s(typeof u=="object"&&u?u.port:a)}),t.listen(a,r)})}function S1(t,e){const r=String(t.headers["sec-fetch-dest"]??"");if(k1.has(r))return`refusing to be embedded as ${r}`;const n=t.headers["sec-fetch-site"];return typeof n=="string"&&n!==""&&n!=="same-origin"&&n!=="none"?`refusing a ${n} request for ${e}`:null}const k1=new Set(["iframe","frame","embed","object","fencedframe"]);async function Mv(t){const e=t.log??Iy,r=yo(t.root),n=t.host??ar,s=n===ar||n==="::1"||n==="localhost",o=t.runtime?.path??t.storePath??sa();if(!t.runtime){const y=await kS(o);if(y)throw new Gl(y)}const i=t.runtime??Cy({path:t.storePath,log:e,retention:t.retention,observe:t.observe}),a=import.meta.url.endsWith(".mjs")?wS(import.meta.url,{path:i.path,retention:i.retention,machineId:i.machine.id}):void 0,c=import.meta.url.endsWith(".mjs")?DS(import.meta.url,{path:i.path,machineId:i.machine.id}):void 0,u=qS({runtime:i,log:e,version:t.version,activity:a,landscape:c,allowedHosts:s?v1:null}),l=pm((y,v)=>{(async()=>{try{if(await u(y,v))return;if(y.method!=="GET"&&y.method!=="HEAD"){v.statusCode=405,v.setHeader("allow","GET, HEAD"),v.end();return}const g=new URL(y.url??"/","http://localhost").pathname,C=S1(y,g);if(C){e.warn(`[057] ${C}`),v.statusCode=403,v.setHeader("content-type","text/plain; charset=utf-8"),ql(v),v.end(`${C}
118
- `);return}if(um(r,g==="/"?"/index.html":g,v)||!g.startsWith("/assets/")&&um(r,"/index.html",v))return;v.statusCode=404,v.setHeader("content-type","text/plain; charset=utf-8"),v.end(`not found
119
- `)}catch(g){e.error(`[057] request failed: ${String(g)}`),v.headersSent||(v.statusCode=500),v.end()}})()}),d=await A1(l,t.port??Pd,n,b1).catch(y=>{throw i.stop(),y}),m=s?"localhost":n;let p;if(t.display)try{p=await g1({storePath:i.path,loopbackUrl:`http://${ar}:${d}`,log:e})}catch(y){e.error(`[057] authenticated Display delivery could not start: ${String(y)}`)}return xS(i.path,{pid:process.pid,url:`http://${s?ar:n}:${d}`,version:t.version??"dev",contract:Wl,store:i.path,startedAt:Date.now(),owner:t.owner??"cli",...p?{display:p.info}:{}}),{url:`http://${m}:${d}`,port:d,host:n,runtime:i,server:l,display:p?.info,close(){ES(i.path),a?.close(),c?.close();const y=new Promise(v=>l.close(()=>v()));return l.closeAllConnections?.(),Promise.all([y,p?.close()]).then(()=>i.stop())}}}function x1(t){return yo(Zv(new URL(".",t)),"..","dist")}function E1(t,e){switch(e.operation){case"summary":return{operation:"summary",result:t.summary(e.period)};case"availability":return{operation:"availability",result:t.availability(e.period)};case"compare":return{operation:"compare",result:t.compare(e.periodA,e.periodB)};case"breakdown":return{operation:"breakdown",result:t.breakdown(e.period,e.dimension)}}}const mo="1.2.3";function I1(t){const e={command:"serve",activityOperation:"summary",activityPrevious:!1,activityAscii:!1,open:!1,yes:!1,desktop:!1},r=[...t],n=r[0];if(n&&!n.startsWith("-"))if(n==="status"||n==="compact"||n==="reset")e.command=n,r.shift();else if(n==="activity"){e.command="activity",r.shift();const s=r[0];if(s&&!s.startsWith("-")){const o=j1(s);if(o)e.activityOperation=o.operation,e.activityDimension=o.dimension,e.activityItemFilter=o.itemFilter;else if(s==="today")e.activityOperation="summary";else if(Kw.includes(s))e.activityOperation=s;else return{...e,command:"help",error:`unknown activity operation: ${s}`};r.shift()}}else return{...e,command:"help",error:`unknown command: ${n}`};for(;r.length;){const s=r.shift(),[o,i]=s.includes("=")?C1(s,"="):[s,void 0],a=()=>i??r.shift();switch(o){case"-h":case"--help":e.command="help";break;case"-v":case"--version":e.command="version";break;case"--open":e.open=!0;break;case"--yes":case"-y":e.yes=!0;break;case"--desktop":e.desktop=!0;break;case"--last":{const c=a(),u=c?.match(/^(\d+)d$/),l=u?Number(u[1]):NaN;if(!Number.isInteger(l)||l<1)return{...e,command:"help",error:`--last needs a positive duration such as 7d, got ${c}`};e.activityLastDays=l;break}case"--previous":e.activityPrevious=!0;break;case"--by":{const c=a(),u=["model","executor","lifecycle","outcome","session","duration-band"];if(!c||!u.includes(c))return{...e,command:"help",error:`--by needs one of: ${u.join(", ")}`};e.activityDimension=c;break}case"--width":{const c=a(),u=Number(c);if(!Number.isInteger(u)||u<1)return{...e,command:"help",error:`--width needs a positive number of columns, got ${c}`};e.activityWidth=u;break}case"--color":{const c=a();if(c!=="always"&&c!=="never"&&c!=="auto")return{...e,command:"help",error:`--color needs always, never or auto, got ${c}`};e.activityColor=c;break}case"--ascii":e.activityAscii=!0;break;case"--port":{const c=a(),u=Number(c);if(!Number.isInteger(u)||u<0||u>65535)return{...e,command:"help",error:`--port needs a port number, got ${c}`};e.port=u;break}case"--host":{const c=a();if(!c)return{...e,command:"help",error:"--host needs a value"};e.host=c;break}case"--store":{const c=a();if(!c)return{...e,command:"help",error:"--store needs a path"};e.store=c;break}default:return{...e,command:"help",error:`unknown option: ${o}`}}}return e}function C1(t,e){const r=t.indexOf(e);return[t.slice(0,r),t.slice(r+1)]}const O1=`057 — a spatial interface for observing the shape of a computational workday
132
+ `)},wI);t.once("close",i),a()}const da=1,SI=12e4;function kI(t,e){const r=`${t}.${process.pid}.tmp`;Wl(r,e,{mode:384}),Kl(r,t),pa(t,384)}class EI{path;state;constructor(e){if(this.path=ue(e,"trusted.json"),this.state=ge(this.path)?JSON.parse(Gl(this.path,"utf8")):{version:1,displays:[]},this.state.version!==1)throw new Error(`unsupported 057 Display trust version ${String(this.state.version)}`)}list(){return this.state.displays.map(e=>({...e}))}trusts(e){const r=e.replaceAll(":","").toLowerCase();return this.state.displays.some(n=>n.fingerprint===r&&n.revokedAt===void 0&&n.expiresAt>Date.now())}add(e,r){const n=this.state.displays.find(o=>o.deviceId===e.deviceId&&o.revokedAt===void 0);n&&(n.revokedAt=Date.now()),this.state.displays.push({deviceId:e.deviceId,name:e.deviceName.slice(0,80)||"iPhone",fingerprint:r.fingerprint,serial:r.serial,pairedAt:Date.now(),expiresAt:r.expiresAt}),this.save()}revoke(e){const r=this.state.displays.find(n=>n.deviceId===e&&n.revokedAt===void 0);return r?(r.revokedAt=Date.now(),this.save(),!0):!1}save(){kI(this.path,`${JSON.stringify(this.state,null,1)}
133
+ `)}}function xI(t){return Buffer.concat([Buffer.from("057.display.pair.v1\0","utf8"),Buffer.from(t.grantId,"utf8"),Buffer.from([0]),Buffer.from(t.coreId,"utf8"),Buffer.from([0]),Buffer.from(t.deviceId,"utf8"),Buffer.from([0]),Buffer.from(t.publicKey,"base64")])}function II(t){if(t.length!==65||t[0]!==4)throw new Error("the Display public key is not an uncompressed P-256 point");return _b({key:{kty:"EC",crv:"P-256",x:t.subarray(1,33).toString("base64url"),y:t.subarray(33,65).toString("base64url")},format:"jwk"})}class OI{constructor(e){this.identity=e}identity;grants=new Map;create(e=Date.now()){this.grants.clear();const r={id:Yn(18).toString("base64url"),secret:Yn(32),expiresAt:e+SI};this.grants.set(r.id,r);const n={p:da,id:this.identity.coreId,pin:this.identity.caPin,sp:this.identity.serverPin,grant:r.id,secret:Buffer.from(r.secret).toString("base64url"),expires:r.expiresAt};return{payload:n,uri:`o57-display://pair#${Buffer.from(JSON.stringify(n)).toString("base64url")}`}}async redeem(e,r,n=Date.now()){if(e.protocol!==da)throw new Error("unsupported pairing protocol");if(e.coreId!==this.identity.coreId)throw new Error("pairing grant belongs to another Core");const o=this.grants.get(e.grantId);if(!o||o.expiresAt<=n)throw this.grants.delete(e.grantId),new Error("pairing grant is missing or expired");const s=Buffer.from(e.secret,"base64url");if(s.length!==o.secret.length||!Rb(s,o.secret))throw new Error("pairing grant is invalid");this.grants.delete(e.grantId);const i=Buffer.from(e.publicKey,"base64"),a=Buffer.from(e.signature,"base64");if(!Mb("sha256",xI(e),II(i),a))throw new Error("Display did not prove possession of its private key");const c=await this.identity.issueClient(i,e.deviceName);return r.add(e,c),c}}const Fl="127.0.0.1",CI="0.0.0.0",NI=16*1024;function Rm(t,e,r){return new Promise((n,o)=>{t.once("error",o),t.listen(e,r,()=>{t.off("error",o);const s=t.address();if(!s||typeof s=="string")return o(new Error("Display listener has no TCP address"));n(s.port)})})}function Qc(t){return new Promise(e=>{t.close(()=>e()),t.closeAllConnections?.()})}function qt(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json; charset=utf-8"),t.setHeader("cache-control","no-store"),t.setHeader("x-content-type-options","nosniff"),t.end(`${JSON.stringify(r)}
134
+ `)}async function TI(t){let e=0;const r=[];for await(const n of t){const o=Buffer.isBuffer(n)?n:Buffer.from(n);if(e+=o.length,e>NI)throw new Error("request body is too large");r.push(o)}return JSON.parse(Buffer.concat(r).toString("utf8"))}function $I(t){if(!t||typeof t!="object")throw new Error("pairing request must be an object");const e=t;for(const r of["coreId","grantId","secret","deviceId","deviceName","publicKey","signature"])if(typeof e[r]!="string"||e[r].length===0)throw new Error(`pairing request has no ${r}`);if(typeof e.protocol!="number")throw new Error("pairing request has no protocol version");if(e.deviceId.length>128||e.deviceName.length>128)throw new Error("Display identity is too long");return e}function BI(t){const e=t.socket;return e.authorized?e.getPeerCertificate().fingerprint256?.replaceAll(":","").toLowerCase()??null:null}async function RI(t){const e=await fetch(`${t}/api/landscape?window=live`,{headers:{"x-057-client":"display-delivery"},signal:AbortSignal.timeout(6e4)});if(!e.ok)throw new Error(`private Core returned ${e.status}`);const r=await e.json();if(r.contract!==Oi||r.version!==us||!r.landscape)throw new Error("private Core returned an incompatible landscape envelope");const n={contract:Oi,version:us,landscape:r.landscape};return{wire:JSON.stringify(n),envelope:n}}function MI(t,e,r){AI(t,async()=>{const n=await RI(e),o=fo("sha256").update(n.wire).digest("base64url").slice(0,16);return{wire:n.wire,id:o}},n=>r.warn(`[057] Display landscape delivery failed: ${String(n)}`))}function _I(t,e){const r=t.socket.remoteAddress;return(r===Fl||r==="::1"||r==="::ffff:127.0.0.1")&&t.headers.authorization===`Bearer ${e}`}async function jI(t){const e=await vI(t.storePath),r=new EI(hb(t.storePath)),n=new OI(e),o=Pb({key:e.serverPrivateKey,cert:`${e.serverCertificate.trimEnd()}
135
+ ${e.caCertificate.trimStart()}`,ca:e.caCertificate,minVersion:"TLSv1.3",maxVersion:"TLSv1.3",requestCert:!0,rejectUnauthorized:!1},(d,l)=>{(async()=>{const m=new URL(d.url??"/","https://057-display.local");if(d.method==="POST"&&m.pathname==="/v1/pair"){try{const p=$I(await TI(d)),h=await n.redeem(p,r);qt(l,201,{protocol:da,coreId:e.coreId,caPin:e.caPin,caCertificate:Buffer.from(new Jo(e.caCertificate).raw).toString("base64"),clientCertificate:h.certificateDer,expiresAt:h.expiresAt})}catch(p){t.log.warn(`[057] Display pairing refused: ${String(p)}`),qt(l,403,{error:p instanceof Error?p.message:String(p)})}return}if(d.method==="GET"&&m.pathname==="/v1/landscape"){const p=BI(d);if(!p||!r.trusts(p)){qt(l,401,{error:"trusted Display certificate required"});return}MI(l,t.loopbackUrl,t.log);return}qt(l,404,{error:"not found"})})().catch(m=>{t.log.error(`[057] Display request failed: ${String(m)}`),l.headersSent?l.end():qt(l,500,{error:"Display request failed"})})});o.requestTimeout=15e3,o.headersTimeout=15e3;const s=await Rm(o,t.port??0,CI),i=Yn(32).toString("base64url"),a=Lm((d,l)=>{(async()=>{if(!_I(d,i)){qt(l,403,{error:"local Display control token required"});return}const m=new URL(d.url??"/","http://localhost");if(d.method==="POST"&&m.pathname==="/v1/grants"){qt(l,201,n.create());return}if(d.method==="GET"&&m.pathname==="/v1/displays"){qt(l,200,{displays:r.list()});return}if(d.method==="DELETE"&&m.pathname.startsWith("/v1/displays/")){const p=decodeURIComponent(m.pathname.slice(13));qt(l,r.revoke(p)?200:404,{revoked:p});return}qt(l,404,{error:"not found"})})()}),c=await Rm(a,0,Fl).catch(async d=>{throw await Qc(o),d}),u={protocol:da,landscape:us,coreId:e.coreId,caPin:e.caPin,port:s,controlUrl:`http://${Fl}:${c}`,controlToken:i};return t.log.info(`[057] Display delivery ${e.coreId} listening securely on port ${s}`),{info:u,async close(){await Promise.all([Qc(a),Qc(o)])}}}const cf=5057,pr="127.0.0.1",DI=["localhost","127.0.0.1","[::1]","::1"],LI=10,PI={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".woff2":"font/woff2",".png":"image/png",".ico":"image/vnd.microsoft.icon"};function Mm(t,e,r){let n;try{n=decodeURIComponent(e)}catch{return!1}if(n.includes("\0"))return!1;const o=$s(t,`.${Ob(n)}`);if(o!==t&&!o.startsWith(t+ru)||!ge(o)||!fa(o).isFile())return!1;const s=PI[Cb(o).toLowerCase()]??"application/octet-stream";return r.statusCode=200,r.setHeader("content-type",s),r.setHeader("x-content-type-options","nosniff"),yd(r),r.setHeader("cache-control",e.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-store"),jm(o).pipe(r),!0}function UI(t,e,r,n){return new Promise((o,s)=>{let i=n,a=e;const c=u=>{if(u.code==="EADDRINUSE"&&i>1){i--,a++,t.listen(a,r);return}t.off("error",c),s(u)};t.on("error",c),t.once("listening",()=>{t.off("error",c);const u=t.address();o(typeof u=="object"&&u?u.port:a)}),t.listen(a,r)})}function VI(t,e){const r=String(t.headers["sec-fetch-dest"]??"");if(HI.has(r))return`refusing to be embedded as ${r}`;const n=t.headers["sec-fetch-site"];return typeof n=="string"&&n!==""&&n!=="same-origin"&&n!=="none"?`refusing a ${n} request for ${e}`:null}const HI=new Set(["iframe","frame","embed","object","fencedframe"]);async function yb(t){const e=t.log??ig,r=$s(t.root),n=t.host??pr,o=n===pr||n==="::1"||n==="localhost",s=t.runtime?.path??t.storePath??ga();if(!t.runtime){const v=await WS(s);if(v)throw new md(v)}const i=t.runtime??ag({path:t.storePath,log:e,retention:t.retention,observe:t.observe}),a=import.meta.url.endsWith(".mjs")?VS(import.meta.url,{path:i.path,retention:i.retention,machineId:i.machine.id}):void 0,c=import.meta.url.endsWith(".mjs")?kp(import.meta.url,{path:i.path,machineId:i.machine.id}):void 0,u=import.meta.url.endsWith(".mjs")?kp(import.meta.url,{path:i.path,machineId:i.machine.id}):void 0,d=fk({runtime:i,log:e,version:t.version,activity:a,landscape:c,analytics:u,allowedHosts:o?DI:null}),l=Lm((v,g)=>{(async()=>{try{if(await d(v,g))return;if(v.method!=="GET"&&v.method!=="HEAD"){g.statusCode=405,g.setHeader("allow","GET, HEAD"),g.end();return}const I=new URL(v.url??"/","http://localhost").pathname,N=VI(v,I);if(N){e.warn(`[057] ${N}`),g.statusCode=403,g.setHeader("content-type","text/plain; charset=utf-8"),yd(g),g.end(`${N}
136
+ `);return}if(Mm(r,I==="/"?"/index.html":I,g)||!I.startsWith("/assets/")&&Mm(r,"/index.html",g))return;g.statusCode=404,g.setHeader("content-type","text/plain; charset=utf-8"),g.end(`not found
137
+ `)}catch(I){e.error(`[057] request failed: ${String(I)}`),g.headersSent||(g.statusCode=500),g.end()}})()}),m=await UI(l,t.port??cf,n,LI).catch(v=>{throw i.stop(),v}),p=o?"localhost":n;let h;if(t.display)try{h=await jI({storePath:i.path,loopbackUrl:`http://${pr}:${m}`,log:e})}catch(v){e.error(`[057] authenticated Display delivery could not start: ${String(v)}`)}return KS(i.path,{pid:process.pid,url:`http://${o?pr:n}:${m}`,version:t.version??"dev",contract:pd,store:i.path,startedAt:Date.now(),owner:t.owner??"cli",...h?{display:h.info}:{}}),{url:`http://${p}:${m}`,port:m,host:n,runtime:i,server:l,display:h?.info,close(){GS(i.path),a?.close(),c?.close(),u?.close();const v=new Promise(g=>l.close(()=>g()));return l.closeAllConnections?.(),Promise.all([v,h?.close()]).then(()=>i.stop())}}}function FI(t){return $s(Nb(new URL(".",t)),"..","dist")}function WI(t,e){switch(e.operation){case"summary":return{operation:"summary",result:t.summary(e.period)};case"availability":return{operation:"availability",result:t.availability(e.period)};case"compare":return{operation:"compare",result:t.compare(e.periodA,e.periodB)};case"breakdown":return{operation:"breakdown",result:t.breakdown(e.period,e.dimension)}}}const Ts="1.3.0";function KI(t){const e={command:"serve",activityOperation:"summary",activityPrevious:!1,activityAscii:!1,open:!1,yes:!1,desktop:!1},r=[...t],n=r[0];if(n&&!n.startsWith("-"))if(n==="status"||n==="compact"||n==="reset")e.command=n,r.shift();else if(n==="activity"){e.command="activity",r.shift();const o=r[0];if(o&&!o.startsWith("-")){const s=t1(o);if(s)e.activityOperation=s.operation,e.activityDimension=s.dimension,e.activityItemFilter=s.itemFilter;else if(o==="today")e.activityOperation="summary";else if(xA.includes(o))e.activityOperation=o;else return{...e,command:"help",error:`unknown activity operation: ${o}`};r.shift()}}else return{...e,command:"help",error:`unknown command: ${n}`};for(;r.length;){const o=r.shift(),[s,i]=o.includes("=")?GI(o,"="):[o,void 0],a=()=>i??r.shift();switch(s){case"-h":case"--help":e.command="help";break;case"-v":case"--version":e.command="version";break;case"--open":e.open=!0;break;case"--yes":case"-y":e.yes=!0;break;case"--desktop":e.desktop=!0;break;case"--last":{const c=a(),u=c?.match(/^(\d+)d$/),d=u?Number(u[1]):NaN;if(!Number.isInteger(d)||d<1)return{...e,command:"help",error:`--last needs a positive duration such as 7d, got ${c}`};e.activityLastDays=d;break}case"--previous":e.activityPrevious=!0;break;case"--by":{const c=a(),u=["model","executor","lifecycle","outcome","session","duration-band"];if(!c||!u.includes(c))return{...e,command:"help",error:`--by needs one of: ${u.join(", ")}`};e.activityDimension=c;break}case"--width":{const c=a(),u=Number(c);if(!Number.isInteger(u)||u<1)return{...e,command:"help",error:`--width needs a positive number of columns, got ${c}`};e.activityWidth=u;break}case"--color":{const c=a();if(c!=="always"&&c!=="never"&&c!=="auto")return{...e,command:"help",error:`--color needs always, never or auto, got ${c}`};e.activityColor=c;break}case"--ascii":e.activityAscii=!0;break;case"--port":{const c=a(),u=Number(c);if(!Number.isInteger(u)||u<0||u>65535)return{...e,command:"help",error:`--port needs a port number, got ${c}`};e.port=u;break}case"--host":{const c=a();if(!c)return{...e,command:"help",error:"--host needs a value"};e.host=c;break}case"--store":{const c=a();if(!c)return{...e,command:"help",error:"--store needs a path"};e.store=c;break}default:return{...e,command:"help",error:`unknown option: ${s}`}}}return e}function GI(t,e){const r=t.indexOf(e);return[t.slice(0,r),t.slice(r+1)]}const qI=`057 — a spatial interface for observing the shape of a computational workday
120
138
 
121
139
  057 observe this machine and serve the interface
122
140
  057 status where the store is, what it holds, what is observed
@@ -132,8 +150,8 @@ ${e.caCertificate.trimStart()}`,ca:e.caCertificate,minVersion:"TLSv1.3",maxVersi
132
150
  057 reset delete the local store
133
151
 
134
152
  Options
135
- --port <n> port to serve on (default ${Pd}; the next free one if taken)
136
- --host <addr> address to bind (default ${ar}; read the warning below first)
153
+ --port <n> port to serve on (default ${cf}; the next free one if taken)
154
+ --host <addr> address to bind (default ${pr}; read the warning below first)
137
155
  --store <path> store file to use (same as O57_STORE)
138
156
  --open open the interface in the default browser — the running
139
157
  057's, if one (or 057.app) already observes the store
@@ -159,41 +177,41 @@ to that trusted device on your local network. Reset deletes the SQLite store and
159
177
 
160
178
  --host binds beyond the loopback interface and serves your telemetry, unauthenticated, to
161
179
  anything that can reach that address. Do not do it on a network you do not control.
162
- `;function kr(t){return process.stdout.isTTY?`\x1B[2m${t}\x1B[0m`:t}function Gs(t){return t<1024?`${t} B`:t<1024**2?`${(t/1024).toFixed(1)} KB`:t<1024**3?`${(t/1024**2).toFixed(1)} MB`:`${(t/1024**3).toFixed(2)} GB`}function N1(t,e,r,n){const s=["",` 057 ${mo}`,` ${t}`,"",kr(" observing this machine only — its process table, and any AI runtime state it finds"),kr(` storing ${e}`),kr(` keeping ${r}`),kr(" sending local only to a paired Display; no account, no cloud, no analytics."),kr(" resetting 057 reset")];return n!==ar&&s.push("",` ! bound to ${n}, not loopback. Your telemetry is readable, without`," authentication, by anything that can reach this address."),s.push(""),s.join(`
163
- `)}async function T1(t){if(!process.stdin.isTTY)return!1;const e=Yv({input:process.stdin,output:process.stdout});try{return(await new Promise(n=>e.question(`${t} [y/N] `,n))).trim().toLowerCase()==="y"}finally{e.close()}}async function B1(t,e){const r=I1(t);if(r.command==="version")return console.log(mo),0;if(r.command==="help")return r.error&&console.error(`057: ${r.error}
164
- `),(r.error?console.error:console.log)(O1),r.error?2:0;r.store&&(process.env.O57_STORE=r.store);const n=sa(),s=ly();if(r.command==="status")return P1(n,s);if(r.command==="activity")return $1(n,s,r);if(r.command==="compact")return L1(n);if(r.command==="reset")return U1(n,r.yes);if(r.desktop)return D1(e,n,s,r.port??0);const o=r.port??V1(process.env.O57_PORT)??Pd,i=r.host??process.env.O57_HOST??ar;let a;try{a=await Mv({root:e,port:o,host:i,storePath:n,retention:s,log:Ld(),version:mo,display:!0})}catch(l){if(l instanceof Gl){const d=l.record;return r.open?(console.log(`
165
- ${l.message}${d.owner==="desktop"?" — 057.app":""}.
166
- Opening ${d.url}
167
- `),await lm(d.url),0):(console.error(`
168
- ${l.message}.
169
- Open ${d.url} (\`057 --open\`), or stop that 057 before starting another.
170
- `),1)}return sc(l)}console.log(N1(a.url,n,ia(s),i)),r.open&&await lm(a.url);let c=!1;const u=()=>{c||(c=!0,console.log(`
180
+ `;function Nr(t){return process.stdout.isTTY?`\x1B[2m${t}\x1B[0m`:t}function as(t){return t<1024?`${t} B`:t<1024**2?`${(t/1024).toFixed(1)} KB`:t<1024**3?`${(t/1024**2).toFixed(1)} MB`:`${(t/1024**3).toFixed(2)} GB`}function zI(t,e,r,n){const o=["",` 057 ${Ts}`,` ${t}`,"",Nr(" observing this machine only — its process table, and any AI runtime state it finds"),Nr(` storing ${e}`),Nr(` keeping ${r}`),Nr(" sending local only to a paired Display; no account, no cloud, no analytics."),Nr(" resetting 057 reset")];return n!==pr&&o.push("",` ! bound to ${n}, not loopback. Your telemetry is readable, without`," authentication, by anything that can reach this address."),o.push(""),o.join(`
181
+ `)}async function YI(t){if(!process.stdin.isTTY)return!1;const e=Ib({input:process.stdin,output:process.stdout});try{return(await new Promise(n=>e.question(`${t} [y/N] `,n))).trim().toLowerCase()==="y"}finally{e.close()}}async function XI(t,e){const r=KI(t);if(r.command==="version")return console.log(Ts),0;if(r.command==="help")return r.error&&console.error(`057: ${r.error}
182
+ `),(r.error?console.error:console.log)(qI),r.error?2:0;r.store&&(process.env.O57_STORE=r.store);const n=ga(),o=Uy();if(r.command==="status")return n1(n,o);if(r.command==="activity")return JI(n,o,r);if(r.command==="compact")return o1(n);if(r.command==="reset")return s1(n,r.yes);if(r.desktop)return r1(e,n,o,r.port??0);const s=r.port??i1(process.env.O57_PORT)??cf,i=r.host??process.env.O57_HOST??pr;let a;try{a=await yb({root:e,port:s,host:i,storePath:n,retention:o,log:uf(),version:Ts,display:!0})}catch(d){if(d instanceof md){const l=d.record;return r.open?(console.log(`
183
+ ${d.message}${l.owner==="desktop"?" — 057.app":""}.
184
+ Opening ${l.url}
185
+ `),await _m(l.url),0):(console.error(`
186
+ ${d.message}.
187
+ Open ${l.url} (\`057 --open\`), or stop that 057 before starting another.
188
+ `),1)}return vc(d)}console.log(zI(a.url,n,ba(o),i)),r.open&&await _m(a.url);let c=!1;const u=()=>{c||(c=!0,console.log(`
171
189
  057 stopping — history is on disk
172
- `),a.close().then(()=>process.exit(0)))};return process.on("SIGINT",u),process.on("SIGTERM",u),new Promise(()=>{})}function $1(t,e,r){let n;try{n=aa(t)}catch(s){return sc(s)}try{const s=Date.now(),o=_1(s,r.activityLastDays),i=ky(n,e,_r().id,s);if(r.activityOperation==="compare"&&!r.activityPrevious)return console.error(`057: activity compare currently requires --previous
173
- `),2;let a;if(r.activityOperation==="compare")a={operation:"compare",periodA:o,periodB:M1(o)};else if(r.activityOperation==="breakdown"){if(!r.activityDimension)return console.error(`057: activity breakdown requires --by <dimension>
174
- `),2;a={operation:"breakdown",period:o,dimension:r.activityDimension}}else r.activityOperation==="availability"?a={operation:"availability",period:o}:a={operation:"summary",period:o};return process.stdout.write(qt(E1(i,a),r.activityItemFilter,R1(r,process.stdout,process.env))),0}finally{n.close()}}function R1(t,e,r){const n=e.isTTY===!0,s=t.activityWidth??(n&&e.columns?e.columns:80),o=r.FORCE_COLOR!==void 0&&r.FORCE_COLOR!=="0"&&r.FORCE_COLOR!=="false",i=t.activityColor??(o?"always":"auto"),a=i==="always"||i==="auto"&&n&&!r.NO_COLOR&&r.TERM!=="dumb",c=r.LC_ALL||r.LC_CTYPE||r.LANG,u=!c||/utf-?8/i.test(c);return{width:s,color:a,ascii:t.activityAscii||!u}}function _1(t,e){if(e!==void 0)return{from:t-e*864e5,to:t};const r=new Date(t);return r.setHours(0,0,0,0),{from:r.getTime(),to:t}}function M1(t){const e=t.to-t.from;return{from:t.from-e,to:t.from}}function j1(t){switch(t){case"running":return{operation:"breakdown",dimension:"lifecycle",itemFilter:"running"};case"waiting":return{operation:"breakdown",dimension:"lifecycle",itemFilter:"waiting"};case"failed":return{operation:"breakdown",dimension:"outcome",itemFilter:"failed"};case"sessions":return{operation:"breakdown",dimension:"session"};case"usage":case"concurrency":return{operation:"summary"};default:return}}async function D1(t,e,r,n){const s=c=>{process.stdout.write(`${JSON.stringify(c)}
175
- `)};let o;try{o=await Mv({root:t,port:n,host:ar,storePath:e,retention:r,log:Ld(),version:mo,owner:"desktop",display:!0})}catch(c){if(c instanceof Gl){const u=c.record;return s({event:"running",url:u.url,pid:u.pid,version:u.version,owner:u.owner,contract:u.contract}),0}return c instanceof gt?(s({event:"error",kind:"store",message:c.message,remedy:c.remedy}),1):(s({event:"error",kind:"start",message:c instanceof Error?c.message:String(c)}),1)}let i=!1;const a=c=>{i||(i=!0,process.stderr.write(`[057] stopping (${c}) — history is on disk
176
- `),o.close().then(()=>process.exit(0)))};return process.on("SIGINT",()=>a("SIGINT")),process.on("SIGTERM",()=>a("SIGTERM")),process.stdin.on("end",()=>a("app closed its pipe")),process.stdin.on("close",()=>a("app closed its pipe")),process.stdin.resume(),s({event:"ready",url:`http://${ar}:${o.port}`,pid:process.pid,version:mo,store:e,contract:Wl,display:o.display}),new Promise(()=>{})}function P1(t,e){let r=null;if(t!==":memory:"&&fe(t))try{r=aa(t)}catch(n){return sc(n)}try{const n=r?.stats()??{events:0,claims:0,bySource:[],earliest:null,latest:null},s=r?.sizeBytes()??{db:0,wal:0,shm:0,total:0},o=oa(t).map(a=>Vl(a)).filter(a=>a!==null).map(a=>"0"+a.toString(8)).join(" ");if(console.log(`
177
- store ${t}${ay()?" (from O57_STORE)":""}
190
+ `),a.close().then(()=>process.exit(0)))};return process.on("SIGINT",u),process.on("SIGTERM",u),new Promise(()=>{})}function JI(t,e,r){let n;try{n=wa(t)}catch(o){return vc(o)}try{const o=Date.now(),s=QI(o,r.activityLastDays),i=ng(n,e,Vr().id,o);if(r.activityOperation==="compare"&&!r.activityPrevious)return console.error(`057: activity compare currently requires --previous
191
+ `),2;let a;if(r.activityOperation==="compare")a={operation:"compare",periodA:s,periodB:e1(s)};else if(r.activityOperation==="breakdown"){if(!r.activityDimension)return console.error(`057: activity breakdown requires --by <dimension>
192
+ `),2;a={operation:"breakdown",period:s,dimension:r.activityDimension}}else r.activityOperation==="availability"?a={operation:"availability",period:s}:a={operation:"summary",period:s};return process.stdout.write(tr(WI(i,a),r.activityItemFilter,ZI(r,process.stdout,process.env))),0}finally{n.close()}}function ZI(t,e,r){const n=e.isTTY===!0,o=t.activityWidth??(n&&e.columns?e.columns:80),s=r.FORCE_COLOR!==void 0&&r.FORCE_COLOR!=="0"&&r.FORCE_COLOR!=="false",i=t.activityColor??(s?"always":"auto"),a=i==="always"||i==="auto"&&n&&!r.NO_COLOR&&r.TERM!=="dumb",c=r.LC_ALL||r.LC_CTYPE||r.LANG,u=!c||/utf-?8/i.test(c);return{width:o,color:a,ascii:t.activityAscii||!u}}function QI(t,e){if(e!==void 0)return{from:t-e*864e5,to:t};const r=new Date(t);return r.setHours(0,0,0,0),{from:r.getTime(),to:t}}function e1(t){const e=t.to-t.from;return{from:t.from-e,to:t.from}}function t1(t){switch(t){case"running":return{operation:"breakdown",dimension:"lifecycle",itemFilter:"running"};case"waiting":return{operation:"breakdown",dimension:"lifecycle",itemFilter:"waiting"};case"failed":return{operation:"breakdown",dimension:"outcome",itemFilter:"failed"};case"sessions":return{operation:"breakdown",dimension:"session"};case"usage":case"concurrency":return{operation:"summary"};default:return}}async function r1(t,e,r,n){const o=c=>{process.stdout.write(`${JSON.stringify(c)}
193
+ `)};let s;try{s=await yb({root:t,port:n,host:pr,storePath:e,retention:r,log:uf(),version:Ts,owner:"desktop",display:!0})}catch(c){if(c instanceof md){const u=c.record;return o({event:"running",url:u.url,pid:u.pid,version:u.version,owner:u.owner,contract:u.contract}),0}return c instanceof xt?(o({event:"error",kind:"store",message:c.message,remedy:c.remedy}),1):(o({event:"error",kind:"start",message:c instanceof Error?c.message:String(c)}),1)}let i=!1;const a=c=>{i||(i=!0,process.stderr.write(`[057] stopping (${c}) — history is on disk
194
+ `),s.close().then(()=>process.exit(0)))};return process.on("SIGINT",()=>a("SIGINT")),process.on("SIGTERM",()=>a("SIGTERM")),process.stdin.on("end",()=>a("app closed its pipe")),process.stdin.on("close",()=>a("app closed its pipe")),process.stdin.resume(),o({event:"ready",url:`http://${pr}:${s.port}`,pid:process.pid,version:Ts,store:e,contract:pd,display:s.display}),new Promise(()=>{})}function n1(t,e){let r=null;if(t!==":memory:"&&ge(t))try{r=wa(t)}catch(n){return vc(n)}try{const n=r?.stats()??{events:0,claims:0,bySource:[],earliest:null,latest:null},o=r?.sizeBytes()??{db:0,wal:0,shm:0,total:0},s=va(t).map(a=>dd(a)).filter(a=>a!==null).map(a=>"0"+a.toString(8)).join(" ");if(console.log(`
195
+ store ${t}${Dy()?" (from O57_STORE)":""}
178
196
  schema ${r?r.schemaVersion:"none"}
179
- size ${Gs(s.total)} ${kr(`(db ${Gs(s.db)}, wal ${Gs(s.wal)})`)}
197
+ size ${as(o.total)} ${Nr(`(db ${as(o.db)}, wal ${as(o.wal)})`)}
180
198
  events ${n.events.toLocaleString()}
181
199
  claims ${n.claims.toLocaleString()}
182
- keeping ${ia(e)}
183
- permissions ${o||"none — no store yet"}
200
+ keeping ${ba(e)}
201
+ permissions ${s||"none — no store yet"}
184
202
  `),n.bySource.length===0)console.log(` nothing has been captured yet
185
- `);else{for(const a of n.bySource){const c=`${new Date(a.first).toISOString().slice(0,10)} → ${new Date(a.last).toISOString().slice(0,10)}`;console.log(` ${a.source.padEnd(20)}${String(a.events).padStart(10)} events ${kr(c)}`)}console.log("")}const i=uy();return i&&console.log(` a store from a previous layout is at ${i} and is not in use
186
- `),0}finally{r?.close()}}function L1(t){let e;try{e=Cy({path:t,observe:!1,log:Ld()})}catch(r){return sc(r)}try{const r=e.store.sizeBytes().total,n=e.sweep();e.store.compact();const s=e.store.sizeBytes().total;return console.log(`
203
+ `);else{for(const a of n.bySource){const c=`${new Date(a.first).toISOString().slice(0,10)} → ${new Date(a.last).toISOString().slice(0,10)}`;console.log(` ${a.source.padEnd(20)}${String(a.events).padStart(10)} events ${Nr(c)}`)}console.log("")}const i=Py();return i&&console.log(` a store from a previous layout is at ${i} and is not in use
204
+ `),0}finally{r?.close()}}function o1(t){let e;try{e=ag({path:t,observe:!1,log:uf()})}catch(r){return vc(r)}try{const r=e.store.sizeBytes().total,n=e.sweep();e.store.compact();const o=e.store.sizeBytes().total;return console.log(`
187
205
  removed ${n.processEvents+n.otherEvents} expired events
188
- ${Gs(r)} → ${Gs(s)}
189
- `),0}finally{e.stop()}}async function U1(t,e){const r=wA(t);console.log(`
206
+ ${as(r)} → ${as(o)}
207
+ `),0}finally{e.stop()}}async function s1(t,e){const r=ZA(t);console.log(`
190
208
  this deletes, permanently:
191
- `);for(const n of r)console.log(` ${n}`);if(console.log(""),!e&&!await T1(" delete the local store?"))return console.log(` nothing was deleted
192
- `),1;for(const n of r)fm(n,{recursive:!0,force:!0});return console.log(` deleted. the next run starts a new store.
193
- `),0}function Ld(){return{info:t=>{process.stderr.write(`${kr(t)}
209
+ `);for(const n of r)console.log(` ${n}`);if(console.log(""),!e&&!await YI(" delete the local store?"))return console.log(` nothing was deleted
210
+ `),1;for(const n of r)Dm(n,{recursive:!0,force:!0});return console.log(` deleted. the next run starts a new store.
211
+ `),0}function uf(){return{info:t=>{process.stderr.write(`${Nr(t)}
194
212
  `)},warn:t=>{process.stderr.write(`${t}
195
213
  `)},error:t=>{process.stderr.write(`${t}
196
- `)}}}function sc(t){if(t instanceof gt)return console.error(`
214
+ `)}}}function vc(t){if(t instanceof xt)return console.error(`
197
215
  057: ${t.message}
198
216
  ${t.remedy}
199
217
  `),1;const e=t?.code;return e==="EADDRINUSE"?(console.error(`
@@ -202,4 +220,4 @@ anything that can reach that address. Do not do it on a network you do not contr
202
220
  057: cannot bind that address or port (${e}).
203
221
  `),1):(console.error(`
204
222
  057: ${t instanceof Error?t.message:String(t)}
205
- `),1)}function V1(t){if(!t)return;const e=Number(t);return Number.isInteger(e)&&e>=0&&e<=65535?e:void 0}async function lm(t){const e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open",{spawn:r}=await import("node:child_process");try{r(e,[t],{stdio:"ignore",detached:!0}).unref()}catch{}}async function dO(t){const e=await B1(t,x1(import.meta.url));e!==0&&process.exit(e)}export{x1 as defaultRoot,dO as main,B1 as run};
223
+ `),1)}function i1(t){if(!t)return;const e=Number(t);return Number.isInteger(e)&&e>=0&&e<=65535?e:void 0}async function _m(t){const e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open",{spawn:r}=await import("node:child_process");try{r(e,[t],{stdio:"ignore",detached:!0}).unref()}catch{}}async function TC(t){const e=await XI(t,FI(import.meta.url));e!==0&&process.exit(e)}export{FI as defaultRoot,TC as main,XI as run};