@tansr/cli 0.10.3 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/tansr-artifacts.json +1223 -831
- package/tansr-bg-A35DNHK2.mjs +5 -0
- package/tansr-chunk-2CIB4KCJ.mjs +5 -0
- package/{tansr-chunk-XXBNISJJ.mjs → tansr-chunk-2HZJSKHM.mjs} +2 -2
- package/{tansr-chunk-CJP7YEGC.mjs → tansr-chunk-2PB54HDR.mjs} +2 -2
- package/tansr-chunk-33QZBUL6.mjs +6 -0
- package/tansr-chunk-3YSQG6KY.mjs +5 -0
- package/tansr-chunk-4DAH4AIH.mjs +7 -0
- package/{tansr-chunk-HHL7HM62.mjs → tansr-chunk-4IWNKAT5.mjs} +2 -2
- package/tansr-chunk-4YAEV3T6.mjs +9 -0
- package/tansr-chunk-546BDI3V.mjs +7 -0
- package/tansr-chunk-6N333TUL.mjs +241 -0
- package/{tansr-chunk-KQVXXXEF.mjs → tansr-chunk-6QKU3GNA.mjs} +2 -2
- package/tansr-chunk-AHUB2IHT.mjs +5 -0
- package/tansr-chunk-AOH7YPF3.mjs +8 -0
- package/{tansr-chunk-C6COFFZK.mjs → tansr-chunk-B2O4DB4K.mjs} +2 -2
- package/tansr-chunk-C2NTVBEY.mjs +5 -0
- package/{tansr-chunk-D7VSW2LQ.mjs → tansr-chunk-C75DEEUJ.mjs} +2 -2
- package/tansr-chunk-ECYZ457U.mjs +5 -0
- package/tansr-chunk-EFN24XG3.mjs +25 -0
- package/tansr-chunk-ENRIN7EG.mjs +7 -0
- package/{tansr-chunk-RVSBSUXE.mjs → tansr-chunk-ITZBYACC.mjs} +2 -2
- package/{tansr-chunk-GMPMRXL4.mjs → tansr-chunk-IZZYKHSW.mjs} +3 -3
- package/tansr-chunk-JIC3VWLQ.mjs +252 -0
- package/tansr-chunk-JTGWG4BG.mjs +32 -0
- package/tansr-chunk-LA3LGOYQ.mjs +11 -0
- package/tansr-chunk-MAMODDQN.mjs +5 -0
- package/tansr-chunk-N644DEOO.mjs +5 -0
- package/tansr-chunk-NQOYEFEE.mjs +5 -0
- package/tansr-chunk-O7P4OFK7.mjs +7 -0
- package/tansr-chunk-OEHA7T4Q.mjs +26 -0
- package/{tansr-chunk-ZV3NCXTD.mjs → tansr-chunk-OKNSOZDU.mjs} +7 -7
- package/tansr-chunk-OT4KIQLR.mjs +9 -0
- package/tansr-chunk-OUOTEH4A.mjs +5 -0
- package/tansr-chunk-Q3XDAUKT.mjs +65 -0
- package/tansr-chunk-RFH7OCN6.mjs +5 -0
- package/tansr-chunk-RUYIVG72.mjs +12 -0
- package/tansr-chunk-SCFXBKV6.mjs +8 -0
- package/tansr-chunk-SHLU4JN2.mjs +5 -0
- package/{tansr-chunk-M774GK3P.mjs → tansr-chunk-SIV2666W.mjs} +2 -2
- package/tansr-chunk-SX3XZNN6.mjs +6 -0
- package/tansr-chunk-SXNTYWJY.mjs +8 -0
- package/tansr-chunk-UVL2XWKL.mjs +5 -0
- package/tansr-chunk-V4HGMAJS.mjs +375 -0
- package/{tansr-chunk-2X337GKC.mjs → tansr-chunk-W2WIN3M2.mjs} +2 -2
- package/tansr-chunk-WAYVH5ON.mjs +5 -0
- package/tansr-chunk-WPKFARCU.mjs +11 -0
- package/{tansr-chunk-726Y5F3M.mjs → tansr-chunk-YEYFEVYF.mjs} +2 -2
- package/tansr-chunk-YK3CE3JM.mjs +5 -0
- package/tansr-chunk-YOSRXZWY.mjs +5 -0
- package/tansr-compaction-history-LZXZTWBV.mjs +5 -0
- package/tansr-compaction-log-H2SPLK24.mjs +5 -0
- package/tansr-indexed-CPYJVPFI.mjs +5 -0
- package/tansr-lock-XWDVZMLY.mjs +5 -0
- package/tansr-main-6GDLXIRQ.mjs +7 -0
- package/tansr-render-SVMDLHLN.mjs +6 -0
- package/tansr-restore-7PS7WCJR.mjs +5 -0
- package/tansr-run-acp-entry-EQGUKZ5R.mjs +68 -0
- package/tansr-run-approvals-entry-SEYBHLS2.mjs +12 -0
- package/{tansr-run-auth-entry-7HA4C4NJ.mjs → tansr-run-auth-entry-R3GKGKWX.mjs} +2 -2
- package/tansr-run-doctor-B3XK72DW.mjs +11 -0
- package/tansr-run-headless-entry-4XTAVPTW.mjs +84 -0
- package/tansr-run-init-entry-GH2KDGI6.mjs +5 -0
- package/tansr-run-logout-entry-PLGYDEOB.mjs +5 -0
- package/tansr-run-mcp-serve-entry-UHK4WSKL.mjs +14 -0
- package/tansr-run-orchestrate-entry-M7R3433X.mjs +11 -0
- package/tansr-run-org-entry-UONLGJIJ.mjs +17 -0
- package/tansr-run-policy-entry-NNQCV5WS.mjs +16 -0
- package/tansr-run-profile-entry-PV6OO7FV.mjs +14 -0
- package/tansr-run-serve-entry-GWZQZ37P.mjs +16 -0
- package/tansr-run-sessions-entry-WL7YLRJL.mjs +25 -0
- package/tansr-run-update-entry-YI47IPCC.mjs +5 -0
- package/tansr-spill-YVUTIFOS.mjs +5 -0
- package/tansr-src-LPMSGRKO.mjs +5 -0
- package/{tansr-src-A6WDMY6X.mjs → tansr-src-RQJPOVDN.mjs} +50 -50
- package/tansr-startup-account-MYFJ3NOL.mjs +7 -0
- package/{tansr-startup-model-I6LOCFDP.mjs → tansr-startup-model-BCGEYUM4.mjs} +3 -3
- package/tansr-storage-journal-4E274MUA.mjs +5 -0
- package/tansr-todos-replay-TVQKP7OD.mjs +5 -0
- package/tansr-tui-3Q7Z3ALV.mjs +73 -0
- package/tansr.mjs +1 -1
- package/tansrd.mjs +444 -265
- package/tansr-bg-EAYYM4XW.mjs +0 -5
- package/tansr-chunk-2C6JKHKM.mjs +0 -25
- package/tansr-chunk-4LNN4SQL.mjs +0 -22
- package/tansr-chunk-5T7X32UX.mjs +0 -6
- package/tansr-chunk-5TJVZSZE.mjs +0 -6
- package/tansr-chunk-74H5GQTJ.mjs +0 -35
- package/tansr-chunk-7T6OLLFW.mjs +0 -12
- package/tansr-chunk-BX7CF5RQ.mjs +0 -25
- package/tansr-chunk-DN22GXHD.mjs +0 -8
- package/tansr-chunk-F7C6ITED.mjs +0 -5
- package/tansr-chunk-GDJ5YVNY.mjs +0 -5
- package/tansr-chunk-GR6BWQGG.mjs +0 -38
- package/tansr-chunk-HRKJLVKC.mjs +0 -7
- package/tansr-chunk-I3TOVAA6.mjs +0 -5
- package/tansr-chunk-IZICOKKF.mjs +0 -279
- package/tansr-chunk-J2LWM3S7.mjs +0 -5
- package/tansr-chunk-M6XHWCMA.mjs +0 -11
- package/tansr-chunk-MWHLITGY.mjs +0 -11
- package/tansr-chunk-N3R2URKL.mjs +0 -5
- package/tansr-chunk-NA22YT73.mjs +0 -5
- package/tansr-chunk-OSK64SU3.mjs +0 -5
- package/tansr-chunk-QEKVLX7W.mjs +0 -5
- package/tansr-chunk-QHEQQ2JB.mjs +0 -9
- package/tansr-chunk-QUFHVA3F.mjs +0 -5
- package/tansr-chunk-QWGSXFEJ.mjs +0 -7
- package/tansr-chunk-SJFDQLLC.mjs +0 -5
- package/tansr-chunk-X4GLXJ2Z.mjs +0 -67
- package/tansr-chunk-X5REV3T3.mjs +0 -8
- package/tansr-chunk-ZQ3ZK7IL.mjs +0 -37
- package/tansr-main-STVTNYAI.mjs +0 -7
- package/tansr-render-PUEISX75.mjs +0 -6
- package/tansr-run-acp-entry-6J44XOYJ.mjs +0 -63
- package/tansr-run-approvals-entry-HQWSIW3P.mjs +0 -12
- package/tansr-run-doctor-7T6IAXYE.mjs +0 -10
- package/tansr-run-headless-entry-XEFQC5LE.mjs +0 -78
- package/tansr-run-init-entry-3VKXS2WK.mjs +0 -5
- package/tansr-run-logout-entry-VNCNNCSS.mjs +0 -5
- package/tansr-run-mcp-serve-entry-5KLWER3G.mjs +0 -14
- package/tansr-run-orchestrate-entry-AR57AZLR.mjs +0 -11
- package/tansr-run-org-entry-TJPRLGCL.mjs +0 -17
- package/tansr-run-policy-entry-DHMQ3PAP.mjs +0 -16
- package/tansr-run-profile-entry-LOFPHFG4.mjs +0 -14
- package/tansr-run-serve-entry-CHVKUY5J.mjs +0 -99
- package/tansr-run-sessions-entry-JOMFB5LJ.mjs +0 -23
- package/tansr-run-update-entry-XI6KG7UI.mjs +0 -5
- package/tansr-sqlite-event-store-UQLSSZKP.mjs +0 -26
- package/tansr-sqlite-spool-implementation-LHEIRSUX.mjs +0 -29
- package/tansr-src-KOEPYVXX.mjs +0 -5
- package/tansr-startup-account-7ZFSP3FV.mjs +0 -7
- package/tansr-tui-OWG3JNA6.mjs +0 -75
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
+
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
+
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
+
import{$,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,_,a,aa,b,ba,c,ca,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./tansr-chunk-W2WIN3M2.mjs";import"./tansr-chunk-OT4KIQLR.mjs";import"./tansr-chunk-2HZJSKHM.mjs";import"./tansr-chunk-AMMPDY4V.mjs";import"./tansr-chunk-N644DEOO.mjs";import"./tansr-chunk-546BDI3V.mjs";import"./tansr-chunk-OEHA7T4Q.mjs";import"./tansr-chunk-UVL2XWKL.mjs";import"./tansr-chunk-NQOYEFEE.mjs";import"./tansr-chunk-YOSRXZWY.mjs";import"./tansr-chunk-WAYVH5ON.mjs";import"./tansr-chunk-AHUB2IHT.mjs";import"./tansr-chunk-RFH7OCN6.mjs";import"./tansr-chunk-SHLU4JN2.mjs";import"./tansr-chunk-JIC3VWLQ.mjs";import"./tansr-chunk-C7GGA5ID.mjs";import"./tansr-chunk-O7P4OFK7.mjs";import"./tansr-chunk-6N333TUL.mjs";import"./tansr-chunk-EFN24XG3.mjs";import"./tansr-chunk-OKAA4BJC.mjs";import"./tansr-chunk-4YAEV3T6.mjs";import"./tansr-chunk-AOH7YPF3.mjs";import"./tansr-chunk-DIT3PBNB.mjs";import"./tansr-chunk-YK3CE3JM.mjs";import"./tansr-chunk-4DAH4AIH.mjs";import"./tansr-chunk-ENRIN7EG.mjs";import"./tansr-chunk-MAMODDQN.mjs";import"./tansr-chunk-LA3LGOYQ.mjs";import"./tansr-chunk-3YSQG6KY.mjs";import"./tansr-chunk-RRAMVVYF.mjs";export{c as BACKGROUND_DIR_NAME,f as BACKGROUND_SELF_HEAL_SOURCES,e as BACKGROUND_TASK_STATUSES,a as BG_MESSAGE_KEY,b as BG_MESSAGE_KEYS,A as BG_RUNNER_ENDPOINT_ENV,B as BG_RUNNER_TOKEN_ENV,Q as BG_TASK_ID_ENV,Z as DEFAULT_KILL_GRACE_MS,_ as KILL_POLL_INTERVAL_MS,X as LOG_TAIL_MAX_BYTES,Y as LOG_TAIL_MAX_LINES,I as PROCESS_IDENTITY_PROBE_TIMEOUT_MS,d as PROMPT_SUMMARY_MAX_CHARS,g as RENAME_RETRY_DELAYS_MS,C as RUNNER_REQUEST_TIMEOUT_MS,L as WORKTREES_DIR_NAME,U as attachBackgroundSessionId,h as backgroundDirPath,k as backgroundFinalSentinelPath,j as backgroundLogPath,i as backgroundRecordPath,K as compareProcessIdentity,R as createRunnerIdentity,z as displayStatusOf,t as finalizeBackgroundRecord,W as finalizeBackgroundTask,l as generateBackgroundTaskId,N as generateWorktreeName,y as isPidAlive,O as isValidWorktreeName,T as killProcessTree,S as launchBackgroundTask,u as listBackgroundRecords,v as listBackgroundRecordsSync,p as parseBackgroundRecord,$ as parseBgArgs,J as probeProcessIdentity,r as readBackgroundRecord,aa as readLogTail,n as redactArgv,x as removeBackgroundRecord,F as requestRunner,H as requestRunnerStop,ca as runBgEntry,D as runnerEndpointFor,P as setupWorktree,V as startBackgroundRunnerEndpoint,E as startRunnerEndpoint,m as summarizePrompt,ba as toDisplayRecord,q as toPublicRecord,s as updateBackgroundRecord,G as verifyRunnerIdentity,M as worktreesDirPath,o as writeBackgroundRecord,w as writeBackgroundRecordSync};
|
|
5
|
+
//# sourceMappingURL=tansr-bg-A35DNHK2.mjs.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
+
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
+
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
+
import{wb as b}from"./tansr-chunk-Q3XDAUKT.mjs";import{a as C}from"./tansr-chunk-OT4KIQLR.mjs";import{a as _,b as I,c as A,d as g,e as R,f as T,g as M}from"./tansr-chunk-2HZJSKHM.mjs";import{h as k,l as w,m as x,n as G}from"./tansr-chunk-OKAA4BJC.mjs";import{m as E}from"./tansr-chunk-YK3CE3JM.mjs";function se(e){return t=>{if(t.status==="completed"&&t.stage!=="ready"||t.stage==="ready"&&t.status==="started")return;let r=E("init.stage."+t.stage);e(t.status==="failed"?E("init.failed",{stage:r}):t.status==="cancelled"?E("init.cancelled",{stage:r}):t.stage==="ready"?r:E("init.loading",{stage:r}))}}function ae(e){return e?.cacheMissAlert===void 0?null:{type:"cost.cache_miss",model:e.model,inputTokens:e.cacheMissAlert.inputTokens,threshold:e.cacheMissAlert.threshold}}import{randomUUID as Z}from"node:crypto";import ee from"node:os";import te from"node:path";var F=w,q=6e4,v=10*6e4,H=1e4,L=5,B=1e4,V=[C];function X(e,t,r){if(V.includes(e))return null;let o=r.find(a=>a.handle===e);return o!==void 0?{modelHandle:o.handle,modelId:t}:{modelHandle:`${e}/${t}`,modelId:t}}function W(e,t){if(e.outcome!=="success")return null;let r=X(e.provider,e.model,t);if(r===null)return null;let o=x.includes(e.purpose)?{purpose:e.purpose}:{};if(e.usage!==void 0)return{...r,...o,inTokens:e.usage.inputTokens,outTokens:e.usage.outputTokens,cacheReadTokens:e.usage.cacheReadInputTokens??0,cacheWriteTokens:e.usage.cacheCreationInputTokens??0,estimated:!1};let a=e.features.estimatedTokens,d=e.estimatedOutputTokens??0;return a<=0&&d<=0?null:{...r,...o,inTokens:Math.max(0,Math.round(a)),outTokens:Math.max(0,Math.round(d)),cacheReadTokens:0,cacheWriteTokens:0,estimated:!0}}function ne(e){let t=e.now??Date.now,r=e.generateId??Z,o=e.homedir??ee.homedir(),a=e.queueDir??_(e.env,o,e.profileKeyId),d=e.queueDir===void 0&&e.profileKeyId!==void 0?_(e.env,o):null,P=d===a?null:d,i=te.join(a,I(r())),K=e.requestTimeoutMs??H,$=`${e.apiBaseUrl.replace(/\/+$/,"")}${k.usage}`,j=()=>e.env[b]==="1",U=Promise.resolve(),c=l=>(U=U.then(l,l),U),s=null,S=!1,Y=async()=>{s===null&&(s=(await g(i)).length)},h=async l=>{if(j())return;let p=await T(a,i,t()-v);P!==null&&p.push(...await T(P,i,t()-v));for(let f of p){let u=await g(f.file);u.length>0&&(await A(i,u),s=s===null?null:s+u.length),await M(f.file)}let n=await g(i);if(s=n.length,n.length===0)return;let m=!1;try{for(let f=0;n.length>0&&f<l;f+=1){let u=n.slice(0,F),J=u.map(({purpose:z,...D})=>{let N=G(z);return N===void 0?D:{...D,purpose:N}}),y;try{y=await e.fetchImpl($,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({events:J}),signal:AbortSignal.timeout(K)})}catch{return}if(y.status===202){n=n.slice(u.length),m=!0;continue}if(y.status===400){n=n.slice(u.length),m=!0;continue}return}}finally{(m||n.length===0)&&(await R(i,n),s=n.length)}},O=e.flushIntervalMs??q,Q=O>0?setInterval(()=>{c(()=>h(Number.MAX_SAFE_INTEGER))},O).unref():null;return c(()=>h(Number.MAX_SAFE_INTEGER)),{onRequestMeasured:l=>{if(S)return;let p=W(l,e.directEndpoints);if(p===null)return;let n=e.sessionId?.(),m={clientEventId:r(),...p,occurredAt:new Date(t()).toISOString(),...n!==void 0?{sessionId:n}:{}};c(async()=>{await Y(),!(s!==null&&s>=B)&&(await A(i,[m]),s=s===null?null:s+1)})},flush:()=>c(()=>h(Number.MAX_SAFE_INTEGER)),close:async()=>{S||(S=!0,Q!==null&&clearInterval(Q),await c(()=>h(L)))}}}export{se as a,ae as b,ne as c};
|
|
5
|
+
//# sourceMappingURL=tansr-chunk-2CIB4KCJ.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
2
|
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
3
|
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
-
import{a as I,b as h,c as l,e as v,g as b,i as S,j as F
|
|
4
|
+
import{f as k}from"./tansr-chunk-546BDI3V.mjs";import{a as I,b as h,c as l,e as v,g as b,i as S,j as F}from"./tansr-chunk-AHUB2IHT.mjs";import{m as P}from"./tansr-chunk-OKAA4BJC.mjs";import{existsSync as ee,readFileSync as te}from"node:fs";import ne from"node:os";import{appendFile as U,mkdir as E,readdir as _,readFile as C,rm as T,stat as M,writeFile as O}from"node:fs/promises";import x from"node:os";import u from"node:path";var N="usage-queue";function g(e,n=x.homedir(),t){let r=e.TANSR_CONFIG_DIR?.trim(),i=r!==void 0&&r!==""?r:u.join(n,".tansr"),o=u.join(i,N);if(t===void 0||t==="")return o;let s=t.replace(/[^A-Za-z0-9-]/g,a=>`_${a.codePointAt(0).toString(16)}`);return u.join(o,s)}function ce(e,n=x.homedir(),t){let r=F(e,n);return r!==null?r.usageQueueDir:g(e,n,t)}var L=/^q-[0-9a-f-]+\.ndjson$/;function de(e){return`q-${e}.ndjson`}function V(e){let n;try{n=JSON.parse(e)}catch{return null}if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;return typeof t.clientEventId!="string"||t.clientEventId===""||t.clientEventId.length>64||typeof t.modelHandle!="string"||t.modelHandle===""||typeof t.modelId!="string"||t.modelId===""||typeof t.inTokens!="number"||!Number.isInteger(t.inTokens)||t.inTokens<0||typeof t.outTokens!="number"||!Number.isInteger(t.outTokens)||t.outTokens<0||typeof t.cacheReadTokens!="number"||!Number.isInteger(t.cacheReadTokens)||t.cacheReadTokens<0||typeof t.cacheWriteTokens!="number"||!Number.isInteger(t.cacheWriteTokens)||t.cacheWriteTokens<0||typeof t.estimated!="boolean"||typeof t.occurredAt!="string"?null:{clientEventId:t.clientEventId,modelHandle:t.modelHandle,modelId:t.modelId,inTokens:t.inTokens,outTokens:t.outTokens,cacheReadTokens:t.cacheReadTokens,cacheWriteTokens:t.cacheWriteTokens,estimated:t.estimated,occurredAt:t.occurredAt,...typeof t.sessionId=="string"&&t.sessionId!==""?{sessionId:t.sessionId}:{},...typeof t.purpose=="string"&&P.includes(t.purpose)?{purpose:t.purpose}:{}}}function Q(e){return e.map(n=>JSON.stringify(n)).join(`
|
|
5
5
|
`)+`
|
|
6
6
|
`}async function ge(e,n){if(n.length!==0)try{await E(u.dirname(e),{recursive:!0}),await U(e,Q(n),"utf8")}catch{}}async function fe(e){let n;try{n=await C(e,"utf8")}catch{return[]}let t=[];for(let r of n.split(/\r?\n/)){if(r.trim()==="")continue;let i=V(r);i!==null&&t.push(i)}return t}async function ye(e,n){try{if(n.length===0){await T(e,{force:!0});return}await E(u.dirname(e),{recursive:!0}),await O(e,Q(n),"utf8")}catch{}}async function me(e,n,t){let r;try{r=await _(e)}catch{return[]}let i=u.basename(n),o=[];for(let s of r){if(!L.test(s)||s===i)continue;let a=u.join(e,s);try{let p=await M(a);p.mtimeMs<t&&o.push({file:a,mtimeMs:p.mtimeMs})}catch{}}return o}async function pe(e){try{await T(e,{force:!0})}catch{}}import{readFileSync as W}from"node:fs";import H from"node:path";var q="init-state.json";function w(e){return H.join(e,q)}function J(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e;if(n.version!==1)return null;let t=n.state;if(t!=="uninited"&&t!=="inited")return null;let r=n.identityIndex;if(r!==void 0&&(typeof r!="string"||!I.test(r)))return null;let i=n.completedAt;return i!==void 0&&typeof i!="string"?null:{version:1,state:t,...r!==void 0?{identityIndex:r}:{},...i!==void 0?{completedAt:i}:{}}}function A(e){let n;try{n=W(e,"utf8")}catch{return null}try{return J(JSON.parse(n))}catch{return null}}import{copyFileSync as j,existsSync as d,mkdirSync as c,readFileSync as f,readdirSync as $,renameSync as G,rmSync as y,rmdirSync as z}from"node:fs";import m from"node:path";var B=/^q-[0-9a-f-]+\.ndjson$/;function Y(e){return e.replace(/[^A-Za-z0-9-]/g,n=>`_${n.codePointAt(0).toString(16)}`)}function Z(e){c(e.root,{recursive:!0,mode:l}),c(e.sessionsDir,{recursive:!0,mode:l}),c(e.projectsDir,{recursive:!0,mode:l}),c(e.usageQueueDir,{recursive:!0,mode:l})}function K(e){try{let n=JSON.parse(f(e,"utf8"));if(n.version===2&&typeof n.keyId=="string"&&n.keyId!=="")return[n.keyId];if(n.version===3){let t=n.derivedApp;if(typeof t=="object"&&t!==null&&typeof t.keyId=="string"&&t.keyId!=="")return[t.keyId]}}catch{}return[]}function X(e,n){try{return G(e,n),!0}catch{try{return j(e,n),y(e,{force:!0}),!0}catch{return!1}}}function R(e,n){let t;try{t=$(e)}catch{return 0}let r=0;for(let i of t){if(!B.test(i))continue;let o=m.join(n,i);d(o)||X(m.join(e,i),o)&&(r+=1)}return r}function D(e){let n={credentialsMigrated:!1,usageQueueFilesMoved:0};try{Z(e.vault)}catch{return n}let t=d(e.vault.credentialsFile);if(!t&&d(e.globalCredentialsFile))try{j(e.globalCredentialsFile,e.vault.credentialsFile),y(e.globalCredentialsFile,{force:!0}),n.credentialsMigrated=!0}catch{}else if(t&&d(e.globalCredentialsFile))try{let r=f(e.vault.credentialsFile),i=f(e.globalCredentialsFile);r.equals(i)&&y(e.globalCredentialsFile,{force:!0})}catch{}n.usageQueueFilesMoved+=R(e.globalUsageQueueDir,e.vault.usageQueueDir);for(let r of K(e.vault.credentialsFile)){let i=m.join(e.globalUsageQueueDir,Y(r));n.usageQueueFilesMoved+=R(i,e.vault.usageQueueDir);try{z(i)}catch{}}return n}function re(e){let n;try{n=JSON.parse(te(e,"utf8"))}catch{return null}if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n,r=t.ownerType,i=t.ownerPublicId;return typeof r!="string"||r===""||typeof i!="string"||i===""?null:{ownerType:r,ownerPublicId:i}}function ie(e={}){let n=e.env??process.env,t=e.homedir??ne.homedir(),r=S(n,t),i=A(w(r));if(i===null||i.state!=="inited")return null;let o=i.identityIndex;if(o===void 0)return null;let s;try{s=v(r,o)}catch{return null}let a=re(s.whoamiFile);return a===null||h(a.ownerType,a.ownerPublicId)!==o||(D({globalCredentialsFile:k(n,t),globalUsageQueueDir:g(n,t),vault:s}),!ee(s.credentialsFile))?null:a}function Ce(e={}){return b(()=>ie(e))}export{ce as a,de as b,ge as c,fe as d,ye as e,me as f,pe as g,w as h,Ce as i};
|
|
7
|
-
//# sourceMappingURL=tansr-chunk-
|
|
7
|
+
//# sourceMappingURL=tansr-chunk-2HZJSKHM.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
2
|
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
3
|
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
-
import{b as n}from"./tansr-chunk-
|
|
5
|
-
//# sourceMappingURL=tansr-chunk-
|
|
4
|
+
import{b as n}from"./tansr-chunk-C2NTVBEY.mjs";import{Rb as s}from"./tansr-chunk-JIC3VWLQ.mjs";import i from"node:path";var r={notAbsolute:"cli.cwd.error.not_absolute",notFound:"cli.cwd.error.not_found",notDirectory:"cli.cwd.error.not_directory",notAllowed:"cli.cwd.error.not_allowed"},S=Object.values(r),d={not_absolute:r.notAbsolute,not_found:r.notFound,not_directory:r.notDirectory,not_allowed:r.notAllowed};function a(e,t,o){return i.resolve(t,n(e.trim(),o))}async function f(e){if(e.requested===void 0)return{ok:!0,cwd:e.fallback};let t=a(e.requested,e.fallback,e.homedir),o=await s({requested:t,fallback:e.fallback,policy:{resolve:l=>l}});return o.ok?{ok:!0,cwd:o.cwd}:{ok:!1,reason:o.reason,key:d[o.reason],params:{path:t}}}export{r as a,f as b};
|
|
5
|
+
//# sourceMappingURL=tansr-chunk-2PB54HDR.mjs.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
+
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
+
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
+
import{Ed as w}from"./tansr-chunk-JIC3VWLQ.mjs";import{m as c}from"./tansr-chunk-YK3CE3JM.mjs";import{performance as y}from"node:perf_hooks";var v=1e4;function l(e,t){return new AggregateError(e,c("cli.cleanup.failed",{scope:t}))}async function M(e,t,o=[]){let i=await Promise.allSettled(e);for(let a of i)a.status==="rejected"&&o.push(a.reason);if(o.length>0)throw l(o,t)}async function S(e,t){if(e instanceof w){let o=e.cleanup;await P({resources:()=>[{closeAll:()=>o.settleClose(),settleClose:()=>o.settleClose()}]}).observe({stderr:t})}throw e}async function b(e){let t=await e?.settle?.({timeoutMs:1/0});t!==void 0&&await g(t)}async function _(e){e?.settleResources!==void 0&&await g(await e.settleResources({timeoutMs:1/0}))}async function g(e){if((e.status==="timeout"||e.status==="cancelled"||e.pending.execution+e.pending.modelStreams+e.pending.toolExecutors>0)&&await new Promise(()=>{}),e.status==="failed"||e.failureCount>0)throw l(e.failures.map(t=>t.cause),"resources/beforeMcp")}function P(e){let t,o=!1,i=[],a=new Set,f=()=>(t!==void 0||(t=(async()=>{try{await e.before?.()}catch(n){i.push(n)}try{let n=[...new Set(e.resources().filter(r=>r!=null))],u=await Promise.allSettled(n.map(async r=>{r.settleClose!==void 0?await r.settleClose():await r.closeAll()}));for(let r of u)r.status==="rejected"&&i.push(r.reason)}catch(n){i.push(n)}try{await e.after?.()}catch(n){i.push(n)}if(i.length>0)throw l(i,"CLI/shutdown")})().finally(()=>{o=!0}),t.catch(()=>{})),t);return{settle:f,async observe({timeoutMs:n=v,stderr:u}={}){if(!Number.isFinite(n)||n<0)throw new TypeError(c("cli.cleanup.invalid_timeout"));let r=f();if(!o&&n>0){let d,h=y.now()+n;try{await Promise.race([r.catch(()=>{}),new Promise(x=>{let p=()=>{let m=h-y.now();if(m<=0){x();return}d=setTimeout(p,Math.min(2147483647,m))};p()})])}finally{clearTimeout(d)}}let s={status:o?i.length>0?"failed":"completed":"timeout",pending:!o,failures:i.slice(0,32),failureCount:i.length};if(s.status!=="completed"&&u!==void 0&&!a.has(s.status)){a.add(s.status);try{u.write(JSON.stringify({event:"mcp.cleanup_unconfirmed",status:s.status,pending:s.pending,failureCount:s.failureCount,message:c("cli.assembly.mcp.cleanup_incomplete",{status:s.status,count:s.failureCount})})+`
|
|
5
|
+
`)}catch{}}return s}}}export{l as a,M as b,S as c,b as d,_ as e,P as f};
|
|
6
|
+
//# sourceMappingURL=tansr-chunk-33QZBUL6.mjs.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
+
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
+
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
+
import{c as $e}from"./tansr-chunk-RRAMVVYF.mjs";var Ze={};$e(Ze,{BRAND:()=>ot,DIRTY:()=>D,EMPTY_PATH:()=>ze,INVALID:()=>p,NEVER:()=>Wt,OK:()=>k,ParseStatus:()=>x,Schema:()=>_,ZodAny:()=>P,ZodArray:()=>$,ZodBigInt:()=>U,ZodBoolean:()=>F,ZodBranded:()=>le,ZodCatch:()=>ee,ZodDate:()=>B,ZodDefault:()=>K,ZodDiscriminatedUnion:()=>me,ZodEffects:()=>S,ZodEnum:()=>Q,ZodError:()=>b,ZodFirstPartyTypeKind:()=>m,ZodFunction:()=>_e,ZodIntersection:()=>Y,ZodIssueCode:()=>c,ZodLazy:()=>H,ZodLiteral:()=>G,ZodMap:()=>oe,ZodNaN:()=>de,ZodNativeEnum:()=>X,ZodNever:()=>A,ZodNull:()=>q,ZodNullable:()=>j,ZodNumber:()=>L,ZodObject:()=>w,ZodOptional:()=>C,ZodParsedType:()=>u,ZodPipeline:()=>fe,ZodPromise:()=>z,ZodReadonly:()=>te,ZodRecord:()=>ye,ZodSchema:()=>_,ZodSet:()=>ce,ZodString:()=>V,ZodSymbol:()=>ne,ZodTransformer:()=>S,ZodTuple:()=>N,ZodType:()=>_,ZodUndefined:()=>W,ZodUnion:()=>J,ZodUnknown:()=>Z,ZodVoid:()=>ie,addIssueToContext:()=>d,any:()=>yt,array:()=>xt,bigint:()=>lt,boolean:()=>Ee,coerce:()=>Bt,custom:()=>Ne,date:()=>ft,datetimeRegex:()=>Ae,defaultErrorMap:()=>I,discriminatedUnion:()=>Tt,effect:()=>Mt,enum:()=>Et,function:()=>Nt,getErrorMap:()=>re,getParsedType:()=>R,instanceof:()=>dt,intersection:()=>Ct,isAborted:()=>he,isAsync:()=>se,isDirty:()=>pe,isValid:()=>M,late:()=>ct,lazy:()=>jt,literal:()=>It,makeIssue:()=>ue,map:()=>At,nan:()=>ut,nativeEnum:()=>Zt,never:()=>gt,null:()=>mt,nullable:()=>Pt,number:()=>Ie,object:()=>kt,objectUtil:()=>ve,oboolean:()=>Ft,onumber:()=>Ut,optional:()=>Vt,ostring:()=>Lt,pipeline:()=>Dt,preprocess:()=>zt,promise:()=>$t,quotelessJson:()=>Me,record:()=>St,set:()=>Rt,setErrorMap:()=>Pe,strictObject:()=>bt,string:()=>je,symbol:()=>ht,transformer:()=>Mt,tuple:()=>Ot,undefined:()=>pt,union:()=>wt,unknown:()=>_t,util:()=>g,void:()=>vt});var g;(function(r){r.assertEqual=a=>{};function e(a){}r.assertIs=e;function t(a){throw new Error}r.assertNever=t,r.arrayToEnum=a=>{let n={};for(let i of a)n[i]=i;return n},r.getValidEnumValues=a=>{let n=r.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),i={};for(let o of n)i[o]=a[o];return r.objectValues(i)},r.objectValues=a=>r.objectKeys(a).map(function(n){return a[n]}),r.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{let n=[];for(let i in a)Object.prototype.hasOwnProperty.call(a,i)&&n.push(i);return n},r.find=(a,n)=>{for(let i of a)if(n(i))return i},r.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function s(a,n=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(n)}r.joinValues=s,r.jsonStringifyReplacer=(a,n)=>typeof n=="bigint"?n.toString():n})(g||(g={}));var ve;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ve||(ve={}));var u=g.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),R=r=>{switch(typeof r){case"undefined":return u.undefined;case"string":return u.string;case"number":return Number.isNaN(r)?u.nan:u.number;case"boolean":return u.boolean;case"function":return u.function;case"bigint":return u.bigint;case"symbol":return u.symbol;case"object":return Array.isArray(r)?u.array:r===null?u.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?u.promise:typeof Map<"u"&&r instanceof Map?u.map:typeof Set<"u"&&r instanceof Set?u.set:typeof Date<"u"&&r instanceof Date?u.date:u.object;default:return u.unknown}};var c=g.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Me=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),b=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(n){return n.message},s={_errors:[]},a=n=>{for(let i of n.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else{let o=s,f=0;for(;f<i.path.length;){let l=i.path[f];f===i.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(t(i))):o[l]=o[l]||{_errors:[]},o=o[l],f++}}};return a(this),s}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,g.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},s=[];for(let a of this.issues)if(a.path.length>0){let n=a.path[0];t[n]=t[n]||[],t[n].push(e(a))}else s.push(e(a));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};b.create=r=>new b(r);var Ve=(r,e)=>{let t;switch(r.code){case c.invalid_type:r.received===u.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,g.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:t=`Unrecognized key(s) in object: ${g.joinValues(r.keys,", ")}`;break;case c.invalid_union:t="Invalid input";break;case c.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${g.joinValues(r.options)}`;break;case c.invalid_enum_value:t=`Invalid enum value. Expected ${g.joinValues(r.options)}, received '${r.received}'`;break;case c.invalid_arguments:t="Invalid function arguments";break;case c.invalid_return_type:t="Invalid function return type";break;case c.invalid_date:t="Invalid date";break;case c.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:g.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case c.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case c.custom:t="Invalid input";break;case c.invalid_intersection_types:t="Intersection results could not be merged";break;case c.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c.not_finite:t="Number must be finite";break;default:t=e.defaultError,g.assertNever(r)}return{message:t}},I=Ve;var we=I;function Pe(r){we=r}function re(){return we}var ue=r=>{let{data:e,path:t,errorMaps:s,issueData:a}=r,n=[...t,...a.path||[]],i={...a,path:n};if(a.message!==void 0)return{...a,path:n,message:a.message};let o="",f=s.filter(l=>!!l).slice().reverse();for(let l of f)o=l(i,{data:e,defaultError:o}).message;return{...a,path:n,message:o}},ze=[];function d(r,e){let t=re(),s=ue({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===I?void 0:I].filter(a=>!!a)});r.common.issues.push(s)}var x=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let s=[];for(let a of t){if(a.status==="aborted")return p;a.status==="dirty"&&e.dirty(),s.push(a.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){let s=[];for(let a of t){let n=await a.key,i=await a.value;s.push({key:n,value:i})}return r.mergeObjectSync(e,s)}static mergeObjectSync(e,t){let s={};for(let a of t){let{key:n,value:i}=a;if(n.status==="aborted"||i.status==="aborted")return p;n.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),n.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(s[n.value]=i.value)}return{status:e.value,value:s}}},p=Object.freeze({status:"aborted"}),D=r=>({status:"dirty",value:r}),k=r=>({status:"valid",value:r}),he=r=>r.status==="aborted",pe=r=>r.status==="dirty",M=r=>r.status==="valid",se=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var O=class{constructor(e,t,s,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Te=(r,e)=>{if(M(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new b(r.common.issues);return this._error=t,this._error}}};function y(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:s,description:a}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(i,o)=>{let{message:f}=r;return i.code==="invalid_enum_value"?{message:f??o.defaultError}:typeof o.data>"u"?{message:f??s??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:f??t??o.defaultError}},description:a}}var _=class{get description(){return this._def.description}_getType(e){return R(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new x,ctx:{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(se(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},a=this._parseSync({data:e,path:s.path,parent:s});return Te(s,a)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:t});return M(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>M(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},a=this._parse({data:e,path:s.path,parent:s}),n=await(se(a)?a:Promise.resolve(a));return Te(s,n)}refine(e,t){let s=a=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(a):t;return this._refinement((a,n)=>{let i=e(a),o=()=>n.addIssue({code:c.custom,...s(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(f=>f?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((s,a)=>e(s)?!0:(a.addIssue(typeof t=="function"?t(s,a):t),!1))}_refinement(e){return new S({schema:this,typeName:m.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return C.create(this,this._def)}nullable(){return j.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $.create(this)}promise(){return z.create(this,this._def)}or(e){return J.create([this,e],this._def)}and(e){return Y.create(this,e,this._def)}transform(e){return new S({...y(this._def),schema:this,typeName:m.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new K({...y(this._def),innerType:this,defaultValue:t,typeName:m.ZodDefault})}brand(){return new le({typeName:m.ZodBranded,type:this,...y(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ee({...y(this._def),innerType:this,catchValue:t,typeName:m.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return fe.create(this,e)}readonly(){return te.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},De=/^c[^\s-]{8,}$/i,Le=/^[0-9a-z]+$/,Ue=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fe=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Be=/^[a-z0-9_-]{21}$/i,We=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,qe=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Je=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ye="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",xe,He=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ge=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Qe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Xe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ke=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,et=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Oe="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",tt=new RegExp(`^${Oe}$`);function Se(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function rt(r){return new RegExp(`^${Se(r)}$`)}function Ae(r){let e=`${Oe}T${Se(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function st(r,e){return!!((e==="v4"||!e)&&He.test(r)||(e==="v6"||!e)&&Qe.test(r))}function at(r,e){if(!We.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),a=JSON.parse(atob(s));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return!1}}function nt(r,e){return!!((e==="v4"||!e)&&Ge.test(r)||(e==="v6"||!e)&&Xe.test(r))}var V=class r extends _{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==u.string){let n=this._getOrReturnCtx(e);return d(n,{code:c.invalid_type,expected:u.string,received:n.parsedType}),p}let s=new x,a;for(let n of this._def.checks)if(n.kind==="min")e.data.length<n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),s.dirty());else if(n.kind==="max")e.data.length>n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),s.dirty());else if(n.kind==="length"){let i=e.data.length>n.value,o=e.data.length<n.value;(i||o)&&(a=this._getOrReturnCtx(e,a),i?d(a,{code:c.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&d(a,{code:c.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),s.dirty())}else if(n.kind==="email")Je.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"email",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="emoji")xe||(xe=new RegExp(Ye,"u")),xe.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"emoji",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="uuid")Fe.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"uuid",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="nanoid")Be.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"nanoid",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="cuid")De.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"cuid",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="cuid2")Le.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"cuid2",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="ulid")Ue.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"ulid",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="url")try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),d(a,{validation:"url",code:c.invalid_string,message:n.message}),s.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"regex",code:c.invalid_string,message:n.message}),s.dirty())):n.kind==="trim"?e.data=e.data.trim():n.kind==="includes"?e.data.includes(n.value,n.position)||(a=this._getOrReturnCtx(e,a),d(a,{code:c.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),s.dirty()):n.kind==="toLowerCase"?e.data=e.data.toLowerCase():n.kind==="toUpperCase"?e.data=e.data.toUpperCase():n.kind==="startsWith"?e.data.startsWith(n.value)||(a=this._getOrReturnCtx(e,a),d(a,{code:c.invalid_string,validation:{startsWith:n.value},message:n.message}),s.dirty()):n.kind==="endsWith"?e.data.endsWith(n.value)||(a=this._getOrReturnCtx(e,a),d(a,{code:c.invalid_string,validation:{endsWith:n.value},message:n.message}),s.dirty()):n.kind==="datetime"?Ae(n).test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{code:c.invalid_string,validation:"datetime",message:n.message}),s.dirty()):n.kind==="date"?tt.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{code:c.invalid_string,validation:"date",message:n.message}),s.dirty()):n.kind==="time"?rt(n).test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{code:c.invalid_string,validation:"time",message:n.message}),s.dirty()):n.kind==="duration"?qe.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"duration",code:c.invalid_string,message:n.message}),s.dirty()):n.kind==="ip"?st(e.data,n.version)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"ip",code:c.invalid_string,message:n.message}),s.dirty()):n.kind==="jwt"?at(e.data,n.alg)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"jwt",code:c.invalid_string,message:n.message}),s.dirty()):n.kind==="cidr"?nt(e.data,n.version)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"cidr",code:c.invalid_string,message:n.message}),s.dirty()):n.kind==="base64"?Ke.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"base64",code:c.invalid_string,message:n.message}),s.dirty()):n.kind==="base64url"?et.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"base64url",code:c.invalid_string,message:n.message}),s.dirty()):g.assertNever(n);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(a=>e.test(a),{validation:t,code:c.invalid_string,...h.errToObj(s)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};V.create=r=>new V({checks:[],typeName:m.ZodString,coerce:r?.coerce??!1,...y(r)});function it(r,e){let t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,a=t>s?t:s,n=Number.parseInt(r.toFixed(a).replace(".","")),i=Number.parseInt(e.toFixed(a).replace(".",""));return n%i/10**a}var L=class r extends _{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==u.number){let n=this._getOrReturnCtx(e);return d(n,{code:c.invalid_type,expected:u.number,received:n.parsedType}),p}let s,a=new x;for(let n of this._def.checks)n.kind==="int"?g.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:c.invalid_type,expected:"integer",received:"float",message:n.message}),a.dirty()):n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),a.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),a.dirty()):n.kind==="multipleOf"?it(e.data,n.value)!==0&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.not_multiple_of,multipleOf:n.value,message:n.message}),a.dirty()):n.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:c.not_finite,message:n.message}),a.dirty()):g.assertNever(n);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,s,a){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(a)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&g.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}};L.create=r=>new L({checks:[],typeName:m.ZodNumber,coerce:r?.coerce||!1,...y(r)});var U=class r extends _{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==u.bigint)return this._getInvalidInput(e);let s,a=new x;for(let n of this._def.checks)n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),a.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),a.dirty()):n.kind==="multipleOf"?e.data%n.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.not_multiple_of,multipleOf:n.value,message:n.message}),a.dirty()):g.assertNever(n);return{status:a.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return d(t,{code:c.invalid_type,expected:u.bigint,received:t.parsedType}),p}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,s,a){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(a)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};U.create=r=>new U({checks:[],typeName:m.ZodBigInt,coerce:r?.coerce??!1,...y(r)});var F=class extends _{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==u.boolean){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.boolean,received:s.parsedType}),p}return k(e.data)}};F.create=r=>new F({typeName:m.ZodBoolean,coerce:r?.coerce||!1,...y(r)});var B=class r extends _{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==u.date){let n=this._getOrReturnCtx(e);return d(n,{code:c.invalid_type,expected:u.date,received:n.parsedType}),p}if(Number.isNaN(e.data.getTime())){let n=this._getOrReturnCtx(e);return d(n,{code:c.invalid_date}),p}let s=new x,a;for(let n of this._def.checks)n.kind==="min"?e.data.getTime()<n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),s.dirty()):n.kind==="max"?e.data.getTime()>n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),s.dirty()):g.assertNever(n);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};B.create=r=>new B({checks:[],coerce:r?.coerce||!1,typeName:m.ZodDate,...y(r)});var ne=class extends _{_parse(e){if(this._getType(e)!==u.symbol){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.symbol,received:s.parsedType}),p}return k(e.data)}};ne.create=r=>new ne({typeName:m.ZodSymbol,...y(r)});var W=class extends _{_parse(e){if(this._getType(e)!==u.undefined){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.undefined,received:s.parsedType}),p}return k(e.data)}};W.create=r=>new W({typeName:m.ZodUndefined,...y(r)});var q=class extends _{_parse(e){if(this._getType(e)!==u.null){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.null,received:s.parsedType}),p}return k(e.data)}};q.create=r=>new q({typeName:m.ZodNull,...y(r)});var P=class extends _{constructor(){super(...arguments),this._any=!0}_parse(e){return k(e.data)}};P.create=r=>new P({typeName:m.ZodAny,...y(r)});var Z=class extends _{constructor(){super(...arguments),this._unknown=!0}_parse(e){return k(e.data)}};Z.create=r=>new Z({typeName:m.ZodUnknown,...y(r)});var A=class extends _{_parse(e){let t=this._getOrReturnCtx(e);return d(t,{code:c.invalid_type,expected:u.never,received:t.parsedType}),p}};A.create=r=>new A({typeName:m.ZodNever,...y(r)});var ie=class extends _{_parse(e){if(this._getType(e)!==u.undefined){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.void,received:s.parsedType}),p}return k(e.data)}};ie.create=r=>new ie({typeName:m.ZodVoid,...y(r)});var $=class r extends _{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==u.array)return d(t,{code:c.invalid_type,expected:u.array,received:t.parsedType}),p;if(a.exactLength!==null){let i=t.data.length>a.exactLength.value,o=t.data.length<a.exactLength.value;(i||o)&&(d(t,{code:i?c.too_big:c.too_small,minimum:o?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),s.dirty())}if(a.minLength!==null&&t.data.length<a.minLength.value&&(d(t,{code:c.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),s.dirty()),a.maxLength!==null&&t.data.length>a.maxLength.value&&(d(t,{code:c.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>a.type._parseAsync(new O(t,i,t.path,o)))).then(i=>x.mergeArray(s,i));let n=[...t.data].map((i,o)=>a.type._parseSync(new O(t,i,t.path,o)));return x.mergeArray(s,n)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};$.create=(r,e)=>new $({type:r,minLength:null,maxLength:null,exactLength:null,typeName:m.ZodArray,...y(e)});function ae(r){if(r instanceof w){let e={};for(let t in r.shape){let s=r.shape[t];e[t]=C.create(ae(s))}return new w({...r._def,shape:()=>e})}else return r instanceof $?new $({...r._def,type:ae(r.element)}):r instanceof C?C.create(ae(r.unwrap())):r instanceof j?j.create(ae(r.unwrap())):r instanceof N?N.create(r.items.map(e=>ae(e))):r}var w=class r extends _{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=g.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==u.object){let l=this._getOrReturnCtx(e);return d(l,{code:c.invalid_type,expected:u.object,received:l.parsedType}),p}let{status:s,ctx:a}=this._processInputParams(e),{shape:n,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof A&&this._def.unknownKeys==="strip"))for(let l in a.data)i.includes(l)||o.push(l);let f=[];for(let l of i){let v=n[l],T=a.data[l];f.push({key:{status:"valid",value:l},value:v._parse(new O(a,T,a.path,l)),alwaysSet:l in a.data})}if(this._def.catchall instanceof A){let l=this._def.unknownKeys;if(l==="passthrough")for(let v of o)f.push({key:{status:"valid",value:v},value:{status:"valid",value:a.data[v]}});else if(l==="strict")o.length>0&&(d(a,{code:c.unrecognized_keys,keys:o}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let v of o){let T=a.data[v];f.push({key:{status:"valid",value:v},value:l._parse(new O(a,T,a.path,v)),alwaysSet:v in a.data})}}return a.common.async?Promise.resolve().then(async()=>{let l=[];for(let v of f){let T=await v.key,be=await v.value;l.push({key:T,value:be,alwaysSet:v.alwaysSet})}return l}).then(l=>x.mergeObjectSync(s,l)):x.mergeObjectSync(s,f)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{let a=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:m.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let s of g.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let s of g.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}deepPartial(){return ae(this)}partial(e){let t={};for(let s of g.objectKeys(this.shape)){let a=this.shape[s];e&&!e[s]?t[s]=a:t[s]=a.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let s of g.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let n=this.shape[s];for(;n instanceof C;)n=n._def.innerType;t[s]=n}return new r({...this._def,shape:()=>t})}keyof(){return Re(g.objectKeys(this.shape))}};w.create=(r,e)=>new w({shape:()=>r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,...y(e)});w.strictCreate=(r,e)=>new w({shape:()=>r,unknownKeys:"strict",catchall:A.create(),typeName:m.ZodObject,...y(e)});w.lazycreate=(r,e)=>new w({shape:r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,...y(e)});var J=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function a(n){for(let o of n)if(o.result.status==="valid")return o.result;for(let o of n)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=n.map(o=>new b(o.ctx.common.issues));return d(t,{code:c.invalid_union,unionErrors:i}),p}if(t.common.async)return Promise.all(s.map(async n=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await n._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(a);{let n,i=[];for(let f of s){let l={...t,common:{...t.common,issues:[]},parent:null},v=f._parseSync({data:t.data,path:t.path,parent:l});if(v.status==="valid")return v;v.status==="dirty"&&!n&&(n={result:v,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;let o=i.map(f=>new b(f));return d(t,{code:c.invalid_union,unionErrors:o}),p}}get options(){return this._def.options}};J.create=(r,e)=>new J({options:r,typeName:m.ZodUnion,...y(e)});var E=r=>r instanceof H?E(r.schema):r instanceof S?E(r.innerType()):r instanceof G?[r.value]:r instanceof Q?r.options:r instanceof X?g.objectValues(r.enum):r instanceof K?E(r._def.innerType):r instanceof W?[void 0]:r instanceof q?[null]:r instanceof C?[void 0,...E(r.unwrap())]:r instanceof j?[null,...E(r.unwrap())]:r instanceof le||r instanceof te?E(r.unwrap()):r instanceof ee?E(r._def.innerType):[],me=class r extends _{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.object)return d(t,{code:c.invalid_type,expected:u.object,received:t.parsedType}),p;let s=this.discriminator,a=t.data[s],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(d(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),p)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){let a=new Map;for(let n of t){let i=E(n.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(a.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);a.set(o,n)}}return new r({typeName:m.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...y(s)})}};function ke(r,e){let t=R(r),s=R(e);if(r===e)return{valid:!0,data:r};if(t===u.object&&s===u.object){let a=g.objectKeys(e),n=g.objectKeys(r).filter(o=>a.indexOf(o)!==-1),i={...r,...e};for(let o of n){let f=ke(r[o],e[o]);if(!f.valid)return{valid:!1};i[o]=f.data}return{valid:!0,data:i}}else if(t===u.array&&s===u.array){if(r.length!==e.length)return{valid:!1};let a=[];for(let n=0;n<r.length;n++){let i=r[n],o=e[n],f=ke(i,o);if(!f.valid)return{valid:!1};a.push(f.data)}return{valid:!0,data:a}}else return t===u.date&&s===u.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Y=class extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),a=(n,i)=>{if(he(n)||he(i))return p;let o=ke(n.value,i.value);return o.valid?((pe(n)||pe(i))&&t.dirty(),{status:t.value,value:o.data}):(d(s,{code:c.invalid_intersection_types}),p)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([n,i])=>a(n,i)):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Y.create=(r,e,t)=>new Y({left:r,right:e,typeName:m.ZodIntersection,...y(t)});var N=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.array)return d(s,{code:c.invalid_type,expected:u.array,received:s.parsedType}),p;if(s.data.length<this._def.items.length)return d(s,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),p;!this._def.rest&&s.data.length>this._def.items.length&&(d(s,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let n=[...s.data].map((i,o)=>{let f=this._def.items[o]||this._def.rest;return f?f._parse(new O(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(n).then(i=>x.mergeArray(t,i)):x.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};N.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new N({items:r,typeName:m.ZodTuple,rest:null,...y(e)})};var ye=class r extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.object)return d(s,{code:c.invalid_type,expected:u.object,received:s.parsedType}),p;let a=[],n=this._def.keyType,i=this._def.valueType;for(let o in s.data)a.push({key:n._parse(new O(s,o,s.path,o)),value:i._parse(new O(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?x.mergeObjectAsync(t,a):x.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof _?new r({keyType:e,valueType:t,typeName:m.ZodRecord,...y(s)}):new r({keyType:V.create(),valueType:e,typeName:m.ZodRecord,...y(t)})}},oe=class extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.map)return d(s,{code:c.invalid_type,expected:u.map,received:s.parsedType}),p;let a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map(([o,f],l)=>({key:a._parse(new O(s,o,s.path,[l,"key"])),value:n._parse(new O(s,f,s.path,[l,"value"]))}));if(s.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let f of i){let l=await f.key,v=await f.value;if(l.status==="aborted"||v.status==="aborted")return p;(l.status==="dirty"||v.status==="dirty")&&t.dirty(),o.set(l.value,v.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let f of i){let l=f.key,v=f.value;if(l.status==="aborted"||v.status==="aborted")return p;(l.status==="dirty"||v.status==="dirty")&&t.dirty(),o.set(l.value,v.value)}return{status:t.value,value:o}}}};oe.create=(r,e,t)=>new oe({valueType:e,keyType:r,typeName:m.ZodMap,...y(t)});var ce=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.set)return d(s,{code:c.invalid_type,expected:u.set,received:s.parsedType}),p;let a=this._def;a.minSize!==null&&s.data.size<a.minSize.value&&(d(s,{code:c.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),a.maxSize!==null&&s.data.size>a.maxSize.value&&(d(s,{code:c.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());let n=this._def.valueType;function i(f){let l=new Set;for(let v of f){if(v.status==="aborted")return p;v.status==="dirty"&&t.dirty(),l.add(v.value)}return{status:t.value,value:l}}let o=[...s.data.values()].map((f,l)=>n._parse(new O(s,f,s.path,l)));return s.common.async?Promise.all(o).then(f=>i(f)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ce.create=(r,e)=>new ce({valueType:r,minSize:null,maxSize:null,typeName:m.ZodSet,...y(e)});var _e=class r extends _{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.function)return d(t,{code:c.invalid_type,expected:u.function,received:t.parsedType}),p;function s(o,f){return ue({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,re(),I].filter(l=>!!l),issueData:{code:c.invalid_arguments,argumentsError:f}})}function a(o,f){return ue({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,re(),I].filter(l=>!!l),issueData:{code:c.invalid_return_type,returnTypeError:f}})}let n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof z){let o=this;return k(async function(...f){let l=new b([]),v=await o._def.args.parseAsync(f,n).catch(ge=>{throw l.addIssue(s(f,ge)),l}),T=await Reflect.apply(i,this,v);return await o._def.returns._def.type.parseAsync(T,n).catch(ge=>{throw l.addIssue(a(T,ge)),l})})}else{let o=this;return k(function(...f){let l=o._def.args.safeParse(f,n);if(!l.success)throw new b([s(f,l.error)]);let v=Reflect.apply(i,this,l.data),T=o._def.returns.safeParse(v,n);if(!T.success)throw new b([a(v,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:N.create(e).rest(Z.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new r({args:e||N.create([]).rest(Z.create()),returns:t||Z.create(),typeName:m.ZodFunction,...y(s)})}},H=class extends _{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};H.create=(r,e)=>new H({getter:r,typeName:m.ZodLazy,...y(e)});var G=class extends _{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return d(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),p}return{status:"valid",value:e.data}}get value(){return this._def.value}};G.create=(r,e)=>new G({value:r,typeName:m.ZodLiteral,...y(e)});function Re(r,e){return new Q({values:r,typeName:m.ZodEnum,...y(e)})}var Q=class r extends _{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),s=this._def.values;return d(t,{expected:g.joinValues(s),received:t.parsedType,code:c.invalid_type}),p}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return d(t,{received:t.data,code:c.invalid_enum_value,options:s}),p}return k(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}};Q.create=Re;var X=class extends _{_parse(e){let t=g.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==u.string&&s.parsedType!==u.number){let a=g.objectValues(t);return d(s,{expected:g.joinValues(a),received:s.parsedType,code:c.invalid_type}),p}if(this._cache||(this._cache=new Set(g.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let a=g.objectValues(t);return d(s,{received:s.data,code:c.invalid_enum_value,options:a}),p}return k(e.data)}get enum(){return this._def.values}};X.create=(r,e)=>new X({values:r,typeName:m.ZodNativeEnum,...y(e)});var z=class extends _{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.promise&&t.common.async===!1)return d(t,{code:c.invalid_type,expected:u.promise,received:t.parsedType}),p;let s=t.parsedType===u.promise?t.data:Promise.resolve(t.data);return k(s.then(a=>this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})))}};z.create=(r,e)=>new z({type:r,typeName:m.ZodPromise,...y(e)});var S=class extends _{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===m.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),a=this._def.effect||null,n={addIssue:i=>{d(s,i),i.fatal?t.abort():t.dirty()},get path(){return s.path}};if(n.addIssue=n.addIssue.bind(n),a.type==="preprocess"){let i=a.transform(s.data,n);if(s.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return p;let f=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return f.status==="aborted"?p:f.status==="dirty"?D(f.value):t.value==="dirty"?D(f.value):f});{if(t.value==="aborted")return p;let o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?p:o.status==="dirty"?D(o.value):t.value==="dirty"?D(o.value):o}}if(a.type==="refinement"){let i=o=>{let f=a.refinement(o,n);if(s.common.async)return Promise.resolve(f);if(f instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===!1){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?p:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?p:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(a.type==="transform")if(s.common.async===!1){let i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!M(i))return p;let o=a.transform(i.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>M(i)?Promise.resolve(a.transform(i.value,n)).then(o=>({status:t.value,value:o})):p);g.assertNever(a)}};S.create=(r,e,t)=>new S({schema:r,typeName:m.ZodEffects,effect:e,...y(t)});S.createWithPreprocess=(r,e,t)=>new S({schema:e,effect:{type:"preprocess",transform:r},typeName:m.ZodEffects,...y(t)});var C=class extends _{_parse(e){return this._getType(e)===u.undefined?k(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};C.create=(r,e)=>new C({innerType:r,typeName:m.ZodOptional,...y(e)});var j=class extends _{_parse(e){return this._getType(e)===u.null?k(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};j.create=(r,e)=>new j({innerType:r,typeName:m.ZodNullable,...y(e)});var K=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===u.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};K.create=(r,e)=>new K({innerType:r,typeName:m.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...y(e)});var ee=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return se(a)?a.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new b(s.common.issues)},input:s.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new b(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ee.create=(r,e)=>new ee({innerType:r,typeName:m.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...y(e)});var de=class extends _{_parse(e){if(this._getType(e)!==u.nan){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.nan,received:s.parsedType}),p}return{status:"valid",value:e.data}}};de.create=r=>new de({typeName:m.ZodNaN,...y(r)});var ot=Symbol("zod_brand"),le=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},fe=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let n=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?p:n.status==="dirty"?(t.dirty(),D(n.value)):this._def.out._parseAsync({data:n.value,path:s.path,parent:s})})();{let a=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?p:a.status==="dirty"?(t.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:s.path,parent:s})}}static create(e,t){return new r({in:e,out:t,typeName:m.ZodPipeline})}},te=class extends _{_parse(e){let t=this._def.innerType._parse(e),s=a=>(M(a)&&(a.value=Object.freeze(a.value)),a);return se(t)?t.then(a=>s(a)):s(t)}unwrap(){return this._def.innerType}};te.create=(r,e)=>new te({innerType:r,typeName:m.ZodReadonly,...y(e)});function Ce(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Ne(r,e={},t){return r?P.create().superRefine((s,a)=>{let n=r(s);if(n instanceof Promise)return n.then(i=>{if(!i){let o=Ce(e,s),f=o.fatal??t??!0;a.addIssue({code:"custom",...o,fatal:f})}});if(!n){let i=Ce(e,s),o=i.fatal??t??!0;a.addIssue({code:"custom",...i,fatal:o})}}):P.create()}var ct={object:w.lazycreate},m;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(m||(m={}));var dt=(r,e={message:`Input not instance of ${r.name}`})=>Ne(t=>t instanceof r,e),je=V.create,Ie=L.create,ut=de.create,lt=U.create,Ee=F.create,ft=B.create,ht=ne.create,pt=W.create,mt=q.create,yt=P.create,_t=Z.create,gt=A.create,vt=ie.create,xt=$.create,kt=w.create,bt=w.strictCreate,wt=J.create,Tt=me.create,Ct=Y.create,Ot=N.create,St=ye.create,At=oe.create,Rt=ce.create,Nt=_e.create,jt=H.create,It=G.create,Et=Q.create,Zt=X.create,$t=z.create,Mt=S.create,Vt=C.create,Pt=j.create,zt=S.createWithPreprocess,Dt=fe.create,Lt=()=>je().optional(),Ut=()=>Ie().optional(),Ft=()=>Ee().optional(),Bt={string:(r=>V.create({...r,coerce:!0})),number:(r=>L.create({...r,coerce:!0})),boolean:(r=>F.create({...r,coerce:!0})),bigint:(r=>U.create({...r,coerce:!0})),date:(r=>B.create({...r,coerce:!0}))};var Wt=p;export{b as a,m as b,Ze as c};
|
|
5
|
+
//# sourceMappingURL=tansr-chunk-3YSQG6KY.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
+
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
+
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
+
import{e as qe,y as Re}from"./tansr-chunk-ENRIN7EG.mjs";import{A as de,C as Q,F as O,a as J,b as T,d as le,f as ue,g as $,l as W,x as Y}from"./tansr-chunk-LA3LGOYQ.mjs";import{c}from"./tansr-chunk-3YSQG6KY.mjs";import{createHash as rt,randomUUID as xe}from"node:crypto";import{mkdir as bn,open as Le,readFile as jn,rm as vn,stat as Te}from"node:fs/promises";import k from"node:path";import{createHash as Ge}from"node:crypto";import{access as Bn,mkdir as Un,readFile as qn}from"node:fs/promises";import Xe from"node:path";var ze=["png","jpg","jpeg","gif","webp"],De={png:"image/png",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};function On(e){let t=e.toLowerCase().replace(/^\./,"");return ze.includes(t)}function Se(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"jpeg":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97?"gif":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"webp":null}var Fe=(e,t)=>(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0,Ee=(e,t)=>e[t]<<8|e[t+1],ce=(e,t)=>e[t]|e[t+1]<<8,$e=(e,t)=>e[t]|e[t+1]<<8|e[t+2]<<16;function An(e){if(e.length<24||e[12]!==73||e[13]!==72||e[14]!==68||e[15]!==82)return null;let t=Fe(e,16),n=Fe(e,20);return t>0&&n>0?{width:t,height:n}:null}var Nn=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204;function _n(e){let t=2;for(;t+3<e.length;){if(e[t]!==255)return null;let n=e[t+1];for(;n===255&&t+2<e.length;)t+=1,n=e[t+1];if(n===1||n>=208&&n<=215){t+=2;continue}if(n===217||n===218)return null;let r=Ee(e,t+2);if(r<2)return null;if(Nn(n)){if(t+9>e.length)return null;let i=Ee(e,t+5),a=Ee(e,t+7);return a>0&&i>0?{width:a,height:i}:null}t+=2+r}return null}function Cn(e){if(e.length<10)return null;let t=ce(e,6),n=ce(e,8);return t>0&&n>0?{width:t,height:n}:null}function Hn(e){if(e.length<16)return null;let t=String.fromCharCode(e[12],e[13],e[14],e[15]);if(t==="VP8 "){if(e.length<30||e[23]!==157||e[24]!==1||e[25]!==42)return null;let n=ce(e,26)&16383,r=ce(e,28)&16383;return n>0&&r>0?{width:n,height:r}:null}if(t==="VP8L"){if(e.length<25||e[20]!==47)return null;let n=1+((e[22]&63)<<8|e[21]),r=1+((e[24]&15)<<10|e[23]<<2|(e[22]&192)>>6);return{width:n,height:r}}if(t==="VP8X"){if(e.length<30)return null;let n=1+$e(e,24),r=1+$e(e,27);return{width:n,height:r}}return null}function Z(e){let t=Se(e);if(t===null)return null;switch(t){case"png":return An(e);case"jpeg":return _n(e);case"gif":return Cn(e);case"webp":return Hn(e)}}function Ln(e){let t=Se(e);if(t===null)return null;let n=Z(e);return n===null?null:{format:t,mime:De[t],...n}}var Ke=512*1024;function Tn(e,t=Ke){let n=Math.ceil(t*4/3/4)*4,r=e.length>n?e.slice(0,n):e,i;try{i=Buffer.from(r,"base64")}catch{return null}return i.length===0?null:Z(i)}var Fn="attachments",ht=new Set(["user_prompt","assistant_message","tool_result"]),$n=/^sha256:([0-9a-f]{64})$/;function Ve(e){return Xe.join(e,Fn)}function We(e,t){return Xe.join(Ve(e),t)}var Pe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zn=e=>e.t==="image"&&typeof e.data=="string"&&typeof e.mime=="string"&&e.$ref===void 0,Ye=e=>e.t==="image"&&typeof e.$ref=="string"&&typeof e.mime=="string"&&e.data===void 0;async function Dn(e,t){try{let n=Buffer.from(e.data,"base64"),r=Ge("sha256").update(n).digest("hex"),i=We(t,r),a=!0;try{await Bn(i)}catch{a=!1}a||(await Un(Ve(t),{recursive:!0}),await O(i,n));let o={t:"image",mime:e.mime,$ref:`sha256:${r}`,bytes:n.length},d=Z(n);return d!==null&&(o.w=d.width,o.h=d.height),o}catch{return e}}async function Qe(e,t,n,r){let i=e.$ref,a=(u,l)=>(n.push(`image 附件${u},块已降级为占位文本(${i})`),{t:"text",text:`[image unavailable: attachment ${i} ${l}]`}),o=$n.exec(i);if(o===null)return a("引用非法","has an invalid ref");let d=o[1],s;try{s=r?Buffer.from(await r(d)):await qn(We(t,d))}catch{return a("缺失","is missing")}return Ge("sha256").update(s).digest("hex")!==d?a("摘要不符","is corrupt (sha256 mismatch)"):{t:"image",mime:e.mime,data:s.toString("base64")}}async function Je(e,t,n){if(!Pe(e)||!Array.isArray(e.blocks))return e;let r=!1,i=[];for(let a of e.blocks){if(!Pe(a)){i.push(a);continue}if(t(a)){let o=await n(a);o!==a&&(r=!0),i.push(o);continue}if(a.t==="tool_result"&&Array.isArray(a.content)){let o=!1,d=[];for(let s of a.content){if(!Pe(s)||!t(s)){d.push(s);continue}let u=await n(s);u!==s&&(o=!0),d.push(u)}if(!o){i.push(a);continue}r=!0,i.push({...a,content:d});continue}i.push(a)}return r?{...e,blocks:i}:e}async function Ze(e,t){return Je(e,zn,n=>Dn(n,t))}async function en(e,t,n){return Je(e,Ye,r=>Qe(r,t,n))}async function nn(e,t,n){return Je(e,Ye,r=>Qe(r,"",n,t))}var tn=Object.freeze({recordCount:0,lastSeq:-1,lastEventId:null,lastHash:null,byteLength:0});import{createHash as Kn}from"node:crypto";function Me(e){if(Array.isArray(e))return e.map(Me);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=Me(t[r]);return n}return e}function y(e){let t=JSON.parse(JSON.stringify(e));return JSON.stringify(Me(t))}function Oe(e){let{integrity:t,...n}=e,r={...n,integrity:{previousHash:t.previousHash}};return Kn("sha256").update(y(r),"utf8").digest("hex")}import{readFile as Gn,rm as bt,stat as Xn}from"node:fs/promises";import Vn from"node:path";var Wn=c.object({n:c.number().int().positive(),file:c.string(),firstSeq:c.number().int().nonnegative(),lastSeq:c.number().int().nonnegative(),records:c.number().int().nonnegative(),bytes:c.number().int().nonnegative(),lastHash:c.string(),sealedAt:c.string(),status:c.enum(["pending","sealed"])}),Yn=c.object({schemaVersion:c.union([c.literal(1),c.literal(2),c.literal(3),c.literal(4)]),layout:c.enum(["indexed-journal-v1","indexed-journal-v2"]).optional(),generation:c.string().uuid().optional(),segments:c.array(Wn),live:c.object({firstSeq:c.number().int().nonnegative()})}).superRefine((e,t)=>{e.schemaVersion===3&&(e.layout!=="indexed-journal-v1"||e.generation===void 0)&&t.addIssue({code:c.ZodIssueCode.custom,message:"v3 requires indexed layout and generation"}),e.schemaVersion===4&&(e.layout!=="indexed-journal-v2"||e.generation===void 0)&&t.addIssue({code:c.ZodIssueCode.custom,message:"v4 requires paged indexed layout and generation"}),e.schemaVersion<3&&(e.layout!==void 0||e.generation!==void 0)&&t.addIssue({code:c.ZodIssueCode.custom,message:"legacy manifest cannot carry indexed authority"})});function z(e){return e!=null&&e.generation!==void 0&&(e.schemaVersion===3&&e.layout==="indexed-journal-v1"||e.schemaVersion===4&&e.layout==="indexed-journal-v2")}var Qn=16*1024*1024,Zn=5e3;function Et(e){if(e===void 0)return null;let t=e.maxBytes??Qn,n=e.maxRecords??Zn;if(e.enabled!==void 0&&typeof e.enabled!="boolean"||!Number.isSafeInteger(t)||t<1||!Number.isSafeInteger(n)||n<1)throw new TypeError("Journal segmentation thresholds must be positive safe integers");return{enabled:e.enabled??!0,maxBytes:t,maxRecords:n}}function St(e,t){return e.status==="sealed"||t}async function F(e){let t;try{t=await Gn(de(e),"utf8")}catch(i){if(T(i)&&i.code==="ENOENT"){for(let a of["resume-head.json","resume-pending.json"]){try{await Xn(Vn.join(e,"journal-index",a))}catch(o){if(T(o)&&o.code==="ENOENT")continue;throw o}throw new J("JOURNAL_RECONCILIATION_REQUIRED","Indexed journal mandatory manifest is missing; legacy fallback is disabled")}return null}throw i}let n;try{n=JSON.parse(t)}catch{throw new J("MANIFEST_INVALID",`manifest.json 不是合法 JSON:${de(e)}`)}let r=Yn.safeParse(n);if(typeof n=="object"&&n!==null&&"schemaVersion"in n&&typeof n.schemaVersion=="number"&&n.schemaVersion>4)throw new J("STORAGE_VERSION_UNSUPPORTED","Unsupported journal manifest version");if(!r.success)throw new J("MANIFEST_INVALID",`manifest.json 不符合 JournalManifest schema:${r.error.message}`);return r.data}async function rn(e,t){await O(de(e),`${JSON.stringify(t,null,2)}
|
|
5
|
+
`)}function an(e){let t=new Set,n=[0];for(let r=0;r<e.length;r++){let i=e[r];if(i.role==="assistant")for(let a of i.blocks)a.t==="tool_call"&&t.add(a.id);else for(let a of i.blocks)if(a.t==="tool_result"){if(!t.has(a.callId))return null;t.delete(a.callId)}t.size===0&&n.push(r+1)}return n}function on(e,t,n,r){if(t===null)return null;let i=Math.min(Math.max(0,Math.floor(n)),e),a=Math.min(e,i+Math.max(0,Math.floor(r))),o=0,d;for(let s of t)s<=i&&(o=s),d===void 0&&s>=a&&(d=s);return{start:o,end:d??e}}import{createHash as dn}from"node:crypto";var ge="journal-index-page-v2",me=32*1024,ne=16,cn=1024,fn=4096,Ne=256,fe=/^[0-9a-f]{64}$/,gn="utf16le-base64";function p(e){throw new J("JOURNAL_RECONCILIATION_REQUIRED",`Indexed journal page ${e}; original responsibility retained`)}function Ae(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ee(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function he(e){return typeof e=="string"&&e.length<=fn}function K(e){return dn("sha256").update(y(e)).digest("hex")}function et(e){return Buffer.from(e,"utf16le").toString("base64")}function pe(e){(typeof e!="string"||e.length>Math.ceil(fn*2/3)*4)&&p("separator is invalid");let t=Buffer.from(e,"base64");(t.length%2!==0||t.toString("base64")!==e)&&p("separator encoding is invalid");let n=t.toString("utf16le");return he(n)||p("separator key is invalid"),n}function sn(e){for(let t=1;t<e.length;t++)e[t-1]>=e[t]&&p("keys are not strictly ordered")}function _e(e){return Buffer.byteLength(y(e))}function mn(e){let t;try{t=y(e)}catch{p("is not JSON")}Buffer.byteLength(t)>me&&p("source capacity exceeded");let n=JSON.parse(t);if((!Ae(n)||n.format!==ge)&&p("format is invalid"),n.kind==="leaf"){(!ee(n,["format","kind","entries"])||!Array.isArray(n.entries)||n.entries.length>ne)&&p("leaf is invalid");let i=[];for(let a of n.entries)(!Ae(a)||!ee(a,["key","value"])||!he(a.key)||!Ae(a.value))&&p("entry is invalid"),i.push(a.key),ee(a.value,["hash"])?(typeof a.value.hash!="string"||!fe.test(a.value.hash))&&p("value reference is invalid"):ee(a.value,["inline"])?_e(a.value.inline)>cn&&p("inline value capacity exceeded"):p("value is invalid");return sn(i),n}(n.kind!=="branch"||!ee(n,["format","kind","separatorEncoding","keys","children","maxKeyHash"])||n.separatorEncoding!==gn||!Array.isArray(n.keys)||!Array.isArray(n.children)||n.children.length<2||n.children.length>ne||n.keys.length!==n.children.length-1||typeof n.maxKeyHash!="string"||!fe.test(n.maxKeyHash))&&p("branch is invalid"),n.children.some(i=>typeof i!="string"||!fe.test(i))&&p("child reference is invalid"),new Set(n.children).size!==n.children.length&&p("child references are duplicated");let r=n.keys.map(pe);return sn(r),n}function Ce(e){let t=mn(e);return t.kind==="branch"?{nodes:[...t.children],values:[]}:{nodes:[],values:t.entries.flatMap(n=>"hash"in n.value?[n.value.hash]:[])}}function nt(e){return e.kind==="branch"?e.maxKeyHash:e.entries.length===0?void 0:K(e.entries.at(-1).key)}function tt(e,t,n){let r=e.kind==="leaf"?e.entries.map(a=>a.key):e.keys.map(pe);!n&&e.kind==="leaf"&&r.length===0&&p("non-root leaf is empty");for(let a of r)(t.lower!==void 0&&a<=t.lower||t.upper!==void 0&&a>t.upper)&&p("key is outside its parent range");let i=nt(e);(t.maximumHash!==void 0&&i!==t.maximumHash||t.upper!==void 0&&i!==K(t.upper))&&p("maximum key does not match its parent"),e.kind==="branch"&&t.upper!==void 0&&r.at(-1)>=t.upper&&p("separator does not precede its final child")}async function hn(e,t,n,r){fe.test(t)||p("reference is invalid");let i=mn(await e.get(t,me));return tt(i,n,r),i}function pn(e,t,n,r){return{lower:n===0?r.lower:t[n-1],upper:n<t.length?t[n]:r.upper,maximumHash:n<t.length?K(t[n]):e.maxKeyHash}}async function yn(e,t,n){he(n)||p("key path exceeded");let r=t,i={};for(let a=0;r!==null;a++){a>Ne&&p("tree depth exceeded");let o=await hn(e,r,i,a===0);if(o.kind==="leaf"){let l=o.entries.find(m=>m.key===n);return l===void 0?void 0:"hash"in l.value?e.get(l.value.hash):l.value.inline}let d=o.keys.map(pe),s=d.findIndex(l=>n<=l),u=s===-1?o.children.length-1:s;i=pn(o,d,u,i),r=o.children[u]}}function xn(e,t,n){let r=e.length;if(r<=ne&&_e(n([...e]))<=me)return[[...e]];let i=new Map,a=(s,u)=>{let l=`${s}:${u}`,m=i.get(l);return m===void 0&&(m=_e(n(e.slice(s,u)))<=me,i.set(l,m)),m},o=Array(r+1).fill(1/0);o[r]=0;for(let s=r-t;s>=0;s--)for(let u=s+t;u<=Math.min(r,s+ne);u++)a(s,u)&&(o[s]=Math.min(o[s],1+o[u]));Number.isFinite(o[0])||p("cannot be partitioned within source capacity");let d=[];for(let s=0;s<r;){let u=(r-s)/o[s],l=[];for(let g=s+t;g<=Math.min(r,s+ne);g++)o[g]+1===o[s]&&a(s,g)&&l.push(g);l.sort((g,h)=>Math.abs(g-s-u)-Math.abs(h-s-u)||g-h);let m=l[0];m===void 0&&p("partition has no bounded continuation"),d.push(e.slice(s,m)),s=m}return d}function ln(e){let t=e.slice(0,-1).map(n=>(n.maximumKey===void 0&&p("branch separator is unavailable"),et(n.maximumKey)));return{format:ge,kind:"branch",separatorEncoding:gn,keys:t,children:e.map(n=>n.hash),maxKeyHash:e.at(-1).maximumHash}}function un(e,t){return xn(t,2,ln).map(n=>({hash:e.put(ln(n)),maximumKey:n.at(-1).maximumKey,maximumHash:n.at(-1).maximumHash}))}async function wn(e,t,n,r){he(n)||p("key path exceeded");let i=y(r),a=JSON.parse(i),o=Buffer.byteLength(i)<=cn?void 0:dn("sha256").update(i).digest("hex"),d=()=>o===void 0?{inline:a}:{hash:e.put(a)},s=0,u=g=>xn(g,1,h=>({format:ge,kind:"leaf",entries:h})).map(h=>({hash:e.put({format:ge,kind:"leaf",entries:h}),maximumKey:h.at(-1).key,maximumHash:K(h.at(-1).key)})),l=async(g,h,j)=>{if(j>Ne&&p("tree depth exceeded"),s=Math.max(s,j),g===null)return u([{key:n,value:d()}]);let x=await hn(e,g,h,j===0);if(x.kind==="leaf"){let E=[...x.entries],M=E.findIndex(V=>V.key>=n),U=E[M];return U?.key===n&&("hash"in U.value?U.value.hash===o:o===void 0&&y(U.value.inline)===i)?[{hash:g,maximumKey:E.at(-1).key,maximumHash:K(E.at(-1).key)}]:(M===-1?E.push({key:n,value:d()}):U.key===n?E[M]={key:n,value:d()}:E.splice(M,0,{key:n,value:d()}),u(E))}let R=x.keys.map(pe),N=R.findIndex(E=>n<=E),C=N===-1?x.children.length-1:N,H=x.children.map((E,M)=>({hash:E,maximumKey:M<R.length?R[M]:h.upper,maximumHash:M<R.length?K(R[M]):x.maxKeyHash})),L=await l(x.children[C],pn(x,R,C,h),j+1);return L.length===1&&L[0].hash===x.children[C]?[{hash:g,maximumKey:h.upper,maximumHash:x.maxKeyHash}]:(H.splice(C,1,...L),un(e,H))},m=await l(t,{},0);for(;m.length>1;)++s>Ne&&p("tree depth exceeded"),m=un(e,m);return m[0].hash}var at="journal-index",B="resume-head.json",G="resume-pending.json",ae="indexed-rotation.json",v=c.string().regex(/^[0-9a-f]{64}$/),Be=c.object({recordCount:c.number().int().nonnegative(),lastSeq:c.number().int().min(-1),lastEventId:c.string().nullable(),lastHash:v.nullable(),byteLength:c.number().int().nonnegative(),segmentCount:c.number().int().nonnegative().optional(),mtimeMs:c.number().optional()}),kn=c.object({generation:c.string().uuid(),segment:c.number().int().positive(),offset:c.number().int().nonnegative(),bytes:c.number().int().positive(),seq:c.number().int().nonnegative(),eventId:c.string(),hash:v}),Rn=c.union([c.literal(ue),c.literal($)]),ie=c.object({layout:Rn,generation:c.string().uuid(),commitId:c.string().uuid(),baseCommitId:c.string().uuid().nullable(),baseDescriptor:v.nullable(),objectDelta:v,snapshot:v,projection:v,indexRoot:v.nullable(),businessCursor:Be}),oe=c.object({layout:Rn,generation:c.string().uuid(),commitId:c.string().uuid(),descriptor:v,cursor:Be,witness:kn.nullable()}),it=c.object({generation:c.string().uuid(),baseCommitId:c.string().uuid(),baseCursor:Be,head:oe,segment:c.number().int().positive(),offset:c.number().int().nonnegative(),bytes:c.number().int().positive(),hash:v}),te=c.object({key:c.string().max(4096),value:v,left:v.nullable(),right:v.nullable()}),ye=32*1024,En=c.object({format:c.literal("journal-working-set-v1"),length:c.number().int().nonnegative(),pages:c.array(c.object({start:c.number().int().nonnegative(),count:c.number().int().positive().max(64),hash:v})),cleanBoundaries:c.array(c.number().int().nonnegative()).nullable()}),re=e=>rt("sha256").update(e).digest("hex"),we=e=>k.join(e,at),S=(e,t)=>k.join(we(e),t),In=(e,t)=>k.join(we(e),"objects",`${v.parse(t)}.json`);function f(e){throw new J("JOURNAL_RECONCILIATION_REQUIRED",e)}function w(e,t,n){let r=e.safeParse(t);return r.success||f(`Indexed journal ${n} is invalid; original responsibility retained`),r.data}async function b(e){try{return await Te(e),!0}catch(t){if(T(t)&&t.code==="ENOENT")return!1;throw t}}async function X(e){try{return JSON.parse(await jn(e,"utf8"))}catch(t){throw new J("JOURNAL_RECONCILIATION_REQUIRED",`Indexed journal control cannot be read: ${k.basename(e)} (${t instanceof Error?t.name:"error"})`)}}async function ot(e,t){if(t===void 0)return jn(e);let n=await Le(e,"r");try{(await n.stat()).size>t&&f("Indexed journal object source capacity exceeded");let r=Buffer.alloc(t+1),i=0;for(;i<r.length;){let a=await n.read(r,i,r.length-i,i);if(a.bytesRead===0)break;i+=a.bytesRead}return i>t&&f("Indexed journal object source capacity exceeded"),r.subarray(0,i)}finally{await n.close()}}var A=class{constructor(t,n,r=ue){this.dir=t;this.source=n;this.layout=r}dir;source;layout;staged=new Map;cached=new Map;sizes=new Map;existing=new Set;put(t){let n=y(t),r=re(n);return this.existing.has(r)||this.staged.set(r,n),this.cached.set(r,JSON.parse(n)),this.sizes.set(r,Buffer.byteLength(n)),r}async get(t,n){if(v.parse(t),this.cached.has(t))return n!==void 0&&this.sizes.get(t)>n&&f("Indexed journal object source capacity exceeded"),this.cached.get(t);let r;try{r=await ot(In(this.dir,t),n)}catch(a){if(!(T(a)&&a.code==="ENOENT"))throw a;this.source===void 0&&f("Selected indexed object is missing; full fallback is disabled");let o=await this.source(t,n);o===null&&f("Selected indexed object is missing from original source"),r=o}n!==void 0&&r.length>n&&f("Indexed journal object source capacity exceeded"),re(r)!==t&&f("Indexed journal object hash mismatch");let i;try{i=JSON.parse(Buffer.from(r).toString("utf8"))}catch{f("Indexed journal object is not valid JSON")}return this.cached.set(t,i),this.sizes.set(t,r.length),this.existing.add(t),i}async find(t,n){if(this.layout===$)return t===null?void 0:yn(this,t,n);let r=t;for(let i=0;r!==null;i++){i>256&&f("Indexed journal tree depth exceeded");let a=w(te,await this.get(r,ye),"index node");if(n===a.key)return this.get(a.value);r=n<a.key?a.left:a.right}}async set(t,n,r,i=0){if(this.layout===$)return wn(this,t,n,r);(i>256||n.length>4096)&&f("Indexed journal key path exceeded");let a=this.put(r),o=async(d,s)=>{if(s>256&&f("Indexed journal tree depth exceeded"),d===null)return this.put({key:n,value:a,left:null,right:null});let u=w(te,await this.get(d,ye),"index node");if(n===u.key)return this.put({...u,value:a});let l=n<u.key?"left":"right",m=await o(u[l],s+1),g=w(te,await this.get(m,ye),"index child"),h={...u,[l]:m},j=x=>`${re(x)}:${x}`;return j(g.key)<j(u.key)?l==="left"?this.put({...g,right:this.put({...h,left:g.right})}):this.put({...g,left:this.put({...h,right:g.left})}):this.put(h)};return o(t,i)}stagedReachable(t,n,r){let i=new Set,a=s=>!this.staged.has(s)||i.has(s)?!1:(i.add(s),!0);if(a(t)){let s=w(En,this.cached.get(t),"staged working set");for(let u of s.pages)a(u.hash)}a(n);let o=r===null?[]:[r],d=new Set;for(;o.length>0;){let s=o.pop();if(!(!this.staged.has(s)||d.has(s)))if(d.add(s),a(s),this.layout===$){let u=Ce(this.cached.get(s));for(let l of u.values)a(l);o.push(...u.nodes)}else{let u=w(te,this.cached.get(s),"staged index node");a(u.value),u.left!==null&&o.push(u.left),u.right!==null&&o.push(u.right)}}return[...i].sort()}async flush(t){await bn(k.join(we(this.dir),"objects"),{recursive:!0});let n=t.map(o=>[o,this.staged.get(o)]),r=0,i=!1,a;if(await Promise.all(Array.from({length:Math.min(8,n.length)},async()=>{for(;!i;){let o=n[r++];if(o===void 0)return;try{o[1]===void 0&&f("Indexed commit references an unstaged object"),await O(In(this.dir,o[0]),o[1])}catch(d){i||(i=!0,a=d)}}})),i)throw a}};function Sn(e,t,n){let r=[];for(let i=0;i<n.length;i+=64){let a=n.slice(i,i+64);r.push({start:i,count:a.length,hash:e.put(a)})}return e.put({format:"journal-working-set-v1",length:n.length,pages:r,cleanBoundaries:an(t)})}async function D(e,t){let n=w(En,await e.get(t),"working set descriptor"),r=0;for(let i of n.pages)i.start!==r&&f("Working set page coverage mismatch"),r+=i.count;return(r!==n.length||n.cleanBoundaries?.some((i,a,o)=>i>n.length||a>0&&i<=o[a-1]))&&f("Working set descriptor is incomplete"),n}async function Ie(e,t,n,r,i,a,o){let d=[];for(let s of t.pages){if(s.start>=r||s.start+s.count<=n)continue;let u=w(c.array(c.unknown()),await e.get(s.hash),"working set page");u.length!==s.count&&f("Working set page count mismatch");for(let l of u.slice(Math.max(0,n-s.start),Math.min(s.count,r-s.start))){let m=o.length,g=a.rehydrateImages===!1?l:a.attachmentSource===void 0?await en(l,i,o):await nn(l,a.attachmentSource,o);o.length!==m&&f("Required working-set attachment could not be verified"),d.push(a.rehydrateImages===!1||a.validateMessages===!1?g:w(qe,g,"working set IRMessage"))}}return d}async function Wt(e){return z(await F(e))}async function Yt(e){(await b(k.join(e,"journal.next.jsonl"))||await b(k.join(e,ae))||await b(S(e,G))||!await b(S(e,B)))&&f("Indexed journal original responsibility must be reconciled before reading")}async function Qt(e,t=null,n=ue){await W(e);let r=await F(e);if(r!==null){if(z(r))return;f("Existing journal cannot be implicitly migrated to indexed layout")}let i=Y(e);await b(i)&&(await Te(i)).size!==0&&f("Existing journal cannot be implicitly migrated to indexed layout"),await b(k.join(e,"journal.next.jsonl"))&&f("Legacy pending rotation requires explicit reconciliation");let a=xe();await rn(e,{schemaVersion:n===$?4:3,layout:n,generation:a,segments:[],live:{firstSeq:0}}),await bn(we(e),{recursive:!0});let o=new A(e,void 0,n),d={...tn,segmentCount:0},s=xe(),u=Sn(o,[],[]),l=o.put(t??null),m=o.stagedReachable(u,l,null),g={layout:n,generation:a,commitId:s,baseCommitId:null,baseDescriptor:null,objectDelta:o.put(m),snapshot:u,projection:l,indexRoot:null,businessCursor:d},h={layout:n,generation:a,commitId:s,descriptor:o.put(g),cursor:d,witness:null};await o.flush([...m,g.objectDelta,h.descriptor]),await O(i,""),await O(S(e,B),y(h))}async function Ue(e,t){let n=0;for(let r of t.segments){if(r.n!==n+1&&f("Indexed journal segment order mismatch"),r.status==="pending"&&!await b(Q(e,r.n)))break;n++}return n}async function Pn(e,t,n,r,i,a={}){(!Number.isSafeInteger(r+i)||i<1)&&f("Invalid indexed journal byte range");let o=t.segments.find(u=>u.n===n),d=o!==void 0&&(o.status==="sealed"||await b(Q(e,n))),s=d?Q(e,n):Y(e);!d&&n!==await Ue(e,t)+1&&f("Indexed journal segment is not current");try{let u=await Le(s,"r");try{let l=Buffer.alloc(i),m=0;for(;m<i;){let g=await u.read(l,m,i-m,r+m);g.bytesRead===0&&f("Indexed journal original range is incomplete"),m+=g.bytesRead}return l}finally{await u.close()}}catch(u){if(!(T(u)&&u.code==="ENOENT")||!d||o===void 0||a.segmentSource===void 0)throw u;let l=await a.segmentSource(o,e);l===null&&f("Indexed journal selected original segment is missing");let m=l.getReader(),g=Buffer.alloc(i),h=0,j=0;try{for(;j<i;){let x=await m.read();x.done&&f("Indexed journal selected cold range is incomplete");let R=Math.max(0,r-h),N=Math.min(x.value.byteLength,r+i-h);N>R&&(g.set(x.value.subarray(R,N),j),j+=N-R),h+=x.value.byteLength}}finally{await m.cancel().catch(()=>{}),m.releaseLock()}return g}}async function He(e,t,n,r){n.generation!==t.generation&&f("Indexed journal original generation mismatch");let i;try{i=await Pn(e,t,n.segment,n.offset,n.bytes,r.recordSource===void 0?r:{...r,segmentSource:void 0})}catch(d){if(!(T(d)&&d.code==="ENOENT"))throw d;r.recordSource===void 0&&f("Selected indexed original record is missing; full fallback is disabled");let s=await r.recordSource(n);(s===null||s.byteLength!==n.bytes)&&f("Selected indexed original record is missing"),i=Buffer.from(s)}i.at(-1)!==10&&f("Indexed journal original is not a complete record");let a;try{a=JSON.parse(i.toString("utf8"))}catch{f("Indexed journal original record is not valid JSON")}let o=w(Re,a,"original record");return(o.seq!==n.seq||o.eventId!==n.eventId||o.integrity.hash!==n.hash||Oe(o)!==n.hash||o.completeness!=="complete")&&f("Indexed journal original proof mismatch"),o}async function se(e,t,n,r,i){(n.generation!==t.generation||n.layout!==t.layout)&&f("Indexed journal head generation/layout mismatch");let a=w(ie,await r.get(n.descriptor),"descriptor");if((a.generation!==n.generation||a.commitId!==n.commitId||a.layout!==n.layout)&&f("Indexed journal descriptor identity/layout mismatch"),n.witness===null)(n.cursor.recordCount!==0||n.cursor.lastSeq!==-1||n.cursor.lastHash!==null||n.cursor.lastEventId!==null||n.cursor.byteLength!==0||a.baseCommitId!==null||a.baseDescriptor!==null||a.indexRoot!==null||t.segments.length!==0||y(n.cursor)!==y(a.businessCursor)||(await D(r,a.snapshot)).length!==0)&&f("Indexed journal empty head is not empty");else{(a.baseCommitId===null||a.baseDescriptor===null)&&f("Indexed journal commit has no original base");let l=await He(e,t,n.witness,i),m={type:"indexed_journal_commit",descriptor:n.descriptor,commitId:n.commitId,generation:n.generation};(l.kind!=="event"||l.visibility.model||l.visibility.defaultTranscript||l.visibility.expandedTranscript||l.visibility.sdk||y(l.payload)!==y(m)||l.integrity.previousHash!==a.businessCursor.lastHash||l.seq!==a.businessCursor.lastSeq+1||n.cursor.lastHash!==l.integrity.hash||n.cursor.lastSeq!==l.seq||n.cursor.lastEventId!==l.eventId||n.cursor.recordCount!==a.businessCursor.recordCount+1||n.witness.offset!==a.businessCursor.byteLength||n.cursor.byteLength!==n.witness.offset+n.witness.bytes||n.witness.segment!==(n.cursor.segmentCount??0)+1)&&f("Indexed journal commit witness mismatch")}let o=await Ue(e,t),d=n.witness!==null&&n.witness.segment<=o;if(d){let l=t.segments[o-1];(l?.lastSeq!==n.cursor.lastSeq||l.lastHash!==n.cursor.lastHash)&&f("Indexed journal head is behind sealed records")}else(n.cursor.segmentCount??0)!==o&&f("Indexed journal head segment mismatch");let s=d?0:n.cursor.byteLength,u=0;try{u=(await Te(Y(e))).size}catch(l){if(!(T(l)&&l.code==="ENOENT"&&s===0))throw l}return u!==s&&f("Indexed journal head does not cover the exact original tail"),{descriptor:a,cursor:{...n.cursor,byteLength:s,segmentCount:o}}}async function be(e,t,n,r){let i=S(e,G);if(!await b(i))return n;let a=w(it,await X(i),"pending");(a.generation!==t.generation||a.head.generation!==t.generation||a.head.layout!==t.layout||n.commitId!==a.baseCommitId&&n.commitId!==a.head.commitId)&&f("Indexed journal pending base mismatch");try{r.reconcile||f("Indexed journal has an unresolved original commit"),(a.offset!==a.baseCursor.byteLength||a.segment!==(a.baseCursor.segmentCount??0)+1||n.commitId===a.baseCommitId&&(n.cursor.lastHash!==a.baseCursor.lastHash||n.cursor.lastSeq!==a.baseCursor.lastSeq||n.cursor.recordCount!==a.baseCursor.recordCount))&&f("Indexed journal pending original cursor mismatch");let o=await Pn(e,t,a.segment,a.offset,a.bytes,r);re(o)!==a.hash&&f("Indexed journal pending original bytes are incomplete or mismatched");let d=new A(e,r.objectSource,a.head.layout),s=await se(e,t,a.head,d,r);(s.descriptor.baseCommitId!==a.baseCommitId||n.commitId===a.baseCommitId&&s.descriptor.baseDescriptor!==n.descriptor)&&f("Indexed journal pending descriptor base mismatch");let u=a.segment<=await Ue(e,t)?Q(e,a.segment):Y(e),l=await Le(u,"r+");try{await l.sync()}finally{await l.close()}return await O(S(e,B),y(a.head)),await vn(i),a.head}catch(o){throw o instanceof le?o:new le(a.head.commitId,[],"unknown",o)}}async function Zt(e,t={}){let n=await F(e);if(!z(n))return null;await b(k.join(e,"journal.next.jsonl"))&&f("Legacy pending rotation cannot be consumed by indexed journal"),await b(k.join(e,ae))&&f("Indexed journal generation rotation requires reconciliation");let r=w(oe,await X(S(e,B)),"head");r=await be(e,n,r,t);let i=new A(e,t.objectSource,n.layout),{descriptor:a,cursor:o}=await se(e,n,r,i,t),d=[],s=await D(i,a.snapshot);return{snapshot:await Ie(i,s,0,s.length,e,t,d),projection:await i.get(a.projection),cursor:o,head:r,repairs:d,async readRecord(l){if(r.witness!==null&&("eventId"in l?l.eventId===r.witness.eventId:l.seq===r.witness.seq))return He(e,n,r.witness,t);let m=await i.find(a.indexRoot,"eventId"in l?`record:event:${l.eventId}`:`record:seq:${l.seq}`);return m===void 0?void 0:He(e,n,w(kn,m,"record reference"),t)},getFact:l=>i.find(a.indexRoot,`fact:${l}`)}}async function Jn(e,t={}){let n=await F(e);if(!z(n))return null;(await b(k.join(e,"journal.next.jsonl"))||await b(k.join(e,ae)))&&f("Indexed writer generation is unresolved");let r=w(oe,await X(S(e,B)),"head");r=await be(e,n,r,t);let i=new A(e,t.objectSource,n.layout),a=await se(e,n,r,i,t),o=await D(i,a.descriptor.snapshot),d=t.snapshotTail===!0&&o.length>0?(await Ie(i,o,o.length-1,o.length,e,{...t,rehydrateImages:!1},[]))[0]:void 0;return{head:r,cursor:a.cursor,projection:await i.get(a.descriptor.projection),snapshotLength:o.length,...d===void 0?{}:{lastMessage:d}}}async function er(e,t,n){let r=await F(e);if(!z(r))return null;let i=async()=>{(await b(k.join(e,"journal.next.jsonl"))||await b(k.join(e,ae)))&&f("Indexed writer generation is unresolved")};await i();let a=w(oe,await X(S(e,B)),"head");a=await be(e,r,a,{...t,reconcile:!0}),(a.generation!==r.generation||a.layout!==r.layout)&&f("Indexed journal head generation/layout mismatch");let o=new A(e,t.objectSource,r.layout),d=w(ie,await o.get(a.descriptor),"descriptor");(d.generation!==a.generation||d.commitId!==a.commitId||d.layout!==a.layout)&&f("Indexed journal descriptor identity/layout mismatch");let s=await D(o,d.snapshot),u=s.length===0?void 0:(await Ie(o,s,s.length-1,s.length,e,{...t,rehydrateImages:!1},[]))[0],l=await o.get(d.projection),m=n({snapshotLength:s.length,...u===void 0?{}:{lastMessage:structuredClone(u)}});if(typeof m!="boolean")throw new J("CURSOR_STALE","Indexed commit decision must be synchronous");let g=await se(e,r,a,o,t);return(y(await F(e))!==y(r)||y(await X(S(e,B)))!==y(a)||await b(S(e,G)))&&f("Indexed journal changed during commit preparation"),await i(),{manifest:r,needsWriter:m,state:{head:a,cursor:g.cursor,projection:l,snapshotLength:s.length,...u===void 0?{}:{lastMessage:u}}}}async function*nr(e,t={}){let n=await Jn(e,t);if(n===null)return;let r=new A(e,t.objectSource,n.head.layout),i=w(ie,await r.get(n.head.descriptor),"descriptor"),a=await D(r,i.snapshot),o=new Set,d=async u=>{if(o.has(u))return null;let l=await r.get(u);return o.add(u),{hash:u,data:Buffer.from(y(l))}};for(let u of[n.head.descriptor,i.snapshot,i.projection,...a.pages.map(l=>l.hash)]){let l=await d(u);l!==null&&(yield l)}let s=i.indexRoot===null?[]:[i.indexRoot];for(;s.length>0;){let u=s.pop();if(o.has(u))continue;let l=await r.get(u,ye),m=await d(u);if(m!==null&&(yield m),n.head.layout===$){let g=Ce(l);for(let h of g.values){let j=await d(h);j!==null&&(yield j)}s.push(...g.nodes)}else{let g=w(te,l,"index node"),h=await d(g.value);h!==null&&(yield h),g.left!==null&&s.push(g.left),g.right!==null&&s.push(g.right)}}}async function*tr(e,t={}){let n=await Jn(e,t);if(n===null)return;t.afterDescriptor!==void 0&&w(v,t.afterDescriptor,"confirmed cold descriptor");let r=new A(e,t.objectSource,n.head.layout),i=new Set,a=new Set,o=n.head.descriptor,d=n.head.commitId;for(;o!==null&&o!==t.afterDescriptor;){a.has(o)&&f("Indexed cold delta descriptor cycle"),a.add(o);let s=w(ie,await r.get(o),"cold delta descriptor");(s.generation!==n.head.generation||s.commitId!==d||s.layout!==n.head.layout||s.baseDescriptor===null!=(s.baseCommitId===null))&&f("Indexed cold delta original chain mismatch");let u=w(c.array(v),await r.get(s.objectDelta),"cold delta objects");for(let l of[o,s.objectDelta,...u]){if(i.has(l))continue;let m=await r.get(l);i.add(l),yield{hash:l,data:Buffer.from(y(m))}}o=s.baseDescriptor,d=s.baseCommitId??""}t.afterDescriptor!==void 0&&o!==t.afterDescriptor&&f("Confirmed cold descriptor is not an ancestor in this original generation")}async function rr(e,t){let n=await F(e);if(!z(n))return null;(await b(k.join(e,"journal.next.jsonl"))||await b(k.join(e,ae)))&&f("Indexed history generation is unresolved");let r=w(oe,await X(S(e,B)),"head");r=await be(e,n,r,t);let i=new A(e,t.objectSource,n.layout),{descriptor:a}=await se(e,n,r,i,t),o=await D(i,a.snapshot);if(!Number.isFinite(t.offset)||!Number.isFinite(t.limit)||t.offset<0||t.limit<0)throw new J("INVALID_PAGE","Invalid indexed history page");let d=Math.min(Math.floor(t.offset),o.length),s=Math.floor(t.limit);if(s===0||d===o.length)return{messages:[],total:o.length,offset:d,nextOffset:d};let u=on(o.length,o.cleanBoundaries,d,s)??{start:d,end:Math.min(d+s,o.length)};return{messages:await Ie(i,o,u.start,u.end,e,t,[]),total:o.length,offset:u.start,nextOffset:u.end}}async function ar(e,t,n,r,i,a,o={},d=!0,s={},u){if(await W(e),await b(S(e,G))&&f("Indexed writer cannot append past unresolved original commit"),o.snapshot===void 0&&r.some(I=>I.branchId==="main"&&I.visibility.model&&(I.kind==="user_prompt"||I.kind==="assistant_message"||I.kind==="tool_result")))throw new J("JOURNAL_PROJECTION_REQUIRED","Indexed message commit requires the actual working snapshot");let l=new A(e,s.objectSource,t.layout),m=w(ie,await l.get(t.descriptor),"descriptor");(m.layout!==t.layout||m.generation!==t.generation||m.commitId!==t.commitId)&&f("Indexed journal original descriptor identity/layout mismatch");let g=m.indexRoot;t.witness!==null&&(g=await l.set(g,`record:event:${t.witness.eventId}`,t.witness),g=await l.set(g,`record:seq:${t.witness.seq}`,t.witness));let h=n.byteLength,j=(n.segmentCount??0)+1;for(let I=0;I<r.length;I++){let P=r[I],q={generation:t.generation,segment:j,offset:h,bytes:i[I].length,seq:P.seq,eventId:P.eventId,hash:P.integrity.hash};await l.find(g,`record:event:${P.eventId}`)!==void 0&&f("Indexed journal eventId already exists; original batch must not be replayed"),g=await l.set(g,`record:event:${P.eventId}`,q),g=await l.set(g,`record:seq:${P.seq}`,q),h+=q.bytes}let x=o.projectionSeed!==void 0?o.projectionSeed:await l.get(m.projection);o.projectionSeed!==void 0&&n.recordCount!==0&&f("Projection seed is only valid on an empty indexed generation");let R=new Map;a.reduce!==void 0&&(x=await a.reduce(x,r,{get:async I=>R.has(I)?R.get(I):l.find(g,`fact:${I}`),set:(I,P)=>{R.set(I,P)}}));for(let[I,P]of R)g=await l.set(g,`fact:${I}`,P);let N=m.snapshot;if(o.snapshot!==void 0){let I=await D(l,m.snapshot);for(let q of I.pages)l.existing.add(q.hash);let P=[];for(let q of o.snapshot)P.push(d?await Ze(q,e):q);N=Sn(l,o.snapshot,P)}let C=r.at(-1),H={...n,recordCount:n.recordCount+r.length,lastSeq:C?.seq??n.lastSeq,lastHash:C?.integrity.hash??n.lastHash,lastEventId:C?.eventId??n.lastEventId,byteLength:h},L=xe(),E=l.put(x??null),M=l.stagedReachable(N,E,g),U={layout:t.layout,generation:t.generation,commitId:L,baseCommitId:t.commitId,baseDescriptor:t.descriptor,objectDelta:l.put(M),snapshot:N,projection:E,indexRoot:g,businessCursor:H},V=l.put(U),_=Re.parse({schemaVersion:2,eventId:xe(),sessionId:C?.sessionId??u??k.basename(e),branchId:"main",seq:H.lastSeq+1,kind:"event",parentEventId:H.lastEventId,producer:"kernel:journal-index",payload:{type:"indexed_journal_commit",descriptor:V,commitId:L,generation:t.generation},visibility:{model:!1,defaultTranscript:!1,expandedTranscript:!1,sdk:!1},completeness:"complete",integrity:{previousHash:H.lastHash,hash:""}});_.integrity.hash=Oe(_);let je=Buffer.from(`${JSON.stringify(_)}
|
|
6
|
+
`),ve=Buffer.concat([...i,je]),ke={layout:t.layout,generation:t.generation,commitId:L,descriptor:V,cursor:{...H,recordCount:H.recordCount+1,lastSeq:_.seq,lastHash:_.integrity.hash,lastEventId:_.eventId,byteLength:h+je.length},witness:{generation:t.generation,segment:j,offset:h,bytes:je.length,seq:_.seq,eventId:_.eventId,hash:_.integrity.hash}};await W(e),await l.flush([...M,U.objectDelta,V]);let Mn={generation:t.generation,baseCommitId:t.commitId,baseCursor:n,head:ke,segment:j,offset:n.byteLength,bytes:ve.length,hash:re(ve)};return await O(S(e,G),y(Mn)),{head:ke,witness:_,bytes:ve,commitId:L,projection:JSON.parse(y(x??null)),async publish(){try{await W(e),await O(S(e,B),y(ke)),await vn(S(e,G))}catch(I){throw new le(L,r,"committed",I)}}}}export{y as a,Oe as b,De as c,On as d,Se as e,Ln as f,Tn as g,ht as h,Ve as i,We as j,Ze as k,en as l,nn as m,tn as n,Yn as o,z as p,Et as q,St as r,F as s,rn as t,at as u,B as v,G as w,ae as x,Wt as y,Yt as z,Qt as A,Zt as B,Jn as C,er as D,nr as E,tr as F,rr as G,ar as H};
|
|
7
|
+
//# sourceMappingURL=tansr-chunk-4DAH4AIH.mjs.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
2
|
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
3
|
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
-
import{
|
|
4
|
+
import{Aa as j,Ba as w,Ca as O,Da as E,Fa as N,ta as L}from"./tansr-chunk-JIC3VWLQ.mjs";import{m as a}from"./tansr-chunk-YK3CE3JM.mjs";import{c as f}from"./tansr-chunk-3YSQG6KY.mjs";var R={rejected:"cli.policy.lifecycle_rejected",verifyRejected:"cli.policy.lifecycle_verify_rejected",lkgFallback:"cli.policy.lifecycle_lkg_fallback",requiredMissing:"cli.policy.lifecycle_required_missing",modeLocked:"cli.policy.mode_locked",refuseLaunch:"cli.policy.refuse_launch",stateWriteFailed:"cli.policy.state_write_failed",stateCorrupted:"cli.policy.state_corrupted",stateCorruptedRefuse:"cli.policy.state_corrupted_refuse",sessionBundleExpired:"cli.policy.session_bundle_expired",sessionRequiredExpired:"cli.policy.session_required_expired"},I=["acceptEdits","auto","bypassPermissions"],$="lkg";function Q(e){return{highWater:{...e.highWater},revoked:Object.fromEntries(Object.entries(e.revoked).map(([o,t])=>[o,[...t]])),lkg:{...e.lkg}}}function C(e){if(e!=="verified")return e==="rejected"?"verify_rejected":e==="unsupported"?"verify_unsupported":"verify_unsigned"}function D(e){let o=e.now??Date.now(),t=e.anchor?.requiredBundles??[],i=[],r=[],n=Q(e.state),s=!1,l=new Map;for(let c of t)l.has(c.id)||l.set(c.id,c);let p=(c,m)=>{let g=O(m);g>(n.highWater[c]??0)&&(n.highWater[c]=g,s=!0);let u=m.meta.revokedSequences??[];if(u.length>0){let P=new Set(n.revoked[c]??[]),k=P.size;for(let S of u)P.add(S);P.size!==k&&(n.revoked[c]=[...P].sort((S,_)=>S-_),s=!0)}},d=[],y=new Map,h=new Map;for(let c of e.groups){if(c.builtin===!0){d.push(c);continue}let m=[];for(let g of c.bundles){let u=g.meta.id;if(y.has(u)){m.push(g);continue}let P=l.get(u),k=E(g,{now:o,...P!==void 0?{anchor:P}:{},...n.highWater[u]!==void 0?{highWater:n.highWater[u]}:{},...n.revoked[u]!==void 0?{revoked:n.revoked[u]}:{}});if(!k.ok){h.has(u)||h.set(u,k.reason),i.push({message:a(R.rejected,{id:u,reason:k.reason}),level:"error"});continue}let S=L(g,e.verify).status;if(P!==void 0){let _=C(S);if(_!==void 0){h.has(u)||h.set(u,_),i.push({message:a(R.verifyRejected,{id:u,reason:_}),level:"error"});continue}}else if(S==="rejected"||S==="unsupported"){m.push(g);continue}m.push(g),y.set(u,g),p(u,g)}m.length>0&&d.push({...c,bundles:m})}let b=[];for(let c of l.values()){let m=y.get(c.id);if(m===void 0){let g=h.get(c.id)??"absent",u=n.lkg[c.id],P=u===void 0?void 0:C(L(u,e.verify).status)??(()=>{let k=E(u,{now:o,anchor:c,...n.highWater[c.id]!==void 0?{highWater:n.highWater[c.id]}:{},...n.revoked[c.id]!==void 0?{revoked:n.revoked[c.id]}:{}});return k.ok?void 0:k.reason})();if(u!==void 0&&P===void 0)b.push(u),m=u,p(c.id,u),i.push({message:a(R.lkgFallback,{id:c.id,sequence:O(u),reason:g}),level:"error"});else{r.push({bundleId:c.id,reason:u!==void 0?P:g}),i.push({message:a(R.requiredMissing,{id:c.id,reason:u!==void 0?P:g}),level:"error"});continue}}JSON.stringify(n.lkg[c.id])!==JSON.stringify(m)&&(n.lkg[c.id]=m,s=!0)}for(let c of Object.keys(n.lkg))l.has(c)||(delete n.lkg[c],s=!0);let B=r.length>0;return B?{groups:d.filter(c=>c.builtin===!0),notices:i,refuseLaunch:B,refusals:r,state:n,stateChanged:s}:(b.length>0&&d.push({dir:$,bundles:b}),{groups:d,notices:i,refuseLaunch:B,refusals:r,state:n,stateChanged:s})}function Re(e,o){return e===void 0||o===void 0||!o.lockedModes.includes(e)?{mode:e}:{mode:"default",lockedMode:e}}function ve(e){return{message:a(R.modeLocked,{mode:e}),level:"error"}}function be(e){let o=e.now??Date.now(),t=new Set((e.anchor?.requiredBundles??[]).map(s=>s.id)),i=[],r=[],n=[];for(let s of e.groups){if(s.builtin===!0){n.push(s);continue}let l=[];for(let p of s.bundles){let d=E(p,{now:o});if(d.ok){l.push(p);continue}let y=p.meta.id;t.has(y)?(r.push({bundleId:y,reason:d.reason}),i.push({message:a(R.sessionRequiredExpired,{id:y,reason:d.reason}),level:"error"})):i.push({message:a(R.sessionBundleExpired,{id:y,reason:d.reason}),level:"error"})}l.length>0&&n.push({...s,bundles:l})}return{groups:n,notices:i,refuseSession:r.length>0,refusals:r}}import z from"node:os";import Y from"node:path";import{randomBytes as H}from"node:crypto";import{mkdir as Z,open as q,readFile as X,rename as ee,rm as ie}from"node:fs/promises";import oe from"node:os";import x from"node:path";var re="policy-state.json";function M(){return{highWater:{},revoked:{},lkg:{}}}function A(e,o=oe.homedir()){let t=e.TANSR_CONFIG_DIR?.trim(),i=t!==void 0&&t!==""?t:x.join(o,".tansr");return x.join(i,re)}function te(e){let o={};if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[t,i]of Object.entries(e))typeof i=="number"&&Number.isInteger(i)&&i>=0&&(o[t]=i);return o}function ne(e){let o={};if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[t,i]of Object.entries(e)){if(!Array.isArray(i))continue;let r=i.filter(n=>typeof n=="number"&&Number.isInteger(n)&&n>=0);r.length>0&&(o[t]=[...new Set(r)].sort((n,s)=>n-s))}return o}function se(e){let o={};if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[t,i]of Object.entries(e)){let r=j(i);r.ok&&r.bundle.meta.id===t&&(o[t]=r.bundle)}return o}async function T(e,o=t=>X(t,"utf8")){let t;try{t=await o(e)}catch{return{state:M(),corrupted:!1}}let i;try{i=JSON.parse(t)}catch{return{state:M(),corrupted:!0}}if(typeof i!="object"||i===null||Array.isArray(i))return{state:M(),corrupted:!0};let r=i;return{state:{highWater:te(r.highWater),revoked:ne(r.revoked),lkg:se(r.lkg)},corrupted:!1}}async function F(e,o,t){let i=`${JSON.stringify(o,null,2)}
|
|
5
5
|
`;if(t!==void 0){await t(e,i);return}let r=x.dirname(e);await Z(r,{recursive:!0});let n=`${e}.tmp-${process.pid}-${H(4).toString("hex")}`,s=await q(n,"w");try{await s.writeFile(i,"utf8"),await s.sync()}finally{await s.close()}try{await ee(n,e)}catch(l){throw await ie(n,{force:!0}),l}try{let l=await q(r,"r");try{await l.sync()}finally{await l.close()}}catch{}}var ce="TANSR_RECOMMENDED_RULES",le="tansr-recommended-v1",W={meta:{id:le,version:"1.0.0",issuer:"tansr",issuedAt:"2026-07-29T00:00:00Z"},rules:{ask:["Shell(git push --force *)","Shell(git push *)","Shell(gh pr merge *)","Shell(npm publish *)","Shell(pnpm publish *)","Shell(yarn publish *)","Shell(docker push *)","Shell(git reset --hard *)","Shell(git clean *)","Shell(git stash drop *)"]}};function V(e=process.env,o){let t=e[ce]?.trim();return t!==void 0&&t!==""?t!=="0":o!==!1}var v={loaded:"cli.policy.loaded",sourceError:"cli.policy.source_error",bundleSkipped:"cli.policy.bundle_skipped",invalidRules:"cli.policy.invalid_rules",trustLoaded:"cli.policy.trust_loaded",trustError:"cli.policy.trust_error",trustLoadedManaged:"cli.policy.trust_loaded_managed",trustErrorManaged:"cli.policy.trust_error_managed",sectionIgnored:"cli.policy.section_ignored",trustEnvIgnoredManaged:"cli.policy.trust_env_ignored_managed"},ue="TANSR_POLICY_TRUST",de=f.object({id:f.string().min(1),issuer:f.string().min(1),audience:f.string().min(1).optional(),minSequence:f.number().int().nonnegative().optional()}).strict(),J=f.object({keys:f.record(f.string().min(1)),unsignedPolicy:f.enum(["accept","reject"]).optional(),requiredBundles:f.array(de).optional(),lockedModes:f.array(f.enum(I)).optional(),autoTierCeiling:f.enum(["none","low","medium","high"]).optional(),qualificationRemote:f.object({url:f.string().min(1),required:f.boolean().optional()}).strict().optional(),adjudicatorPool:f.object({url:f.string().min(1),required:f.boolean().optional()}).strict().optional()}).strict(),ae=f.object({trust:J.optional()}).strict(),G={unsignedPolicy:"reject",verifiers:[]};function K(e,o,t){let i;try{i=[N({publicKeys:e.keys})]}catch{return o("trust_key_invalid")}let r=e.requiredBundles!==void 0||e.lockedModes!==void 0||e.autoTierCeiling!==void 0||e.qualificationRemote!==void 0||e.adjudicatorPool!==void 0?{requiredBundles:e.requiredBundles??[],lockedModes:e.lockedModes??[],...e.autoTierCeiling!==void 0?{autoTierCeiling:e.autoTierCeiling}:{},...e.qualificationRemote!==void 0?{qualificationRemote:e.qualificationRemote}:{},...e.adjudicatorPool!==void 0?{adjudicatorPool:e.adjudicatorPool}:{}}:void 0;return{verify:{unsignedPolicy:e.unsignedPolicy??"accept",verifiers:i},...r!==void 0?{anchor:r}:{},trustedKeys:e.keys,notices:[t(Object.keys(e.keys).length)]}}function fe(e){return(e?.ignoredLayers??[]).map(o=>({message:a(v.sectionIgnored,{layer:o}),level:"info"}))}async function ye(e={}){let o=e.env??process.env,t=fe(e.policy),i=s=>({...s,notices:[...t,...s.notices]}),r=o[ue]?.trim(),n=r!==void 0&&r!=="";if(e.policy!==void 0&&"managed"in e.policy){let s=p=>({verify:G,notices:[{message:a(v.trustErrorManaged,{code:p}),level:"error"}]}),l=ae.safeParse(e.policy.managed);if(!l.success)return i(s("trust_shape_invalid"));if(l.data.trust!==void 0){let p=n?[{message:a(v.trustEnvIgnoredManaged,{file:r}),level:"info"}]:[],d=K(l.data.trust,s,y=>({message:a(v.trustLoadedManaged,{count:y}),level:"info"}));return i({...d,notices:[...p,...d.notices]})}}if(n){let s=h=>({verify:G,notices:[{message:a(v.trustError,{code:h,file:r}),level:"error"}]}),l=e.fs?.readFile??pe,p;try{p=await l(r)}catch{return i(s("trust_unreadable"))}let d;try{d=JSON.parse(p)}catch{return i(s("trust_json_invalid"))}let y=J.safeParse(d);return y.success?i(K(y.data,s,h=>({message:a(v.trustLoaded,{count:h}),level:"info"}))):i(s("trust_shape_invalid"))}return{notices:t}}async function pe(e){let{readFile:o}=await import("node:fs/promises");return o(e,"utf8")}function Ae(e){let o=e.verify?.verifiers;if(!(o===void 0||o.length===0))return{verifiers:o}}function ge(e,o=z.homedir()){let t=[],i=e.TANSR_POLICY_DIR?.trim();i!==void 0&&i!==""&&t.push(i);let r=e.TANSR_CONFIG_DIR?.trim(),n=r!==void 0&&r!==""?r:Y.join(o,".tansr");return t.push(Y.join(n,"policies")),t}async function me(e={}){let o=e.env??process.env,t=[],i=[];for(let r of ge(o,e.homedir)){let s=await new w({dir:r,...e.fs!==void 0?{fs:e.fs}:{},onDiagnostic:l=>{l.code!=="dir_missing"&&t.push({message:a(v.sourceError,{code:l.code,file:l.file}),level:l.severity==="error"?"error":"info"})}}).load();s.length>0&&i.push({dir:r,bundles:s})}return V(o,e.recommendedRules)&&i.push({dir:"builtin",bundles:[W],builtin:!0}),{groups:i,notices:t}}function U(e,o,t){let i=[];for(let r of o){let n=e.loadPolicyBundles(r.bundles,{source:r.builtin===!0?"builtin":`localDir:${r.dir}`,...t!==void 0&&r.builtin!==!0?{verify:t}:{}}),s=0;for(let l of n)l.status==="loaded"?s+=1:(r.builtin!==!0||l.reason!=="duplicate_id")&&i.push({message:a(v.bundleSkipped,{id:l.bundleId,reason:l.reason??"unknown"}),level:"error"}),l.invalidRuleCount>0&&i.push({message:a(v.invalidRules,{id:l.bundleId,count:l.invalidRuleCount}),level:"error"});s>0&&r.builtin!==!0&&i.push({message:a(v.loaded,{count:s,dir:r.dir}),level:"info"})}return i}async function Te(e,o={}){let t=o.env??process.env,i=o.trust??await ye(o),{groups:r,notices:n}=await me(o),s=o.statePath??A(t,o.homedir??z.homedir()),l=await T(s,o.fs?.readFile),p=i.anchor?.requiredBundles??[];if(l.corrupted&&p.length>0){let h=p.map(c=>({bundleId:c.id,reason:"state_corrupted"})),b=[...i.notices,...n];b.push({message:a(R.stateCorruptedRefuse,{file:s}),level:"error"});for(let c of h)b.push({message:a(R.requiredMissing,{id:c.bundleId,reason:c.reason}),level:"error"});let B=r.filter(c=>c.builtin===!0);return b.push(...U(e,B,i.verify)),{notices:b,refuseLaunch:!0,refusals:h,...i.anchor!==void 0?{anchor:i.anchor}:{},groups:B}}l.corrupted&&n.push({message:a(R.stateCorrupted,{file:s}),level:"error"});let d=D({groups:r,verify:i.verify,anchor:i.anchor,state:l.state,...o.now!==void 0?{now:o.now}:{}}),y=[...i.notices,...n,...d.notices];if(d.stateChanged)try{await F(s,d.state,o.stateWriteFile)}catch{y.push({message:a(R.stateWriteFailed,{file:s}),level:"error"})}return y.push(...U(e,d.groups,i.verify)),{notices:y,refuseLaunch:d.refuseLaunch,refusals:d.refusals,...i.anchor!==void 0?{anchor:i.anchor}:{},groups:d.groups}}export{R as a,I as b,Re as c,ve as d,be as e,ye as f,Ae as g,ge as h,U as i,Te as j};
|
|
6
|
-
//# sourceMappingURL=tansr-chunk-
|
|
6
|
+
//# sourceMappingURL=tansr-chunk-4IWNKAT5.mjs.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
+
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
+
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
+
import{a as U,ca as P,d as D}from"./tansr-chunk-AOH7YPF3.mjs";var w=class extends Error{constructor(t){super(`SDK2 event store: ${t}`);this.code=t;this.name="EventStoreError"}code};import{createHash as C,createHmac as $,timingSafeEqual as L}from"node:crypto";import{types as x}from"node:util";var K=(1n<<63n)-1n;var z=262317,V=/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/,Z=/^[a-f0-9]{64}$/,J=["active","backpressured","closing","closed"],Q=["source_unavailable","stale_generation","invalid_coverage","request_expired","material_rejected","forbidden","binding_closed"],F=Object.getPrototypeOf(Uint8Array.prototype),X=Object.getOwnPropertyDescriptor(F,"byteLength").get,Y=Object.getOwnPropertyDescriptor(F,"buffer").get;function r(e="invalid_input"){throw new w(e)}function _(e){(!e||typeof e!="object"||x.isProxy(e)||!x.isUint8Array(e)||X.call(e)!==32||x.isSharedArrayBuffer(Y.call(e)))&&r(),Reflect.ownKeys(e).length!==32&&r();for(let t=0;t<32;t++){let i=Object.getOwnPropertyDescriptor(e,String(t));(!i||!("value"in i)||!i.enumerable)&&r()}return new Uint8Array(e)}function m(e){(!e||typeof e!="object"||x.isProxy(e)||![Object.prototype,null].includes(Object.getPrototypeOf(e)))&&r();for(let n of Reflect.ownKeys(e)){let t=Object.getOwnPropertyDescriptor(e,n);(typeof n!="string"||!t.enumerable||!("value"in t))&&r()}return e}function u(e,n,t=[]){let i=m(e);return(n.some(o=>!Object.hasOwn(i,o))||Object.keys(i).some(o=>!n.includes(o)&&!t.includes(o)))&&r(),i}function l(e,n=0,t=Number.MAX_SAFE_INTEGER){return(typeof e!="number"||!Number.isSafeInteger(e)||Object.is(e,-0)||e<n||e>t)&&r(),e}function d(e){return(typeof e!="string"||!V.test(e))&&r(),e}function T(e){return(typeof e!="string"||e.length===0||e.length>1024||[...e].length>512||Buffer.from(e).toString("utf8")!==e)&&r(),e}function c(e){(typeof e!="string"||!/^(0|[1-9][0-9]{0,18})$/.test(e))&&r();let n=BigInt(e);return n>K&&r(),n}function h(e){return(typeof e!="string"||!Z.test(e))&&r(),e}function E(e,n){(typeof e!="string"||!n.includes(e))&&r()}function p(e){try{return U(e)}catch{return r()}}function W(e){try{return D(e)}catch{return r()}}function G(e){return C("sha256").update(e).digest("hex")}function S(e,n){return C("sha256").update(e).update("\0").update(p(n)).digest("hex")}function H(e,n){return Buffer.from(p(e)).equals(Buffer.from(p(n)))}function B(e){let n=u(e,["applicationScopeId","endUserId","bindingId"]);return{applicationScopeId:d(n.applicationScopeId),endUserId:T(n.endUserId),bindingId:d(n.bindingId)}}function ye(e){let n=u(e,["eventRetentionMs","eventRetentionFrames","eventRetentionBytes"]);return{eventRetentionMs:l(n.eventRetentionMs,1e3,6e5),eventRetentionFrames:l(n.eventRetentionFrames,1,4096),eventRetentionBytes:l(n.eventRetentionBytes,1024,8388608)}}function M(e){let n=u(e,["historyEpoch","deletionGeneration","projectionRevision"]);T(n.historyEpoch),c(n.deletionGeneration),c(n.projectionRevision)}function ee(e){let n=u(e,["sessionId","generations","sourceSnapshotDigest"]);T(n.sessionId),M(n.generations),h(n.sourceSnapshotDigest)}function ne(e){let n=u(e,["fromSequence","throughSequence","headDigest"]),t=c(n.fromSequence),i=c(n.throughSequence);(t<1n||t>i)&&r(),h(n.headDigest)}function R(e,n,t){return(!Array.isArray(e)||e.length<n||e.length>t)&&r(),e}function te(e){let n=u(e,["artifactId","sourceId","bytes","sha256","mediaType"]);return d(n.artifactId),d(n.sourceId),l(n.bytes,1,33554432),h(n.sha256),(typeof n.mediaType!="string"||n.mediaType.length>128||!/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+/-]*$/.test(n.mediaType))&&r(),n}function re(e){u(e,["protocol","bindingId","revision","generations","sourceId","sourceGeneration","publishedThroughSequence","acknowledgedCoverage","releasableThroughSequence","pendingBytes","pendingRecords","sessionPersistence","state"]),d(e.sourceId),d(e.sourceGeneration),c(e.revision),M(e.generations),E(e.state,J),e.sessionPersistence!=="unchanged"&&r(),l(e.pendingBytes,0,67108864),l(e.pendingRecords,0,4096);let n=e.publishedThroughSequence===null?null:c(e.publishedThroughSequence),t=e.releasableThroughSequence===null?null:c(e.releasableThroughSequence);if((n===0n||t===0n)&&r(),e.acknowledgedCoverage!==null){ne(e.acknowledgedCoverage);let i=m(e.acknowledgedCoverage);(n===null||c(i.throughSequence)>n||t!==null&&t>c(i.throughSequence))&&r()}else t!==null&&r()}function ie(e){u(e,["protocol","bindingId","materialRequestId","target","sourceId","sourceGeneration","requestedRecords","purpose","maxBytes","chunkBytes"]),d(e.materialRequestId),ee(e.target),d(e.sourceId),d(e.sourceGeneration),E(e.purpose,["context-recall","projection-verification"]);let n=l(e.maxBytes,1024,1048576),t=l(e.chunkBytes,1,65536),i=new Set,o=new Map,s=0;for(let a of R(e.requestedRecords,1,32)){let g=u(a,["recordId","digest","payload","attachments"]),f=d(g.recordId);h(g.digest),i.has(f)&&r(),i.add(f);let A=R(g.attachments,0,32),y=new Set;for(let v of[g.payload,...A]){let b=te(v),k=d(b.artifactId),O=l(b.bytes,1,33554432);(b.sourceId!==e.sourceId||Math.ceil(O/t)>16||y.has(k))&&r(),y.add(k);let q=o.get(k);q&&!H(q,b)&&r(),q||(o.set(k,b),s+=O,s>n&&r())}}}function oe(e){u(e,["protocol","bindingId","materialRequestId","state","revision","acceptedRecordIds"],["reason"]),d(e.materialRequestId),c(e.revision),E(e.state,["pending","received","verified","core-consumed","rejected"]);let n=R(e.acceptedRecordIds,0,32).map(d);new Set(n).size!==n.length&&r(),e.state==="rejected"?E(e.reason,Q):Object.hasOwn(e,"reason")&&r(),e.state==="pending"&&(e.revision!=="0"||n.length)&&r()}function j(e,n){let t=m(W(p(e)));E(t.eventType,["archive.records-available","archive.status","material.request","material.status","binding.status"]);let i=["eventType","revision","generations","payload"];t.eventType==="material.request"&&i.push("issuedAtMs","deadlineMs"),u(t,i),c(t.revision),M(t.generations);let o=m(t.payload);if(t.eventType==="archive.records-available")u(o,["publishedThroughSequence"]),c(o.publishedThroughSequence)<1n&&r();else{switch((o.protocol!=="sdk2-ext-v1"||o.bindingId!==n.bindingId)&&r(),t.eventType){case"archive.status":re(o);break;case"material.request":{ie(o);let a=l(t.issuedAtMs),g=l(t.deadlineMs);(g<=a||g-a>3e4)&&r();break}case"material.status":oe(o);break;case"binding.status":{try{P(o)}catch{r()}let a=m(o.scope);(a.applicationScopeId!==n.applicationScopeId||a.endUserId!==n.endUserId)&&r();break}}(t.eventType==="binding.status"||t.eventType==="archive.status")&&o.revision!==t.revision&&r();let s=Object.hasOwn(o,"generations")?o.generations:Object.hasOwn(o,"target")?m(o.target).generations:void 0;s!==void 0&&!H(s,t.generations)&&r()}return t}function ve(e){return S("tansr.sdk2.event-scope.v1",B(e))}function se(e,n,t){return S("tansr.sdk2.event-life.v1",{eventDbId:h(e),scope:B(n),installationId:d(t)})}function me(e,n,t){return S("tansr.sdk2.event-epoch-life.v1",se(e,n,t))}function he(e,n,t){return $("sha256",_(e)).update("tansr.sdk2.event-key.v1").update("\0").update(p({storeId:n,eventDbId:t})).digest()}function I(e){return(e<0n||e>K)&&r(),e.toString(16).padStart(16,"0")}function N(e,n,t,i,o){return $("sha256",e).update("tansr.sdk2.event-cursor.v1").update("\0").update(p({...n,keyId:"k1",life:t,generation:i.toString(),sequence:o.toString()})).digest()}function ae(e,n,t,i,o){let s=_(e);return h(t),i<1n&&r(),B(n),`e1.k1.${Buffer.from(t,"hex").toString("base64url")}.${I(i)}.${I(o)}.${N(s,n,t,i,o).toString("base64url")}`}function be(e,n,t){(typeof t!="string"||t.length!==127||!/^e1\.k1\.[A-Za-z0-9_-]{43}\.[0-7][0-9a-f]{15}\.[0-7][0-9a-f]{15}\.[A-Za-z0-9_-]{43}$/.test(t))&&r("stream_cursor_unknown");let i=t.split("."),o=Buffer.from(i[2],"base64url"),s=Buffer.from(i[5],"base64url");(o.length!==32||s.length!==32||o.toString("base64url")!==i[2]||s.toString("base64url")!==i[5])&&r("stream_cursor_unknown");let a=BigInt(`0x${i[3]}`),g=BigInt(`0x${i[4]}`),f;try{f=_(e)}catch{return r("stream_cursor_unknown")}return(a<1n||!L(s,N(f,n,o.toString("hex"),a,g)))&&r("stream_cursor_unknown"),{life:o.toString("hex"),generation:a,sequence:g}}function Ee(e){let n=j(e.draft,e.scope);l(e.nowMs),e.sequence<1n&&r();let t=n.payload;if(n.eventType==="material.request"){let a=e.maximumTtl?n.deadlineMs-n.issuedAtMs:Math.min(n.deadlineMs-n.issuedAtMs,n.deadlineMs-e.nowMs);!e.maximumTtl&&e.nowMs<n.issuedAtMs&&r("unavailable"),a<1&&r("stream_cursor_expired"),t={...n.payload,remainingTtlMs:a}}let i=ae(e.key,e.scope,e.life,e.generation,e.sequence),o=p({protocol:"sdk2-ext-v1",bindingId:e.scope.bindingId,eventId:`e1.${Buffer.from(e.life,"hex").toString("base64url")}.${I(e.generation)}.${I(e.sequence)}`,cursor:i,revision:n.revision,generations:n.generations,eventType:n.eventType,payload:t}),s=Buffer.from(`id: ${i}
|
|
5
|
+
event: ${n.eventType}
|
|
6
|
+
data: ${Buffer.from(o).toString("utf8")}
|
|
7
|
+
|
|
8
|
+
`);return s.byteLength>z&&r("capacity_exceeded"),{json:o,sse:s,cursor:i}}import{types as ce}from"node:util";function xe(e,n,t,i){let o=u(i,["generation","after","drafts"]);(!Array.isArray(o.drafts)||ce.isProxy(o.drafts)||o.drafts.length<1||o.drafts.length>8||Reflect.ownKeys(o.drafts).length!==o.drafts.length+1)&&r();let s=[];for(let y=0;y<o.drafts.length;y++){let v=Object.getOwnPropertyDescriptor(o.drafts,String(y));(!v||!("value"in v)||!v.enumerable)&&r(),s.push(j(v.value,e))}let a=c(o.generation),g=c(o.after),f=s.map(p),A=S("tansr.sdk2.event-batch.v1",{scopeKey:n,life:t,generation:String(a),after:String(g),drafts:f.map(G)});return{generation:a,after:g,drafts:s,bodies:f,digest:A}}function Ie(e){let n=e.map(i=>i.eventType);(n.filter(i=>i==="archive.status").length!==1||n.filter(i=>i==="binding.status").length!==1||n.some(i=>!["archive.status","binding.status","material.request"].includes(i))||n.filter(i=>i==="material.request").length>2)&&r();let t=e.flatMap(i=>i.eventType==="material.request"?[i.payload.materialRequestId]:[]);new Set(t).size!==t.length&&r()}function Ae(e,n){(e.rows>8192*n||e.wire>16*1048576*n||e.stored>24*1048576*n)&&r("capacity_exceeded")}export{w as a,K as b,r as c,_ as d,u as e,l as f,d as g,c as h,p as i,W as j,G as k,S as l,B as m,ye as n,j as o,ve as p,se as q,me as r,he as s,ae as t,be as u,Ee as v,xe as w,Ie as x,Ae as y};
|
|
9
|
+
//# sourceMappingURL=tansr-chunk-4YAEV3T6.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
+
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
+
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
+
import{j as w}from"./tansr-chunk-AHUB2IHT.mjs";import{spawn as O}from"node:child_process";var f="tansr-cli",p=class extends Error{constructor(e){super(e),this.name="SecretStoreUnavailableError"}},S=15e3;function v(){return(t,e,r,i)=>new Promise(s=>{let n=O(t,[...e],{windowsHide:!0,stdio:["pipe","pipe","pipe"]}),o="",a="",c=!1,l=d=>{c||(c=!0,clearTimeout(y),s({code:d,stdout:o,stderr:a}))},y=setTimeout(()=>{n.kill(),l(null)},i);n.stdout?.on("data",d=>{o+=d.toString()}),n.stderr?.on("data",d=>{a+=d.toString()}),n.on("error",()=>l(null)),n.on("close",d=>l(d)),n.stdin?.on("error",()=>{}),n.stdin?.end(r)})}function h(t){return t.replace(/\r?\n$/,"")}function m(t){return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function I(t={}){let e=t.runner??v(),r=t.timeoutMs??S;return{kind:"keychain",async store(i,s){let n=["add-generic-password","-U","-a",m(i),"-s",m(f),"-w",m(s)].join(" "),o=await e("security",["-i"],n+`
|
|
5
|
+
`,r);if(o.code!==0)throw new p(o.code===null?"security_unavailable":`security_exit_${o.code}`)},async lookup(i){let s=await e("security",["find-generic-password","-a",i,"-s",f,"-w"],"",r);if(s.code===null)throw new p("security_unavailable");if(s.code===44)return null;if(s.code!==0)throw new p(`security_exit_${s.code}`);let n=h(s.stdout);return n===""?null:n},async remove(i){await e("security",["delete-generic-password","-a",i,"-s",f],"",r)}}}function E(t={}){let e=t.runner??v(),r=t.timeoutMs??S,i=s=>["service",f,"account",s];return{kind:"secret-service",async store(s,n){let o=await e("secret-tool",["store",`--label=${f}`,...i(s)],n,r);if(o.code!==0)throw new p(o.code===null?"secret_tool_unavailable":`secret_tool_exit_${o.code}`)},async lookup(s){let n=await e("secret-tool",["lookup",...i(s)],"",r);if(n.code===null)throw new p("secret_tool_unavailable");if(n.code===1&&n.stdout==="")return null;if(n.code!==0)throw new p(`secret_tool_exit_${n.code}`);let o=h(n.stdout);return o===""?null:o},async remove(s){await e("secret-tool",["clear",...i(s)],"",r)}}}function Y(t,e={}){return t==="darwin"?I(e):t==="linux"?E(e):null}import{randomBytes as V}from"node:crypto";import{readFile as g,rm as D}from"node:fs/promises";import A from"node:os";import x from"node:path";import{randomBytes as T}from"node:crypto";import*as u from"node:fs/promises";import U from"node:path";var C={open:(t,e,r)=>u.open(t,e,r),rename:(t,e)=>u.rename(t,e),rm:(t,e)=>u.rm(t,e),mkdir:(t,e)=>u.mkdir(t,e),chmod:(t,e)=>u.chmod(t,e)};async function B(t,e,r={}){let s=await(r.fs??C).open(t,"w",r.mode);try{await s.writeFile(e),await s.sync()}finally{await s.close()}}function N(t){return`${t}.tmp-${process.pid}-${T(4).toString("hex")}`}async function P(t,e,r={}){let i=r.fs??C,s=U.dirname(t);await i.mkdir(s,{recursive:!0});let n=N(t);try{await B(n,e,{fs:i,...r.mode!==void 0?{mode:r.mode}:{}}),await i.rename(n,t)}catch(o){throw await i.rm(n,{force:!0}).catch(()=>{}),o}r.mode!==void 0&&process.platform!=="win32"&&await i.chmod(t,r.mode).catch(()=>{}),await L(i,s)}async function L(t,e){if(process.platform==="win32")return;let r=null;try{r=await t.open(e,"r"),await r.sync()}catch{}finally{await r?.close().catch(()=>{})}}var M="credentials.json",K=384,k=0;function de(){return k}function j(t,e=A.homedir()){let r=t.TANSR_CONFIG_DIR?.trim(),i=r!==void 0&&r!==""?r:x.join(e,".tansr");return x.join(i,M)}function pe(t,e=A.homedir()){return w(t,e)?.credentialsFile??j(t,e)}async function R(t,e,r){await P(t,JSON.stringify(e,null,2)+`
|
|
6
|
+
`,{mode:K,...r!==void 0?{fs:r}:{}}),k+=1}async function ue(t,e,r={}){let i=r.platform??process.platform,s=r.now??Date.now,n=null,o=!1,a=e.key;if(r.secretStore!==void 0&&r.secretStore!==null)try{await r.secretStore.store(e.keyId,e.key),n=r.secretStore.kind,a=""}catch{}if(n===null&&i==="win32"&&r.cipher!==void 0)try{a=await r.cipher.protect(e.key),o=!0,n="dpapi"}catch{a=e.key}n===null&&(n="plain-file");let c={version:2,encrypted:o,protection:n,apiBaseUrl:e.apiBaseUrl,keyId:e.keyId,key:a,app:e.app,savedAt:new Date(s()).toISOString()};return await R(t,c,r.fs),{encrypted:o,protection:n}}function b(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function $(){return`pat-${V(12).toString("hex")}`}async function J(t){try{let e=JSON.parse(await g(t,"utf8"));if(b(e)&&e.version===3&&typeof e.patRef=="string"&&e.patRef!=="")return e.patRef}catch{}return null}async function fe(t,e,r={}){let i=r.platform??process.platform,s=r.now??Date.now,n=await J(t)??$(),o=null,a=!1,c=e.pat,l=e.derivedApp?.key??null;if(r.secretStore!==void 0&&r.secretStore!==null)try{let d={pat:e.pat,derivedAppKey:l};await r.secretStore.store(n,JSON.stringify(d)),o=r.secretStore.kind,c="",l!==null&&(l="")}catch{}if(o===null&&i==="win32"&&r.cipher!==void 0)try{let d=await r.cipher.protect(e.pat),F=l!==null?await r.cipher.protect(l):null;c=d,l=F,a=!0,o="dpapi"}catch{c=e.pat,l=e.derivedApp?.key??null}o===null&&(o="plain-file");let y={version:3,encrypted:a,protection:o,apiBaseUrl:e.apiBaseUrl,patRef:n,pat:c,...e.derivedApp!==null?{derivedApp:{keyId:e.derivedApp.keyId,key:l??""}}:{},savedAt:new Date(s()).toISOString()};return await R(t,y,r.fs),{encrypted:a,protection:o}}var _=["keychain","secret-service","dpapi","plain-file"];function H(t){if(typeof t!="object"||t===null)return!1;let e=t,r=e.protection,i=r==="keychain"||r==="secret-service";return e.version===2&&typeof e.encrypted=="boolean"&&(r===void 0||typeof r=="string"&&_.includes(r))&&typeof e.apiBaseUrl=="string"&&typeof e.keyId=="string"&&e.keyId!==""&&typeof e.key=="string"&&(i||e.key!=="")&&typeof e.app=="object"&&e.app!==null&&typeof e.app.id=="string"&&typeof e.app.name=="string"&&typeof e.app.ownerType=="string"}function W(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.version===1&&typeof e.accessToken=="string"&&typeof e.refreshToken=="string"}function G(t){if(typeof t!="object"||t===null)return!1;let e=t,r=e.protection,i=r==="keychain"||r==="secret-service",s=e.derivedApp===void 0;if(!s&&typeof e.derivedApp=="object"&&e.derivedApp!==null){let n=e.derivedApp;s=typeof n.keyId=="string"&&n.keyId!==""&&typeof n.key=="string"&&(i||n.key!=="")}return e.version===3&&typeof e.encrypted=="boolean"&&(r===void 0||typeof r=="string"&&_.includes(r))&&typeof e.apiBaseUrl=="string"&&typeof e.patRef=="string"&&e.patRef!==""&&typeof e.pat=="string"&&(i||e.pat!=="")&&s}async function q(t,e){let r=t.protection??(t.encrypted?"dpapi":"plain-file"),i=t.pat,s=t.derivedApp?.key??null;if(r==="keychain"||r==="secret-service"){let n=e.secretStore;if(n==null)return{status:"corrupt",reason:"keystore_unavailable"};let o;try{o=await n.lookup(t.patRef)}catch(c){return{status:"corrupt",reason:c instanceof p?"keystore_unavailable":"keystore_failed"}}if(o===null)return{status:"corrupt",reason:"keystore_missing"};let a;try{a=JSON.parse(o)}catch{return{status:"corrupt",reason:"keystore_corrupt"}}if(!b(a)||typeof a.pat!="string"||a.pat==="")return{status:"corrupt",reason:"keystore_corrupt"};if(i=a.pat,t.derivedApp!==void 0){let c=a.derivedAppKey;if(typeof c!="string"||c==="")return{status:"corrupt",reason:"keystore_corrupt"};s=c}}else if(t.encrypted){let n=e.cipher;if(n===void 0)return{status:"corrupt",reason:"cipher_unavailable"};try{if(t.derivedApp!==void 0){let o=[t.pat,t.derivedApp.key],a=n.unprotectMany!==void 0?await n.unprotectMany(o):[await n.unprotect(o[0]),await n.unprotect(o[1])];if(a.length!==2)throw new Error("unprotectMany: count mismatch");i=a[0],s=a[1]}else i=await n.unprotect(t.pat)}catch{return{status:"corrupt",reason:"decrypt_failed"}}}return{status:"ok",version:3,protection:r,credentials:{apiBaseUrl:t.apiBaseUrl,pat:i,derivedApp:t.derivedApp!==void 0?{keyId:t.derivedApp.keyId,key:s??""}:null}}}async function z(t,e={}){let r;try{r=await g(t,"utf8")}catch(o){return o.code==="ENOENT"?{status:"missing"}:{status:"corrupt",reason:"read_failed"}}let i;try{i=JSON.parse(r)}catch{return{status:"corrupt",reason:"parse_failed"}}if(W(i))return{status:"legacy"};if(G(i))return q(i,e);if(!H(i))return{status:"corrupt",reason:"shape_invalid"};let s=i.protection??(i.encrypted?"dpapi":"plain-file"),n=i.key;if(s==="keychain"||s==="secret-service"){let o=e.secretStore;if(o==null)return{status:"corrupt",reason:"keystore_unavailable"};try{let a=await o.lookup(i.keyId);if(a===null)return{status:"corrupt",reason:"keystore_missing"};n=a}catch(a){return{status:"corrupt",reason:a instanceof p?"keystore_unavailable":"keystore_failed"}}}else if(i.encrypted){if(e.cipher===void 0)return{status:"corrupt",reason:"cipher_unavailable"};try{n=await e.cipher.unprotect(i.key)}catch{return{status:"corrupt",reason:"decrypt_failed"}}}return{status:"ok",version:2,protection:s,credentials:{apiBaseUrl:i.apiBaseUrl,keyId:i.keyId,key:n,app:{id:i.app.id,name:i.app.name,ownerType:i.app.ownerType}}}}async function ye(t,e={}){return Q(await z(t,e))}function Q(t){if(t.status!=="ok")return t;if(t.version===2)return{status:"ok",credentials:t.credentials,protection:t.protection};let e=t.credentials.derivedApp;return e===null?{status:"missing"}:{status:"ok",protection:t.protection,credentials:{apiBaseUrl:t.credentials.apiBaseUrl,keyId:e.keyId,key:e.key,app:{id:e.keyId,name:"",ownerType:""}}}}async function me(t,e={}){if(e.secretStore!==void 0&&e.secretStore!==null)try{let r=JSON.parse(await g(t,"utf8"));if(r.protection==="keychain"||r.protection==="secret-service"){let i=r.version===3?typeof r.patRef=="string"?r.patRef:"":typeof r.keyId=="string"?r.keyId:"";i!==""&&await e.secretStore.remove(i)}}catch{}try{return await D(t),k+=1,!0}catch(r){if(r.code==="ENOENT")return!1;throw r}}export{C as a,B as b,P as c,Y as d,de as e,j as f,pe as g,ue as h,fe as i,z as j,ye as k,Q as l,me as m};
|
|
7
|
+
//# sourceMappingURL=tansr-chunk-546BDI3V.mjs.map
|