openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
4 lines • 348 kB
JavaScript
import{A as e,Ct as t,Ft as n,Mt as r,Q as i,Tt as a,Vt as o,Z as s,a as c,at as l,bt as u,i as d,it as f,k as p,q as m,rt as h,t as g,u as _}from"./sqlite-readonly-subsystem-C-VJT-xk.mjs";import{t as v}from"./sqlite-readonly-deferred-B75K7ut7.mjs";import{$ as y,$t as b,A as x,At as S,B as C,Bt as w,C as ee,Ct as T,Dt as E,E as te,Et as ne,F as re,Ft as ie,G as ae,Ht as D,It as oe,Jt as se,K as ce,Kt as O,L as le,M as ue,N as de,Nt as fe,O as pe,Ot as k,Pt as me,Q as A,Qt as he,R as ge,S as _e,St as ve,T as ye,Tt as j,U as M,Ut as be,V as xe,Vt as Se,W as N,Wt as Ce,X as we,Xt as Te,Y as Ee,Yt as P,Z as De,Zt as Oe,_ as ke,_t as Ae,an as je,at as F,b as Me,bt as Ne,cn as I,ct as Pe,d as L,dn as Fe,dt as Ie,en as Le,et as Re,f as ze,fn as Be,ft as Ve,g as He,gt as Ue,h as We,ht as R,in as z,it as Ge,jt as Ke,k as qe,kt as Je,ln as Ye,lt as B,m as Xe,mn as Ze,mt as Qe,nn as V,nt as $e,on as et,ot as tt,p as nt,pn as H,pt as U,qt as rt,rn as it,rt as W,sn as at,st as ot,tn as st,tt as ct,u as lt,un as ut,ut as dt,v as ft,vt as pt,w as mt,wt as ht,x as gt,xt as G,y as _t,yt as vt}from"./sqlite-readonly-runtime-process-manifest-CLhsN5hb.mjs";import{A as yt,B as bt,C as xt,D as St,E as Ct,F as wt,G as Tt,H as Et,K as Dt,L as Ot,M as kt,N as At,O as K,R as jt,S as Mt,T as Nt,U as Pt,V as Ft,W as q,_ as It,a as Lt,b as Rt,c as zt,d as Bt,f as Vt,g as Ht,h as Ut,i as Wt,j as Gt,k as Kt,l as qt,m as Jt,o as Yt,p as Xt,q as Zt,r as Qt,s as $t,t as en,u as tn,v as nn,w as rn,x as an,y as on,z as sn}from"./sqlite-readonly-lock-config-dZbF0Wy8.mjs";import{A as cn,C as ln,D as un,E as dn,M as fn,N as pn,O as mn,P as hn,S as gn,T as _n,_ as vn,b as yn,d as bn,f as xn,g as Sn,h as Cn,j as wn,k as Tn,m as En,p as Dn,v as On,w as kn,x as An,y as jn}from"./sqlite-readonly-sqlite-wal-CjNCU3qS.mjs";import{v as Mn}from"./sqlite-readonly-sqlite-user-version-DDTE9T44.mjs";import{t as Nn}from"./sqlite-readonly-absolute-path-Cb1z8Zgx.mjs";import{Dn as Pn,Dt as Fn,G as In,Jn as Ln,Nt as Rn,On as zn,Pt as Bn,Tn as Vn,Wn as Hn,Wt as Un,Xn as Wn,Xt as Gn,_n as Kn,a as qn,b as Jn,c as Yn,g as Xn,i as Zn,kt as Qn,sn as $n,t as er,tt as tr}from"./sqlite-readonly-node-sqlite-u3RAlsBE.mjs";import{C as nr,E as rr,N as ir,P as ar,S as or,T as sr,U as cr,V as lr,X as ur,_ as dr,a as fr,c as pr,d as mr,g as hr,l as gr,m as _r,n as vr,ot as yr,p as br,s as xr,t as Sr,w as Cr,x as wr}from"./sqlite-readonly-sqlite-snapshot-capacity-error-Dx-DuFsZ.mjs";import{a as Tr,d as Er,h as Dr,m as J,n as Or,p as Y,s as X,t as kr,u as Ar}from"./sqlite-readonly-schemas-3bx9g-nF.mjs";import{i as jr,r as Mr,t as Nr}from"./sqlite-readonly-pid-alive-5mZxf9nb.mjs";import{_ as Pr,f as Fr,g as Ir,h as Lr,m as Rr,n as zr,p as Br,u as Vr}from"./sqlite-readonly-worker-cpu-COshMrit.mjs";import{a as Hr,i as Ur,o as Wr}from"./sqlite-readonly-cli-invocation-xwXCxqwu.mjs";import{a as Gr}from"./sqlite-readonly-openclaw-root-PLr-9gty.mjs";import{n as Kr}from"./sqlite-readonly-runtime-worker-url-D7L1HCPF.mjs";import{o as qr,t as Jr}from"./sqlite-readonly-gateway-process-argv-Nc_b8yJG.mjs";import{d as Yr,i as Xr,l as Zr,n as Qr,o as $r,r as ei,u as ti}from"./sqlite-readonly-sqlite-schema-sql-BnVx4b5A.mjs";import{t as ni}from"./sqlite-readonly-errors-bSzGfuz-.mjs";import"./sqlite-readonly-sqlite-transaction-CZJn2Fa5.mjs";import Z from"node:path";import{scheduler as ri,setImmediate as ii}from"node:timers/promises";import{hash as ai,randomUUID as oi}from"node:crypto";import Q,{chmodSync as si,constants as ci,readSync as li,statSync as ui,unlinkSync as di,writeFileSync as fi}from"node:fs";import $ from"node:fs/promises";import pi from"node:os";import{fileURLToPath as mi}from"node:url";import{MessageChannel as hi,isMainThread as gi}from"node:worker_threads";import{promisify as _i,types as vi}from"node:util";import{AsyncLocalStorage as yi}from"node:async_hooks";import{execFile as bi,spawn as xi,spawnSync as Si}from"node:child_process";import{isUtf8 as Ci}from"node:buffer";function admitUncachedCopyPath(e,t=!1,n){if(!Z.isAbsolute(e.rootPath)||!Z.isAbsolute(e.absolutePath))throw new I(`invalid-path`,`copy roots and paths must be absolute`);let r=n??Ge(O.native(e.rootPath),`native`,{bigint:!0}),i=n?.realPath,resolve=()=>{let n=t?gt({...e,rootCanonicalPath:i,absolutePath:Z.dirname(e.absolutePath),boundaryLabel:`copy parent`,rejectSymlinks:!0,rejectFinalSymlink:!0}):void 0,r=gt({...e,rootCanonicalPath:i,boundaryLabel:`copy`,rejectSymlinks:!t,rejectFinalSymlink:!t,policy:t?ft.unlinkTarget:void 0});if(n&&Z.dirname(r.canonicalPath)!==n.canonicalPath)throw new I(`path-mismatch`,`copy destination parent changed`);return r},a=resolve(),o=Ge(Z.dirname(a.canonicalPath),`native`,{bigint:!0}),assertCurrent=()=>{W(r),W(o);let e=resolve();if(e.rootCanonicalPath!==r.realPath||e.canonicalPath!==a.canonicalPath)throw new I(`path-mismatch`,`copy path changed during operation`);W(r),W(o)};return assertCurrent(),{path:a.canonicalPath,parent:o,assertCurrent,rootCanonicalPath:void 0}}function createCopyPathAdmissionCache(){let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,assertParent=({root:e,parent:t,chain:n})=>{W(e);for(let e of n)e!==t&&B(e.dir,{dev:BigInt(e.stat.dev),ino:BigInt(e.stat.ino)});t!==e&&W(t),W(e)};return{admit:(r,i=!1)=>{if(process.platform===`win32`&&(!/^[a-z]:\\/iu.test(r.rootPath)||Se(r.rootPath,`filesystem`)||Se(r.absolutePath,`filesystem`)||r.absolutePath.slice(3).split(`\\`).some(e=>/[. ]$/u.test(e)||e.includes(`~`)))||!Z.isAbsolute(r.rootPath)||!Z.isAbsolute(r.absolutePath)||r.rootPath.includes(`\0`)||r.absolutePath.includes(`\0`)||Z.resolve(r.rootPath)!==r.rootPath||Z.resolve(r.absolutePath)!==r.absolutePath||!r.absolutePath.startsWith(r.rootPath.endsWith(Z.sep)?r.rootPath:`${r.rootPath}${Z.sep}`))return admitUncachedCopyPath(r,i);let a=e.get(r.rootPath);if(!a){let t=O.native(r.rootPath);if(t!==r.rootPath)return admitUncachedCopyPath(r,i);a=Ge(t,`native`,{bigint:!0}),e.set(r.rootPath,a)}W(a);let o=Z.dirname(r.absolutePath),s=t.get(r.rootPath),c=s?.get(o);if(!c){let e=admitUncachedCopyPath(r,i,a),l=[],u=r.rootPath,d=Z.relative(r.rootPath,o);for(let e of d?d.split(Z.sep):[]){u=Z.join(u,e);let t=n.get(u);t||(t=Ge(u,`native`,{bigint:!0}),n.set(u,t)),l.push(t)}if(c={root:a,parent:l.at(-1)??a,chain:l},assertParent(c),e.path!==r.absolutePath||e.parent.realPath!==o||!Be(e.parent.stat,c.parent.stat))throw new I(`path-mismatch`,`copy path changed during admission`);s??=/* @__PURE__ */ new Map,s.set(o,c),t.set(r.rootPath,s)}let l=c,assertCurrent=()=>{if(assertParent(l),!i&&Q.lstatSync(r.absolutePath,{throwIfNoEntry:!1})?.isSymbolicLink())throw admitUncachedCopyPath(r,i),new I(`symlink`,`symlink not allowed`)};return assertCurrent(),{path:r.absolutePath,parent:l.parent,assertCurrent,rootCanonicalPath:l.root.realPath}},clear(){e.clear(),t.clear(),n.clear()}}}function resolveCopyCloneMode(e,t){let n=e===void 0?t:e;if(n!==`auto`&&n!==`always`&&n!==`never`)throw new I(`invalid-path`,`copy clone policy must be auto, always, or never`);return n}function ownFileDescriptorSync(e,t=Q.closeSync){let n=!0,r={fd:e,close(){n&&(n=!1,t(e))},[Symbol.dispose](){r.close()}};return Object.freeze(r)}function nativeGuidance(e,t){switch(e){case`disabled`:return`If native loading is intended, ${t===`programmatic configuration`?`call configureFsSafeNative({ mode: "auto" }) or configureFsSafeNative({ mode: "require" })`:`set ${t}=auto or ${t}=require`}; keep intentional off settings.`;case`unsupported-target`:return`Portable mode is expected on this target.`;case`package-missing`:return`Reinstall with optional dependencies included: npm --include=optional, or pnpm without --no-optional / optional=false. Check the lockfile and registry mirror.`;case`load-failed`:return`Check Node architecture, Linux libc compatibility, package dependencies, and OS code-integrity policy. Reinstalling identical bytes may not help.`;case`capability-missing`:return`Use matching fs-safe and platform-package versions; some targets intentionally provide only a subset of capabilities.`;default:return}}const wi=/* @__PURE__ */ new Set;function fallbackReason(e){let t=Te(...e),n=t.packageName===void 0?`No native package is published for ${t.target}.`:`Expected ${t.packageName}@${t.packageVersion}.`,r=nativeGuidance(t.reason,Le().source);switch(t.reason){case`disabled`:return`native support is disabled by ${t.source} (disabled). ${n} ${r}`;case`unsupported-target`:return`the target ${t.target} is unsupported (unsupported-target). ${n} ${r}`;case`package-missing`:return`the selected native package could not be resolved (package-missing). ${n} ${r}`;case`load-failed`:return`the native package could not be loaded (load-failed: ${t.code}). ${n} ${r}`;case`capability-missing`:return`the native package lacks requested functions (capability-missing: ${t.capabilities.join(`, `)}). ${n} ${r}`;default:return`the requested native operation is unavailable (${t.reason}). ${n}`}}function warnNativeFallback(e,t,...n){wi.has(e)||(wi.add(e),process.emitWarning(`${e} is using its portable fallback because ${fallbackReason(n)} ${t}`,{code:`FS_SAFE_NATIVE_FALLBACK`,type:`FsSafeWarning`}))}function windowsSecurityHelperPath(){return mi(new URL(`./windows-security-helper.exe`,new URL(`dist/windows-security-helper.js`,import.meta.resolve(`@openclaw/fs-safe/package.json`)).href))}function explainWindowsSecurityHelperFailure(e){e.message+=`; Windows security helper could not complete; rebuild with pnpm build:windows-helper or reinstall @openclaw/fs-safe`}_i(bi);const Ti=3e4;function formatPermissionErrorDetail(e){let t=ae(e.slice(0,401));return t.length>400?`${t.slice(0,399)}…`:t}const Ei=vi.isUint8Array,Di=Uint8Array,Oi=Object.getPrototypeOf(Di.prototype),ki=Object.getOwnPropertyDescriptor(Oi,`buffer`).get,Ai=Object.getOwnPropertyDescriptor(Oi,`byteOffset`).get,ji=Object.getOwnPropertyDescriptor(Oi,`byteLength`).get,Mi=Object.getOwnPropertyDescriptor(Oi,`set`).value,Ni=TextDecoder.prototype.decode,Pi=new TextDecoder(`utf-8`,{fatal:!1,ignoreBOM:!0}),Fi=1600;function isInspectableCaughtObject(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return!1;try{return!vi.isProxy(e)}catch{return!1}}function dataProperty(e,t){let n=e;for(let e=0;n!==null&&e<4;e+=1){if(!isInspectableCaughtObject(n))return;let e;try{e=Object.getOwnPropertyDescriptor(n,t)}catch{return}if(e)return Object.hasOwn(e,`value`)?e:void 0;try{n=Object.getPrototypeOf(n)}catch{return}}}function formatBoundedCaughtDetail(e,t=!1){let n=t||e.length>400,r=formatPermissionErrorDetail(e.slice(0,400));return!n||r.endsWith(`…`)?r:`${r.slice(0,399)}…`}function safeStderr(e){if(typeof e==`string`)return formatBoundedCaughtDetail(e);try{if(!Ei(e))return``;let t=Reflect.apply(ki,e,[]),n=Reflect.apply(Ai,e,[]),r=Reflect.apply(ji,e,[]),i=r<Fi?r:Fi,a=new Di(t,n,i),o=new Di(i);return Reflect.apply(Mi,o,[a,0]),formatBoundedCaughtDetail(Reflect.apply(Ni,Pi,[o]),r>i)}catch{return``}}function commandFailureFields(e){let t=dataProperty(e,`killed`),n=dataProperty(e,`code`),r=dataProperty(e,`signal`),i=dataProperty(e,`stderr`);return{found:!!(t||n||r||i),timedOut:t?.value===!0&&r?.value===`SIGKILL`,exitCode:typeof n?.value==`number`?n.value:null,signal:typeof r?.value==`string`?r.value:null,stderr:i?safeStderr(i.value):``}}var PermissionCommandError=class extends Error{command;durationMs;timedOut;exitCode;signal;stderr;constructor(e,t,n,r=Ti){let i=commandFailureFields(n);super(i.timedOut?`Windows permission inspection timed out after ${r}ms`:`Windows permission command ${formatPermissionErrorDetail(Z.win32.basename(e))} failed (exit code ${i.exitCode}, signal ${formatPermissionErrorDetail(i.signal??`none`)})`,{cause:n}),this.name=`PermissionCommandError`,this.command=e,this.durationMs=Math.round(t),this.timedOut=i.timedOut,this.exitCode=i.exitCode,this.signal=i.signal,this.stderr=i.stderr}};function unverified(e,t){throw new I(`permission-unverified`,e,t===void 0?{}:{cause:t})}const Ii=1048576,Li=/^[0-9a-f]{16}:[0-9a-f]{32}$/;function isFullIdentity(e){return typeof e==`string`&&e.length===49&&Li.test(e)}function assertIdentity(e){if(!isFullIdentity(e))throw TypeError(`Windows security operation requires a complete file identity`)}function command(e,t){let n=t.targetPath??``;if(n.includes(`\0`))throw Object.assign(/* @__PURE__ */ Error(`Windows path contains a NUL byte`),{code:`EINVAL`});if((t.fd!==void 0||e===`descriptor`||e===`protect-file`||e===`verify-file`)&&(typeof t.fd!=`number`||!Number.isInteger(t.fd)||t.fd<0||t.fd>2147483647)&&unverified(`Windows security inspection requires a valid descriptor`),t.expectedParentIdentity!==void 0&&assertIdentity(t.expectedParentIdentity),t.expectedFileIdentity!==void 0&&assertIdentity(t.expectedFileIdentity),t.expectedLinks!==void 0&&(!Number.isInteger(t.expectedLinks)||t.expectedLinks<1||t.expectedLinks>4294967295))throw TypeError(`Windows security operation requires a positive uint32 link count`);return{file:windowsSecurityHelperPath(),args:[e],env:{...process.env,FS_SAFE_WINDOWS_SECURITY_PATH:n,FS_SAFE_WINDOWS_SECURITY_REQUIRE_PRIVATE:t.requirePrivate?`1`:`0`,FS_SAFE_WINDOWS_SECURITY_PARENT_IDENTITY:t.expectedParentIdentity??``,FS_SAFE_WINDOWS_SECURITY_FILE_IDENTITY:t.expectedFileIdentity??``,FS_SAFE_WINDOWS_SECURITY_EXPECTED_LINKS:String(t.expectedLinks??1)}}}function record(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function parseReply(e,t){try{return parseReplyValue(e,t)}catch(e){throw t===`create`&&e instanceof Error&&e.code!==`EEXIST`&&Object.assign(e,{creationOutcome:`unconfirmed`}),e}}function parseReplyValue(e,t){let n;try{n=JSON.parse(e.trim())}catch(e){unverified(`Windows security command returned invalid data`,e)}if((!record(n)||typeof n.ok!=`boolean`)&&unverified(`Windows security command returned an incomplete response`),!n.ok){if(t===`paths`&&(n.code===`helper-unavailable`||n.code===`too-large`)&&typeof n.message==`string`)throw new I(n.code,n.message);let e=/* @__PURE__ */ new Set([`EACCES`,`EPERM`,`EEXIST`,`ENOENT`,`ENOTSUP`,`EIO`,`EBADF`,`ELOOP`,`ENOTDIR`,`EINVAL`,`ENOSPC`,`EBUSY`]);(typeof n.code!=`string`||!e.has(n.code)||typeof n.message!=`string`)&&unverified(`Windows security command returned an invalid failure`),n.errno!==void 0&&(typeof n.errno!=`number`||!Number.isInteger(n.errno)||n.errno<0||n.errno>4294967295)&&unverified(`Windows security command returned an invalid native error number`);let r=Object.assign(Error(n.message),{code:n.code});throw n.errno!==void 0&&Object.defineProperty(r,"errno",{value:n.errno,enumerable:!0,configurable:!0,writable:!0}),r}return t===`create`&&(!record(n.result)||n.result.created!==!0||!isFullIdentity(n.result.identity))&&unverified(`Windows security command did not verify private-directory creation`),n.result}function explainHelperFailure(e,t){t.endsWith(`windows-security-helper.exe`)&&explainWindowsSecurityHelperFailure(e)}function executeSync(e,t){rt();let{file:n,args:r,env:i}=command(e,t),a=performance.now(),o=Si(n,r,{encoding:`utf8`,windowsHide:!0,env:i,stdio:[t.fd??`ignore`,`pipe`,`pipe`],timeout:Ti,killSignal:`SIGKILL`,maxBuffer:Ii});if(o.error||o.status!==0){let t=new PermissionCommandError(n,performance.now()-a,{cause:o.error,code:o.status,signal:o.error?.code===`ETIMEDOUT`?`SIGKILL`:o.signal,stderr:o.stderr,killed:o.error?.code===`ETIMEDOUT`,...e===`create`?{creationOutcome:`unconfirmed`}:{}});throw explainHelperFailure(t,n),e===`create`&&Object.assign(t,{creationOutcome:`unconfirmed`}),t}return parseReply(o.stdout,e)}var WindowsSecurityCommandError=class extends PermissionCommandError{timedOut;creationOutcome;processExitConfirmed;constructor(e,t,n,r,i=Ti){super(e,t,n,i),this.timedOut=r,r||explainHelperFailure(this,e),this.creationOutcome=n.creationOutcome,this.processExitConfirmed=n.processExitConfirmed,r&&(this.message=`Windows permission inspection timed out after ${i}ms`),n.processExitConfirmed?n.outputClosed||(this.message+=`; command output did not close`):this.message+=`; process exit was not confirmed`,n.creationOutcome&&(this.message+=`; private-directory creation outcome is unconfirmed`)}};function hasUnsettledWindowsSecurityCommand(e){let t=[e],n=/* @__PURE__ */ new Set;for(let e=0;t.length&&e<32;e++){let e=t.pop();if(typeof e==`object`&&e&&!n.has(e)){n.add(e);try{if(e instanceof WindowsSecurityCommandError&&!e.processExitConfirmed)return!0;let n=Object.getOwnPropertyDescriptor(e,`cause`);if(n&&`value`in n&&t.push(n.value),e instanceof AggregateError){let n=Object.getOwnPropertyDescriptor(e,`errors`);n&&`value`in n&&Array.isArray(n.value)&&t.push(...n.value.slice(0,32))}}catch{return!0}}}return t.length>0}function ignoreLateError(){}async function execute(e,t,n){rt();let{file:r,args:i,env:a,input:o,timeoutMs:s=Ti,maxOutputBytes:c=Ii}=n??command(e,t),l=performance.now();return await new Promise((n,u)=>{let d=xi(r,i,{windowsHide:!0,env:a,stdio:[o===void 0?t.fd??`ignore`:`pipe`,`pipe`,`pipe`]}),f=[],p=[],m=0,h,g=!1,_=!1,v=!1,y=!1,b=!1,x=null,S=null,C,w,ee,T,deadlineError=()=>/* @__PURE__ */ Error(`Windows security command exceeded its inspection deadline`),E=setTimeout(()=>{_=!0,fail(deadlineError())},s),finish=t=>{if(y)return;y=!0,clearTimeout(E),clearTimeout(ee),clearImmediate(T),d.removeListener(`exit`,onExit),d.removeListener(`close`,onClose),d.removeListener(`error`,onChildError),d.on(`error`,ignoreLateError);let i=[];if(o!==void 0&&d.stdin&&(d.stdin.removeListener(`error`,fail),d.stdin.on(`error`,ignoreLateError),!t))try{d.stdin.destroy()}catch(e){i.push(e)}for(let[e,n]of[[d.stdout,te],[d.stderr,ne]])if(e&&(e.removeListener(`data`,n),e.removeListener(`error`,fail),e.on(`error`,ignoreLateError),!t))try{e.destroy()}catch(e){i.push(e)}if(!t&&!b)try{d.unref()}catch(e){i.push(e)}if(g||x!==0||!t)u(new WindowsSecurityCommandError(r,performance.now()-l,{cause:h,pid:d.pid??null,code:x,signal:S,stderr:Buffer.concat(p),processExitConfirmed:b,outputClosed:t,terminationSignalSent:C,terminationError:w,cleanupErrors:i,...e===`create`?{creationOutcome:`unconfirmed`}:{}},_,s));else try{n(parseReply(Buffer.concat(f).toString(`utf8`),e))}catch(e){u(e)}f.length=0,p.length=0},fail=e=>{if(!y&&(g||(g=!0,h=e),!v&&(v=!0,clearTimeout(E),ee=setTimeout(()=>finish(!1),1e3),!b)))try{C=d.kill(`SIGKILL`)}catch(e){w??=e}},collect=e=>t=>{g||y||(m+=t.length,m<=c?e.push(t):fail(/* @__PURE__ */ Error(`Windows security command exceeded its output budget`)))},te=collect(f),ne=collect(p),onChildError=e=>{y||(v?w??=e:fail(e))},onExit=(e,t)=>{b=!0,x=e,S=t},onClose=(e,t)=>{onExit(e,t),!g&&performance.now()-l>=s&&(_=!0,g=!0,h=deadlineError()),finish(!0)};if(d.on(`error`,onChildError),d.once(`exit`,onExit),d.once(`close`,onClose),d.stdout?.on(`error`,fail),d.stderr?.on(`error`,fail),d.stdout?.on(`data`,te),d.stderr?.on(`data`,ne),(!d.stdout||!d.stderr||o!==void 0&&!d.stdin)&&(T=setImmediate(()=>{!g&&!y&&fail(/* @__PURE__ */ Error(`Windows security command output pipes are unavailable`))})),o!==void 0&&d.stdin){d.stdin.on(`error`,fail);try{d.stdin.end(o,`utf8`)}catch(e){fail(e)}}})}async function createPrivateWindowsDirectoryCommand(e,t){return fullIdentityReceipt(await execute(`create`,{targetPath:e,expectedParentIdentity:t}))}function createPrivateWindowsDirectoryCommandSync(e,t){return fullIdentityReceipt(executeSync(`create`,{targetPath:e,expectedParentIdentity:t}))}function fullIdentityReceipt(e,t){if((!record(e)||!isFullIdentity(e.identity))&&unverified(`Windows security command returned an incomplete file identity`),t!==void 0&&e.identity!==t)throw new I(`path-mismatch`,`Windows security command observed a different file`);return{identity:e.identity}}function inspectWindowsDirectoryCommandSync(e,t){return fullIdentityReceipt(executeSync(`directory`,{targetPath:e,requirePrivate:t}))}async function inspectWindowsDirectoryCommand(e,t){return fullIdentityReceipt(await execute(`directory`,{targetPath:e,requirePrivate:t}))}function protectPrivateWindowsFileCommandSync(e,t,n){return assertIdentity(n),fullIdentityReceipt(executeSync(`protect-file`,{fd:e,targetPath:t,expectedParentIdentity:n}))}async function protectPrivateWindowsFileCommand(e,t,n){return assertIdentity(n),fullIdentityReceipt(await execute(`protect-file`,{fd:e,targetPath:t,expectedParentIdentity:n}))}function verifyPrivateWindowsFileCommandSync(e,t,n,r,i=1){assertIdentity(n),assertIdentity(r),fullIdentityReceipt(executeSync(`verify-file`,{fd:e,targetPath:t,expectedFileIdentity:n,expectedParentIdentity:r,expectedLinks:i}),n)}async function verifyPrivateWindowsFileCommand(e,t,n,r,i=1){assertIdentity(n),assertIdentity(r),fullIdentityReceipt(await execute(`verify-file`,{fd:e,targetPath:t,expectedFileIdentity:n,expectedParentIdentity:r,expectedLinks:i}),n)}function resolveCreationPermissions(e,t){let n=e.private,r=e.mode;if(n!==void 0&&typeof n!=`boolean`)throw TypeError(`private must be a boolean`);if(r!==void 0&&(!Number.isInteger(r)||r<0||r>4095))throw RangeError(`mode must contain only permission bits`);if(n&&r!==void 0&&r&3647)throw new I(`insecure-permissions`,`private creation requires owner-only permission bits`);return n&&assertDarwinPrivateCreationAvailable(),n&&t&&assertDarwinPrivateDirectoryMode(r??448),{private:n===!0,mode:r??(n?t?448:384:void 0)}}function assertPrivatePosixDirectory(e){if(typeof process.getuid!=`function`||e.uid!==BigInt(process.getuid()))throw new I(`not-owned`,`private directory must belong to the current user`);if((e.mode&3647n)!=0n)throw new I(`insecure-permissions`,`existing directory is not private`)}function unavailable$5(){throw new I(`helper-unavailable`,`private Windows creation requires an up-to-date native helper`)}function assertPrivateFileCreationAvailable(){let e=P();process.platform===`win32`&&b().mode===`require`&&(typeof e?.createPrivateDirectoryWithParentIdentity!=`function`||typeof e.inspectWindowsDirectory!=`function`||typeof e.protectPrivateWindowsFile!=`function`||typeof e.verifyPrivateWindowsFile!=`function`)&&unavailable$5()}function commandFallback(e){b().mode===`require`&&unavailable$5(),warnNativeFallback(`windows-private-creation`,`Private Windows creation launches the packaged .NET helper for each check or creation.`,e)}function creationOperation(e){let t=P(),n=t?.[e];if(typeof n==`function`)return n.bind(t);commandFallback(e)}function inspectCreationDirectorySync(e,t){w(e,`filesystem`);let n=creationOperation(`inspectWindowsDirectory`);return(n?n(e,t):inspectWindowsDirectoryCommandSync(e,t)).identity}async function inspectCreationDirectory(e,t){w(e,`filesystem`);let n=creationOperation(`inspectWindowsDirectory`);return(n?n(e,t):await inspectWindowsDirectoryCommand(e,t)).identity}function assertPrivateDirectorySync(e){let t=B(e);process.platform===`win32`?inspectCreationDirectorySync(e,!0):(assertPrivatePosixDirectory(t),assertDarwinCreationDirectoryAcl(e,t)),B(e,t)}async function assertPrivateDirectory(e){let t=B(e);process.platform===`win32`?await inspectCreationDirectory(e,!0):(assertPrivatePosixDirectory(t),assertDarwinCreationDirectoryAcl(e,t)),B(e,t)}function protectCreatedFileSync(e,t,n){let r=creationOperation(`protectPrivateWindowsFile`);return(r?r(e,t,n):protectPrivateWindowsFileCommandSync(e,t,n)).identity}async function protectCreatedFile(e,t,n){let r=creationOperation(`protectPrivateWindowsFile`);return(r?r(e,t,n):await protectPrivateWindowsFileCommand(e,t,n)).identity}function verifyCreatedFileSync(e,t,n,r,i=1){let a=creationOperation(`verifyPrivateWindowsFile`);a?a(e,t,n,r,i):verifyPrivateWindowsFileCommandSync(e,t,n,r,i)}async function verifyCreatedFile(e,t,n,r,i=1){let a=creationOperation(`verifyPrivateWindowsFile`);a?a(e,t,n,r,i):await verifyPrivateWindowsFileCommand(e,t,n,r,i)}function inspector(){let e=P();if(typeof e?.inspectDarwinAcl!=`function`)throw new I(`helper-unavailable`,`private Darwin creation requires native descriptor ACL inspection`);return e.inspectDarwinAcl.bind(e)}function assertDarwinPrivateCreationAvailable(){process.platform===`darwin`&&inspector()}function assertDarwinPrivateDirectoryMode(e){if(process.platform===`darwin`&&!(e&~process.umask()&320))throw new I(`helper-unavailable`,`private Darwin directory ACL inspection requires owner read or search permission`)}function assertDarwinCreationAcl(e,t){if(process.platform!==`darwin`)return;let n=inspector()(e,t)?.state;if(n===`present`)throw new I(`insecure-permissions`,t?`private creation parent has inheritable Darwin ACL entries`:`private creation object has Darwin ACL entries`);if(n!==`absent`&&n!==`empty`)throw new I(`helper-unavailable`,`native Darwin ACL inspection returned incomplete facts`)}function assertDarwinCreationDirectoryAcl(e,t,n){if(process.platform!==`darwin`)return;assertDarwinPrivateCreationAvailable();let r;try{r=Q.openSync(e,Ft())}catch(t){if(t.code!==`EACCES`)throw t;let n=Et();if(!n)throw t;try{r=Q.openSync(e,n.flags|Q.constants.O_DIRECTORY|Q.constants.O_NOFOLLOW|Q.constants.O_NONBLOCK)}catch(e){throw e.code===`EACCES`?new I(`helper-unavailable`,`private Darwin directory ACL inspection requires owner read or search permission`,{cause:e}):e}}try{if(!z(()=>Q.fstatSync(r,{bigint:!0}),t).isDirectory())throw new I(`path-mismatch`,`ACL target is not the admitted directory`);assertDarwinCreationAcl(r,n),B(e,t)}finally{Q.closeSync(r)}}function assertCreationFile(e,t,n){let r=z(()=>Q.fstatSync(e,{bigint:!0}),n),i=z(()=>Q.lstatSync(t,{bigint:!0}),r);if(!r.isFile()||!i.isFile()||i.isSymbolicLink()||r.nlink!==1n||i.nlink!==1n)throw new I(`path-mismatch`,`created file is not the expected single-linked regular file`);return r}function assertPrivateCreationFile(e,t){if(process.platform!==`win32`){if(typeof process.getuid!=`function`||e.uid!==BigInt(process.getuid()))throw new I(`not-owned`,`created private file must belong to the current user`);if((e.mode&3647n)!=0n)throw new I(`insecure-permissions`,`created private file is not owner-only`);assertDarwinCreationAcl(t)}}function assertRecordedFile(e,t){if(!e.isFile()||e.isSymbolicLink()||!H(e,t))throw new I(`path-mismatch`,`created file cleanup preserved a replacement`)}function removeRecordedCreationFileSync(e,t,n){n();let r;try{r=Q.lstatSync(e,{bigint:!0})}catch(e){if(e?.code===`ENOENT`)return;throw e}assertRecordedFile(r,t),Q.unlinkSync(e)}async function removeRecordedCreationFile(e,t,n){n();let r;try{r=await $.lstat(e,{bigint:!0})}catch(e){if(e?.code===`ENOENT`)return;throw e}n(),assertRecordedFile(r,t),assertRecordedFile(Q.lstatSync(e,{bigint:!0}),t),await $.unlink(e)}function creationPublicationAfterFailure(e,t){if(e instanceof I){let t=e.details?.publication;if(t&&typeof t==`object`&&`status`in t&&t.status===`indeterminate`)return`indeterminate`}return t}function hasPreservedCreationArtifacts(e){if(!(e instanceof I))return!1;if(e.details?.cleanup===`preserved`||e.details?.cleanup===`failed`)return!0;let t=e.details?.publication;return typeof t==`object`&&!!t&&`status`in t&&(t.status===`published`||t.status===`indeterminate`)}function rethrowPrivateStageCreationFailure(e,t,n){if(e instanceof I&&e.code===`already-exists`)throw new I(`helper-failed`,`private file staging path already exists`,{cause:e,details:{publication:{status:`not-published`},path:t,stageDirectory:n}});let r=e instanceof I?e.details?.publication:void 0,i=e instanceof I&&e.details?.path===n&&typeof r==`object`&&!!r&&`status`in r&&r.status===`published`,a=hasUnsettledWindowsSecurityCommand(e);if(e!==null&&(typeof e==`object`||typeof e==`function`))try{let t=Object.getOwnPropertyDescriptor(e,`creationOutcome`);a||=!!(t&&`value`in t&&t.value===`unconfirmed`)}catch{a=!0}throw i||a?privateFileSettlementFailure({primary:e,cleanup:[],publication:`not-published`,path:t,stageDirectory:n,preserved:!0}):e}function privateFileSettlementFailure(e){return new I(`helper-failed`,`file creation or staging settlement failed`,{cause:e.cleanup.length?AggregateError([e.primary,...e.cleanup],`file creation and cleanup failed`):e.primary,details:{publication:{status:e.publication},path:e.path,stageDirectory:e.stageDirectory,cleanup:e.preserved||e.publication===`indeterminate`?`preserved`:e.cleanup.length?`failed`:`removed`}})}function assertBeforeCreation(e,t,n,r){t.private&&assertDarwinCreationDirectoryAcl(e.parent.dir,e.parent.stat,r),q(n?.(),`assertBeforeMutation`),(n!==void 0||t.private)&&e.assertParent(),t.private&&r===`directory`&&assertDarwinPrivateDirectoryMode(t.mode),t.private&&assertDarwinCreationDirectoryAcl(e.parent.dir,e.parent.stat,r)}function creationAdmissionFromParent(e){let{dev:t,ino:n}=e.stat;if(typeof t!=`bigint`||typeof n!=`bigint`)throw new I(`path-mismatch`,`private creation requires an exact parent identity`);let r=B(e.dir,{dev:t,ino:n});return{expectedParentIdentity:{dev:r.dev,ino:r.ino,realPath:e.realPath}}}function prepareCreationPath(e,t){if(t&&={dev:t.dev,ino:t.ino,realPath:t.realPath},ht(e),w(e,`filesystem`),process.platform===`win32`&&e.replaceAll(`/`,`\\`).split(`\\`).some(e=>e.endsWith(`.`)||e.endsWith(` `)))throw new I(`invalid-path`,`creation path contains an ambiguous Windows component`);let n=Ce(e),r=Z.dirname(n);if(n===r||e.length===0)throw new I(`invalid-path`,`creation requires a child name`);t&&Re(r,t);let i=B(r),a=O.native(r),o={dir:r,realPath:a,stat:i},assertParent=()=>{Re(r,{dev:i.dev,ino:i.ino,realPath:a}),t&&Re(r,t)};return assertParent(),{target:n,parent:o,assertParent}}function creationCollision(e){return e?.code===`EEXIST`?new I(`already-exists`,`creation target already exists`,{cause:e}):e}function removeCreationDirectory(e,t,n){n();try{Re(e,t),Q.rmdirSync(e)}catch(e){if(e?.code!==`ENOENT`)throw e}}async function removeCreationDirectoryAsync(e,t,n){n();try{Re(e,t),await $.rmdir(e)}catch(e){if(e?.code!==`ENOENT`)throw e}}const Ri=/* @__PURE__ */ new Set([`EACCES`,`EPERM`,`EXDEV`,`ENOTSUP`,`EOPNOTSUPP`,`ENOSYS`]);function isHardlinkFallbackError(e){return Ri.has(e?.code??``)}function pathMismatch(e){return new I(`path-mismatch`,e)}function assertInitialSource(e){if(e.isSymbolicLink())throw new I(`path-alias`,`isolated producer output must not be a symlink`);if(!e.isFile())throw new I(`not-file`,`isolated producer output must be a regular file`);if(e.nlink!==1n)throw new I(`hardlink`,`isolated producer output must have exactly one link`)}function inspectLinkedFile(e,t,n,r){return z(()=>{let t=e();if(t.isSymbolicLink()||!t.isFile()||t.nlink!==n)throw pathMismatch(`${r} changed during isolated producer handoff`);return t},t)}function assertParents(e){e.assertTargetParent(),e.assertSourceParent()}function normalizeLinkError(e){return e?.code===`EEXIST`?new I(`already-exists`,`isolated producer sibling already exists`,U(e)):isHardlinkFallbackError(e)?new I(`helper-unavailable`,`atomic isolated producer handoff is unavailable`,U(e)):e}function removeSiblingIfOwned(e){if(!e.state.siblingOwned)return;e.assertTargetParent();let t;try{t=Q.lstatSync(e.targetPath,{bigint:!0})}catch(t){if(t?.code===`ENOENT`){e.state.siblingOwned=!1;return}throw t}if(t.isSymbolicLink()||!t.isFile()||t.nlink!==1n&&t.nlink!==2n||!H(t,e.identity))throw pathMismatch(`isolated producer sibling changed before cleanup`);Q.unlinkSync(e.targetPath),e.state.siblingOwned=!1,e.assertTargetParent()}function combinedFailure(e,t){return t.length===0?e:AggregateError([e,...t],`isolated producer handoff and settlement failed`)}function hasCode(e,t){return!(e instanceof I)&&t.includes(e?.code??``)}async function throwAfterClosing(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let e of t)if(e&&!r.has(e)){r.add(e);try{await e.close()}catch(e){n.push(e)}}throw combinedFailure(e,n)}function inspectSourceDescriptor(e,t,n=1n){return inspectLinkedFile(()=>Q.fstatSync(e.fd,{bigint:!0}),t,n,`isolated producer descriptor`)}function historicalOpenFlags(e){return(e?Q.constants.O_RDWR:Q.constants.O_RDONLY)|ke()}async function openHistoricalSource(e,t,n,r){let i;try{return i=await $.open(e,historicalOpenFlags(n)),inspectSourceDescriptor(i,t,r),i}catch(e){if(i)return await throwAfterClosing(e,[i]);throw e}}async function openProducerSource(e,t,n=1n){if(process.platform!==`win32`)return await openHistoricalSource(e.sourcePath,t,e.readWrite,n);let r;try{r=await $.open(e.sourcePath,Q.constants.O_WRONLY)}catch(r){if(!hasCode(r,[`EACCES`,`EPERM`,`EBUSY`]))throw r;return await openHistoricalSource(e.sourcePath,t,e.readWrite,n)}try{return inspectSourceDescriptor(r,t,n),r}catch(e){if(!hasCode(e,[`EACCES`,`EPERM`]))return await throwAfterClosing(e,[r])}let i;try{i=await $.open(e.sourcePath,historicalOpenFlags(e.readWrite)),inspectSourceDescriptor(i,t,n),inspectLinkedFile(()=>Q.lstatSync(e.sourcePath,{bigint:!0}),t,n,`isolated producer path`),assertParents(e)}catch(e){return await throwAfterClosing(e,[i,r])}try{await r.close()}catch(e){return await throwAfterClosing(e,[i])}return i}var FileHandoff=class{paths;identity;createdLabels;siblingOwned=!1;publication=`not-published`;cleanup=`preserved`;closeFailed=!1;constructor(e,t,n=!1){this.paths=e,this.identity=t,this.createdLabels=n}inspect(e,t){assertParents(this.paths);let n=inspectLinkedFile(()=>Q.fstatSync(e.fd,{bigint:!0}),this.identity,t,this.createdLabels?`created file descriptor`:`isolated producer descriptor`);return this.cleanup!==`removed`&&inspectLinkedFile(()=>Q.lstatSync(this.paths.sourcePath,{bigint:!0}),this.identity,t,this.createdLabels?`created file stage`:`isolated producer path`),{opened:n,named:this.publication===`published`?inspectLinkedFile(()=>Q.lstatSync(this.paths.targetPath,{bigint:!0}),this.identity,t,this.createdLabels?`created file destination`:`isolated producer sibling`):void 0}}publish(){this.publication=`indeterminate`;try{Q.linkSync(this.paths.sourcePath,this.paths.targetPath)}catch(e){let t=normalizeLinkError(e);throw t instanceof I&&(t.code===`already-exists`||t.code===`helper-unavailable`)&&(this.publication=`not-published`),t}this.publication=`published`}retireSource(){this.cleanup=`failed`,Q.unlinkSync(this.paths.sourcePath),this.cleanup=`removed`}failure(e,t){let n=e[0];return new I(this.closeFailed||e.length>1?`helper-failed`:n instanceof I?n.code:`helper-failed`,`created file publication failed`,{cause:e.length===1?n:AggregateError(e,t),details:{publication:{status:this.publication},cleanup:this.cleanup,resources:this.closeFailed?`close-failed`:`closed`,path:this.paths.targetPath,dev:this.identity.dev,ino:this.identity.ino}})}};async function handoffFile(e){let t=`source`in e?e:void 0,n=t?.identity??z(()=>{assertParents(e);let t=Q.lstatSync(e.sourcePath,{bigint:!0});return assertInitialSource(t),t}),r=t?.source,i=new Set(r?[r]:[]),a=[],o,s=new FileHandoff(e,n);async function close(e){t&&i.delete(e);try{await e.close(),i.delete(e)}catch(e){throw s.closeFailed=!0,e}}try{assertInitialSource(n),r||(r=await openProducerSource({...e,readWrite:`readWrite`in e&&e.readWrite},n),i.add(r)),s.inspect(r,1n),t?.verifyDescriptor&&await t.verifyDescriptor(r.fd,e.sourcePath,1),t||(o=sn(e.targetPath,{cleanupSync:()=>removeSiblingIfOwned({assertTargetParent:e.assertTargetParent,identity:n,state:s,targetPath:e.targetPath})})),q(t?.assertBeforeMutation?.(),`assertBeforeMutation`),s.inspect(r,1n),s.publish(),s.siblingOwned=!t;try{q(t?.onPublished?.(),`onPublished`)}catch(e){a.push(e)}if(s.inspect(r,2n),process.platform===`win32`){let a=t?await $.open(e.targetPath,historicalOpenFlags(!0)):await openProducerSource({...e,sourcePath:e.targetPath,readWrite:`readWrite`in e&&e.readWrite},n,2n);i.add(a),s.inspect(a,2n),t?.verifyDescriptor&&await t.verifyDescriptor(a.fd,e.targetPath,2),s.inspect(a,2n),inspectSourceDescriptor(r,n,2n),await close(r),r=a,s.inspect(r,2n)}t?.verifyDescriptor&&await t.verifyDescriptor(r.fd,process.platform===`win32`?e.targetPath:e.sourcePath,2),q(t?.assertBeforeMutation?.(),`assertBeforeMutation`),s.inspect(r,2n),s.retireSource(),t?.verifyDescriptor&&await t.verifyDescriptor(r.fd,e.targetPath,1);let{opened:c,named:l}=s.inspect(r,1n),u=n.mode&511n;if(!t&&process.platform===`win32`&&(u&128n)==0n&&((c.mode&511n)!==u||(l.mode&511n)!==u)){assertParents(e),Q.fchmodSync(r.fd,Number(u));let t=s.inspect(r,1n);if((t.opened.mode&511n)!==u||(t.named.mode&511n)!==u)throw pathMismatch(`isolated producer read-only mode could not be restored`)}if(!t){let e=o,release=(()=>{s.siblingOwned=!1,e()});return release.setIdentity=e.setIdentity,{handle:r,identity:n,unregister:release}}}catch(e){a.push(e)}if(a.length===0)return r;if(o)try{removeSiblingIfOwned({assertTargetParent:e.assertTargetParent,identity:n,state:s,targetPath:e.targetPath}),o()}catch(e){a.push(e)}for(let e of[...i].reverse())try{await close(e)}catch(e){a.push(e)}throw t?s.failure(a,`isolated producer handoff and settlement failed`):combinedFailure(a[0],a.slice(1))}function handoffCreatedFile(e){return handoffFile(e)}function handoffCreatedFileSync(e){let t=e.source,n=/* @__PURE__ */ new Set([t]),r=[],i=new FileHandoff(e,e.identity,!0);function close(e){n.delete(e);try{e.close()}catch(e){throw i.closeFailed=!0,e}}function verifyCurrent(t,n,r){i.inspect(t,r),e.verifyDescriptor?.(t.fd,n,Number(r))}try{assertInitialSource(e.identity),verifyCurrent(t,e.sourcePath,1n),q(e.assertBeforeMutation?.(),`assertBeforeMutation`),i.inspect(t,1n),i.publish();try{e.onPublished?.()}catch(e){r.push(e)}if(process.platform===`win32`){verifyCurrent(t,e.sourcePath,2n);let r=ownFileDescriptorSync(Q.openSync(e.targetPath,Q.constants.O_RDWR|ke()));n.add(r),verifyCurrent(r,e.targetPath,2n),inspectLinkedFile(()=>Q.fstatSync(t.fd,{bigint:!0}),e.identity,2n,`created file descriptor`),close(t),t=r}let a=process.platform===`win32`?e.targetPath:e.sourcePath;verifyCurrent(t,a,2n),q(e.assertBeforeMutation?.(),`assertBeforeMutation`),i.inspect(t,2n),i.retireSource(),verifyCurrent(t,e.targetPath,1n)}catch(e){r.push(e)}if(r.length===0)return t;for(let e of n)try{close(e)}catch(e){r.push(e)}throw i.failure(r,`created file publication and settlement failed`)}function createPrivateWindowsFile(e,t,n){let r=t.assertBeforeMutation;if(Q.lstatSync(e.target,{throwIfNoEntry:!1}))throw new I(`already-exists`,`creation target already exists`);let i=inspectCreationDirectorySync(e.parent.dir,!1);e.assertParent();let a=Z.join(e.parent.dir,`.fs-safe-create-${oi()}`),o;try{o=createDirectoryWithReceiptSync(a,{private:!0,assertBeforeMutation:r},{expectedParentIdentity:e.parent.stat})}catch(t){rethrowPrivateStageCreationFailure(t,e.target,a)}let s=o.windowsIdentity,c=Z.join(a,`file`),assertStage=()=>{e.assertParent(),Re(a,o.stat)},l,u,d,f=`not-published`;try{if(inspectCreationDirectorySync(a,!0)!==s)throw new I(`path-mismatch`,`private staging directory changed before file creation`);return q(r?.(),`assertBeforeMutation`),assertStage(),re(c),l=ownFileDescriptorSync(Q.openSync(c,Q.constants.O_RDWR|Q.constants.O_CREAT|Q.constants.O_EXCL|ke(),384)),u=assertCreationFile(l.fd,c),q(r?.(),`assertBeforeMutation`),assertStage(),assertCreationFile(l.fd,c,u),d=protectCreatedFileSync(l.fd,c,s),assertStage(),l=handoffCreatedFileSync({source:l,sourcePath:c,targetPath:e.target,identity:u,assertSourceParent:assertStage,assertTargetParent:e.assertParent,assertBeforeMutation:r,verifyDescriptor:(e,t,n)=>verifyCreatedFileSync(e,t,d,t===c?s:i,n),onPublished:()=>{f=`published`}}),Q.fchmodSync(l.fd,n),e.assertParent(),u=assertCreationFile(l.fd,e.target,u),verifyCreatedFileSync(l.fd,e.target,d,i),removeCreationDirectory(a,o.stat,e.assertParent),l}catch(t){f=creationPublicationAfterFailure(t,f);let n=[];if(l)try{l.close()}catch(e){n.push(e)}if(f!==`indeterminate`){if(u)try{removeRecordedCreationFileSync(c,u,assertStage)}catch(e){n.push(e)}try{removeCreationDirectory(a,o.stat,e.assertParent)}catch(e){n.push(e)}}throw f===`not-published`&&n.length===0?creationCollision(t):privateFileSettlementFailure({primary:t,cleanup:n,publication:f,path:e.target,stageDirectory:a})}}function createFileSync(e,t={}){return createFileWithAdmissionSync(e,t)}function createFileWithAdmissionSync(e,t={},n={}){let r=resolveCreationPermissions(t,!1),i=t.assertBeforeMutation,a=prepareCreationPath(e,n.expectedParentIdentity);if(r.private&&process.platform===`win32`)return assertPrivateFileCreationAvailable(),createPrivateWindowsFile(a,{...r,assertBeforeMutation:i},r.mode);assertBeforeCreation(a,r,i,`file`);let o;try{re(a.target),o=ownFileDescriptorSync(Q.openSync(a.target,Q.constants.O_RDWR|Q.constants.O_CREAT|Q.constants.O_EXCL|ke(),r.mode??438))}catch(e){throw creationCollision(e)}try{let e=assertCreationFile(o.fd,a.target);return a.assertParent(),r.private&&assertPrivateCreationFile(e,o.fd),o}catch(e){let t=e;try{o.close()}catch(n){t=AggregateError([e,n],`created file admission and close failed`)}throw new I(`helper-failed`,`created file admission failed`,{cause:t,details:{publication:{status:`published`},path:a.target,cleanup:`preserved`}})}}async function createFileHandle(e,t={},n={}){let r=resolveCreationPermissions(t,!1),i=t.assertBeforeMutation;if(process.platform!==`win32`||!r.private){let t=prepareCreationPath(e,n.expectedParentIdentity);assertBeforeCreation(t,r,i,`file`);try{re(t.target)}catch(e){throw creationCollision(e)}let a=await $.open(t.target,Q.constants.O_RDWR|Q.constants.O_CREAT|Q.constants.O_EXCL|ke(),r.mode??438).catch(e=>{throw creationCollision(e)});try{let e=assertCreationFile(a.fd,t.target);return t.assertParent(),r.private&&assertPrivateCreationFile(e,a.fd),a}catch(e){let n=e;try{await a.close()}catch(t){n=AggregateError([e,t],`created file admission and close failed`)}throw new I(`helper-failed`,`created file handle admission failed`,{cause:n,details:{publication:{status:`published`},path:t.target,cleanup:`preserved`}})}}return assertPrivateFileCreationAvailable(),await createPrivateWindowsFileHandle(prepareCreationPath(e,n.expectedParentIdentity),{mode:r.mode,assertBeforeMutation:i})}function directoryAdoptionFailure(e,t,n){return new I(`helper-failed`,`created directory admission failed`,{cause:e,details:{publication:{status:`published`},path:t,cleanup:`preserved`,...n===void 0?{}:{windowsIdentity:n}}})}function privateDirectoryBackend(){let e=P();if(typeof e?.createPrivateDirectoryWithParentIdentity==`function`)return e.createPrivateDirectoryWithParentIdentity.bind(e);if(b().mode===`require`)throw new I(`helper-unavailable`,`private directory creation requires an up-to-date native parent identity capability`);warnNativeFallback(`windows-private-directory`,`Private Windows directory creation launches the packaged .NET helper for each check or creation.`,`createPrivateDirectoryWithParentIdentity`)}async function createDirectoryWithAdmission(e,t={},n={}){await createDirectoryWithReceipt(e,t,n)}async function createDirectoryWithReceipt(e,t={},n={}){let r=resolveCreationPermissions(t,!0),i=t.assertBeforeMutation,a=prepareCreationPath(e,n.expectedParentIdentity),o=r.private&&process.platform===`win32`?privateDirectoryBackend():void 0,s=r.private&&process.platform===`win32`?await inspectCreationDirectory(a.parent.dir,!1):void 0;assertBeforeCreation(a,r,i,`directory`);let c=!1,l;try{if(s!==void 0){let e=o?o(a.target,s):await createPrivateWindowsDirectoryCommand(a.target,s);if(c=!0,l=e.identity,await inspectCreationDirectory(a.target,!0)!==e.identity)throw new I(`path-mismatch`,`created private directory changed before adoption`)}else await $.mkdir(a.target,{mode:r.mode}),c=!0,r.private&&await assertPrivateDirectory(a.target);return a.assertParent(),{stat:B(a.target),windowsIdentity:l}}catch(e){throw c?directoryAdoptionFailure(e,a.target,l):creationCollision(e)}}function createDirectorySync(e,t={}){createDirectoryWithReceiptSync(e,t,{})}function createDirectoryWithReceiptSync(e,t={},n={}){let r=resolveCreationPermissions(t,!0),i=t.assertBeforeMutation,a=prepareCreationPath(e,n.expectedParentIdentity),o=r.private&&process.platform===`win32`?privateDirectoryBackend():void 0,s=r.private&&process.platform===`win32`?inspectCreationDirectorySync(a.parent.dir,!1):void 0;assertBeforeCreation(a,r,i,`directory`);let c=!1,l;try{if(s!==void 0){let e=o?o(a.target,s):createPrivateWindowsDirectoryCommandSync(a.target,s);if(c=!0,l=e.identity,inspectCreationDirectorySync(a.target,!0)!==e.identity)throw new I(`path-mismatch`,`created private directory changed before adoption`)}else Q.mkdirSync(a.target,{mode:r.mode}),c=!0,r.private&&assertPrivateDirectorySync(a.target);return a.assertParent(),{stat:B(a.target),windowsIdentity:l}}catch(e){throw c?directoryAdoptionFailure(e,a.target,l):creationCollision(e)}}async function createPrivateWindowsFileHandle(e,t){let n=t.assertBeforeMutation,r=await $.lstat(e.target).catch(e=>{if(e.code!==`ENOENT`)throw e});if(e.assertParent(),r)throw new I(`already-exists`,`creation target already exists`);let i=await inspectCreationDirectory(e.parent.dir,!1);e.assertParent();let a=Z.join(e.parent.dir,`.fs-safe-create-${oi()}`),o;try{o=await createDirectoryWithReceipt(a,{private:!0,assertBeforeMutation:n},{expectedParentIdentity:e.parent.stat})}catch(t){rethrowPrivateStageCreationFailure(t,e.target,a)}let s=o.windowsIdentity,c=Z.join(a,`file`),assertStage=()=>{e.assertParent(),Re(a,o.stat)},l,u,d=`not-published`;try{if(await inspectCreationDirectory(a,!0)!==s)throw new I(`path-mismatch`,`private staging directory changed before file creation`);q(n?.(),`assertBeforeMutation`),assertStage(),re(c),l=await $.open(c,Q.constants.O_RDWR|Q.constants.O_CREAT|Q.constants.O_EXCL|ke(),384),assertStage(),u=assertCreationFile(l.fd,c),q(n?.(),`assertBeforeMutation`),assertStage(),assertCreationFile(l.fd,c,u);let r=await protectCreatedFile(l.fd,c,s);assertStage(),assertCreationFile(l.fd,c,u);let f=l;return l=void 0,l=await handoffCreatedFile({source:f,sourcePath:c,targetPath:e.target,identity:u,assertSourceParent:assertStage,assertTargetParent:e.assertParent,assertBeforeMutation:n,verifyDescriptor:(e,t,n)=>verifyCreatedFile(e,t,r,t===c?s:i,n),onPublished:()=>{d=`published`}}),q(n?.(),`assertBeforeMutation`),e.assertParent(),assertCreationFile(l.fd,e.target,u),await verifyCreatedFile(l.fd,e.target,r,i),e.assertParent(),assertCreationFile(l.fd,e.target,u),await l.chmod(t.mode),await verifyCreatedFile(l.fd,e.target,r,i),e.assertParent(),assertCreationFile(l.fd,e.target,u),await removeCreationDirectoryAsync(a,o.stat,e.assertParent),e.assertParent(),assertCreationFile(l.fd,e.target,u),l}catch(t){d=creationPublicationAfterFailure(t,d);let n=d===`indeterminate`||hasUnsettledWindowsSecurityCommand(t),r=[];if(l){let e=l;l=void 0;try{await e.close()}catch(e){r.push(e)}}if(!n){if(u)try{await removeRecordedCreationFile(c,u,assertStage)}catch(e){r.push(e)}try{await removeCreationDirectoryAsync(a,o.stat,e.assertParent)}catch(e){r.push(e)}}throw d===`not-published`&&r.length===0&&!n?creationCollision(t):privateFileSettlementFailure({primary:t,cleanup:r,publication:d,path:e.target,stageDirectory:a,preserved:n})}}const zi=Uint8Array,Bi=Object.getPrototypeOf(zi.prototype),Vi=Object.getOwnPropertyDescriptor(Bi,`byteLength`).get,Hi=Object.getOwnPropertyDescriptor(Bi,`byteOffset`).get,Ui=Object.getOwnPropertyDescriptor(Bi,`buffer`).get;function snapshotByteView(e){let t=Reflect.apply(Vi,e,[]);return t===0?new zi(0):new zi(Reflect.apply(Ui,e,[]),Reflect.apply(Hi,e,[]),t)}async function writeAllToFile(e,t,n={}){let r=typeof t==`string`?Buffer.from(t,n.encoding??`utf8`):t,i=0;for(;i<r.byteLength;){let t=Math.min(524288,r.byteLength-i),a=n.position===void 0?null:n.position+i;n.assertBeforeMutation?.();let o=typeof e==`number`?await new Promise((n,o)=>{Q.write(e,r,i,t,a,(e,t)=>{e?o(e):n(t)})}):(await e.write(r,i,t,a)).bytesWritten;if(o<=0)throw new I(`helper-failed`,`file write made no progress`);i+=o}}const Wi=Object.freeze([]);function createTransferBuffer(e,t){return Buffer.allocUnsafe(Math.min(524288,Math.max(65536,e),t+1))}function copyFileDescriptorSync(e,t,n={}){let r=n.signal;r?.throwIfAborted();let i=Ye(n.maxBytes),a=n.onChunk,o=n.assertBeforeMutation,s=z(()=>(r?.throwIfAborted(),Q.fstatSync(e,{bigint:!0})));if(!s.isFile())throw new I(`not-file`,`copy source descriptor must be a regular file`);if(i!==void 0&&Number.isFinite(i)&&s.size>BigInt(i))throw new I(`too-large`,`file exceeds limit of ${i} bytes`);let c=z(()=>(r?.throwIfAborted(),Q.fstatSync(t,{bigint:!0})));if(!c.isFile())throw new I(`not-file`,`copy target descriptor must be a regular file`);if(s.dev===c.dev&&s.ino===c.ino)throw new I(`path-alias`,`copy source and target descriptors refer to the same file`);let l=i??1/0,u=createTransferBuffer(Number(s.size),l),d=0;for(;;){r?.throwIfAborted();let n=Q.readSync(e,u,0,Math.min(u.length,l-d+1),d);if(n>l-d)throw new I(`too-large`,`file exceeds limit of ${l} bytes`);if(n===0)return d;let i=u.subarray(0,n);q(a?.(i),`onChunk`);let s=0;for(;s<n;){r?.throwIfAborted(),q(o?.(),`assertBeforeMutation`),r?.throwIfAborted();let e=Q.writeSync(t,i,s,n-s,d+s);if(e<=0)throw new I(`helper-failed`,`file write made no progress`);s+=e}d+=n}}function transferFileHandle(e,t,n){try{let r=n.maxBytes,i=n.sizeHint,a=n.targetPosition,o=n.signal,s=n.onChunk,c=n.assertBeforeMutation;return transferFileHandleCore(e,t,i,r,a,o,s,o===void 0&&c===void 0?void 0:()=>{o?.throwIfAborted(),c&&Reflect.apply(c,n,Wi)},n)}catch(e){return Promise.reject(e)}}async function transferFileHandleCore(e,t,n,r,i,a,o,s,c){let l=r??1/0,u=createTransferBuffer(n,l),d=0;for(;;){a?.throwIfAborted();let{bytesRead:n}=await e.read(u,0,Math.min(u.length,l-d+1),d);if(a?.throwIfAborted(),n>l-d)throw new I(`too-large`,`file exceeds limit of ${l} bytes`);if(n===0)return d;let r=u.subarray(0,n);if(o){let e=Function.prototype.call.call(o,c,r);q(e,`onChunk`)}await writeAllToFile(t,r,{position:i===void 0?void 0:i+d,assertBeforeMutation:s}),d+=n}}function recordFileOpenFailure(e,t){throw at(e,`open:${t}`),e}function recordExclusiveCreateFailure(e,t){throw at(e,`exclusive-create:${t}`),e}function openedPathResolutionError(e=new I(`path-mismatch`,`unable to resolve opened file path`)){return at(e,`resolution`),e}async function recordPreOpenFileChange(e,t,n,r,i){if(et(e,`identity`)&&r?.isFile()&&i?.isFile()&&[0n,1n].includes(r.nlink)&&[0n,1n].includes(i.nlink))try{await it(async()=>r);let a=await it(()=>Q.fstatSync(t.fd,{bigint:!0}),i);a.isFile()&&[0n,1n].includes(a.nlink)&&(r.dev!==a.dev||r.ino!==a.ino)&&at(e,`changed:${n}`)}catch{}}async function recordOpenedFileFailure(e,t,n,r){if(!(!et(e,`resolution`)&&!et(e,`identity`)||!r.isFile()||r.nlink>1n))try{let i=await it(()=>Q.fstatSync(t.fd,{bigint:!0}),r);i.isFile()&&i.nlink===0n&&at(e,`unlinked:${n}`)}catch{}}const ensureTrailingSep=e=>e.endsWith(Z.sep)?e:e+Z.sep;function assertValidRootRelativePath(e){ht(e,`relative path contains a NUL byte`),w(e,`filesystem`,`relative path uses a Windows filesystem namespace alias`)}function assertValidRootDestinationPath(e){if(assertValidRootRelativePath(e),fe(e))throw new I(`invalid-path`,`relative path must not start with a drive letter`)}let Gi;const Ki=/(?:^|\/)\.\.(?:\/|$)/,qi=/(?:^|[\\/])\.\.(?:[\\/]|$)/;async function expandRelativePathWithHome(e){let t=e===`~`,n=e.startsWith(`~/`)||Z.sep===`\\`&&e.startsWith(`~\\`);if(!t&&!n)return w(e,`filesystem`,`relative path uses a Windows filesystem namespace alias`),e;let r=process.env.HOME||process.env.USERPROFILE||pi.homedir();if(w(r,`filesystem`,`home path uses a Windows filesystem namespace alias`),Gi?.raw!==r){let e=r;try{e=O.native(D(r))}catch{}Gi={raw:r,real:e}}if(t)return w(Gi.real,`filesystem`,`home path uses a Windows filesystem namespace alias`),Gi.real;let i=`${ensureTrailingSep(Gi.real)}${e.slice(2)}`;return w(i,`filesystem`,`expanded path uses a Windows filesystem namespace alias`),i}async function resolveRootContext(e){ht(e,`root dir contains a NUL byte`),w(e,`filesystem`,`root dir uses a Windows filesystem namespace alias`);let t=Ce(e);w(t,`filesystem`,`root dir uses a Windows filesystem namespace alias`);let n,r,i;try{n=O.native(D(e)),w(n,`filesystem`,`canonical root path uses a Windows filesystem namespace alias`),r=await it(()=>{let e=Q.statSync(n,{bigint:!0});if(!e.isDirectory())throw new I(`invalid-path`,`root dir is not a directory`);return e}),i={dev:r.dev,ino:r.ino}}catch(e){throw e instanceof I?e:E(e)?new I(`not-found`,`root dir not found`):e}return{rootDir:t,rootGuard:{dir:n,realPath:n,stat:r},rootIdentity:i,rootReal:n,rootWithSep:ensureTrailingSep(n)}}function rootRelativeReadPath(e,t){if(!Z.isAbsolute(t))return t;let n=process.platform===`win32`?t.replaceAll(`/`,Z.sep):t,r=e.rootDir===e.rootReal?[e.rootReal]:[e.rootDir,e.rootReal];for(let t of r){if(process.platform===`win32`){let r=M({rootPath:t,candidatePath:n,rootIdentity:e.rootIdentity,resolveCandidateRoot:t===e.rootDir&&e.rootDir!==e.rootReal});if(r)return`.${Z.sep}${r.relativePath}`;continue}let r=ensureTrailingSep(t);if(n.startsWith(r)){let e=r.length;for(;n[e]===Z.sep;)e+=1;return`.${Z.sep}${n.slice(e)}`}}return n}function assertRootIdentityCurrentSync(e,t){try{let n=B(e.rootReal,{dev:e.rootIdentity.dev,ino:e.rootIdentity.ino});t?.(n)}catch(e){throw T(e instanceof Error?e:void 0)}}async function assertRootIdentityCurrent(e,t){assertRootIdentityCurrentSync(e,t)}async function createRootObservationGuard(e){let t=e.rootIdentity;if(typeof t?.dev!=`bigint`||typeof t.ino!=`bigint`)throw T();try{let n=await dt(e.rootReal,t);return ot(n,e.rootReal,e.rootReal)}catch(e){throw T(e instanceof Error?e:void 0)}}async function resolvePathInRoot(e,t,n){assertValidRootRelativePath(t),await assertRootIdentityCurrent(e);let r=await expandRelativePathWithHome(t);w(r,`filesystem`,`expanded path uses a Windows filesystem namespace alias`);let i=be(e.rootWithSep,r);if(w(i,`filesystem`,`resolved path uses a Windows filesystem namespace alias`),!n?.resolveCanonical&&!k(e.rootWithSep,i))throw G();n?.rejectUnsafeDeviceReads===!0&&oe(i);let a=Z.isAbsolute(r)?r:`${e.rootWithSep}${r}`;w(a,`filesystem`,`resolved path uses a Windows filesystem namespace alias`);try{let t={absolutePath:a,rootPath:e.rootReal,rootCanonicalPath:e.rootReal,rootIdentity:e.rootIdentity,boundaryLabel:`root`,policy:n?.allowFinalSymlink?ft.unlinkTarget:void 0,rejectSymlinks:n?.rejectSymlinks,rejectFinalSymlink:n?.rejectFinalSymlink},o=await _t(t),s=process.platform===`win32`?qi:Ki;if(n?.rejectAmbiguousParents&&s.test(r)&&Z.relative(o.canonicalPath,i)!==``){let e=await _t({...t,absolutePath:i});if(Z.relative(o.canonicalPath,e.canonicalPath)!==``)throw new I(`path-alias`,`parent traversal resolves differently through a symlink`)}if(n?.resolveCanonical)i=o.canonicalPath;else{let t=M({rootPath:e.rootReal,candidatePath:o.absolutePath,rootIdentity:e.rootIdentity});if(!t)throw G();i=t.path}}catch(e){let t=ve(e,a);if(t)throw t;if(e instanceof I&&e.code===`symlink`)throw e;if(j(e,`ENAMETOOLONG`))throw new I(`invalid-path`,`relative path is too long`,U(e));let r=n?.aliasErrorCode??`outside-workspace`;throw new I(r,r===`path-alias`?`path alias escape blocked`:`file is outside workspace root`,U(e))}return{rootReal:e.rootReal,rootWithSep:e.rootWithSep,resolved:i}}function resolveFinalOpenedRealPath(e){try{return O.native(e)}catch(e){throw process.platform===`win32`&&e instanceof Error&&[`EPERM`,`EBADF`].includes(e.code??``)?openedPathResolutionError(e):e}}function inspectOpenedPathIdentitySync(e,t){let n=t===`follow-within-root`?Q.statSync(e,{bigint:!0}):Q.lstatSync(e,{bigint:!0});if(n.isSymbolicLink()&&t!==`follow-within-root`)throw new I(`symlink`,`symlink not allowed`);return n}async function admitRootReadHandle(e){try{if(e.hardlinks!==`allow`&&e.opened.stat.nlink>1)throw R();e.beforeFinalFence&&await e.beforeFinalFence(e.filePath,e.opened.handle);try{assertRootIdentityCurrentSync(e.root);let t;try{let n=z(()=>inspectOpenedPathIdentitySync(e.filePath,e.symlinks),e.identity);if(e.hardlinks!==`allow`&&n.nlink>1n)throw R();let r=resolveFinalOpenedRealPath(e.filePath);w(r,`filesystem`,`resolved file path uses a Windows filesystem namespace alias`);let i=M({rootPath:e.root.rootReal,candidatePath:r,rootIdentity:e.root.rootIdentity});if(!i)throw openedPathResolutionError(G());let a=z(()=>inspectOpenedPathIdentitySync(r,void 0),e.identity);if(e.hardlinks!==`allow`&&a.nlink>1n)throw R();t=i.path}catch(e){throw E(e)?openedPathResolutionError(Qe()):e}return e.afterPathIdentityCheck?.(e.filePath,e.opened.handle),assertRootIdentityCurrentSync(e.root),{...e.opened,realPath:t}}catch(t){throw e.identity.nlink<=1n&&await recordOpenedFileFailure(t,e.opened.handle,e.filePath,e.identity),t}}catch(t){throw await e.opened.handle.close().catch(()=>{}),t}}function copyError(e){if(e instanceof I)return e;let t=e?.code;return new I(t===`EEXIST`?`already-exists`:t===`ENOENT`?`not-found`:t===`too-large`?`too-large`:[`ENOTSUP`,`EOPNOTSUPP`,`ENOSYS`,`EXDEV`,`EINVAL`].includes(t??``)?`unsupported-platform`:`helper-failed`,`guarded synchronous file copy failed`,{cause:e})}function copyRootFileSync(e){return copyRootFileWithAdmissionSync(e,createCopyPathAdmissionCache())}function copyRootFileWithAdmissionSync(e,t){let n=e.source,r={rootPath:n.rootPath,absolutePath:n.absolutePath},i=e.destination,a={rootPath:i.rootPath,absolutePath:i.absolutePath},o=e.expectedSourceIdentity,s=o===void 0?void 0:Fe(o),c=s&&{dev:s.dev,ino:s.ino},l=resolveCopyCloneMode(e.clone,`never`),u=Ye(e.maxBytes),d=e.mode,f=e.preserveSourceMode,p=e.sourceHardlinks??`reject`;if(d!==void 0&&(!Number.isInteger(d)||d<0||d>511))throw new I(`invalid-path`,`copy mode must be an integer from 0 to 0o777`);if(p!==`allow`&&p!==`reject`)throw new I(`invalid-path`,`invalid copy source hardlink policy`);let m,h,g,_=!1,v,y,b=process.platform===`win32`?P():P(`copyFileExclusiveSync`,`removeStagedFile`),x=process.platform!==`win32`&&b?.copyFileExclusiveSync&&b.removeStagedFile?b.copyFileExclusiveSync.bind(b):void 0;try{let e=t.admit(r);if(v=t.admit(a,!0),re(a.absolutePath),Q.lstatSync(v.path,{throwIfNoEntry:!1}))throw new I(`already-exists`,`copy destination already exists`);let n=lt({...r,rootRealPath:e.rootCanonicalPath,boundaryLabel:`copy source`,maxBytes:u,rejectHardlinks:p!==`allow`});if(!n.ok)throw n.error??new I(`helper-failed`,`copy source admission failed`);m=ownFileDescriptorSync(n.fd);let i=z(()=>Q.fstatSync(n.fd,{bigint:!0}),c),verifySource=()=>{e.assertCurrent();for(let t of[()=>Q.fstatSync(n.fd,{bigint:!0}),()=>inspectOpenedPathIdentitySync(e.path,void 0)]){let e=z(t,i);if(!e.isFile())throw new I(`not-file`,`copy source must be a regular file`);if(p!==`allow`&&e.nlink>1n)throw new I(`hardlink`,`copy source must not be hardlinked`)}},o=d??(f?Number(i.mode&511n):384&~process.umask()),s;if(verifySource(),v.assertCurrent(),x){let e=V(b),t=On(v.parent.realPath);g=ownFileDescriptorSync(t.fd),_=!0,z(()=>Q.fstatSync(t.fd,{bigint:!0}),{dev:BigInt(v.parent.stat.dev),ino:BigInt(v.parent.stat.ino)}),v.assertCurrent();try{s=x(n.fd,t.fd,Z.basename(v.path),l,u!==void 0&&Number.isFinite(u)?u:void 0)}catch(e){throw jt(e,v.path),e}h=ownFileDescriptorSync(s.fd,e)}else{if(l===`always`)throw new I(`unsupported-platform`,`synchronous native file cloning is unavailable`);h=createFileWithAdmissionSync(v.path,{mode:384,assertBeforeMutation:v.assertCurrent},creationAdmissionFromParent(v.parent))}y=z(()=>Q.fstatSync(h.fd,{bigint:!0}));let verifyTarget=()=>{v.assertCurrent();let e=z(()=>Q.fstatSync(h.fd,{bigint:!0}),y),t=z(()=>inspectOpenedPathIdentitySync(v.path,void 0),y);if(!e.isFile()||e.nlink!==1n||!t.isFile()||t.nlink!==1n)throw new I(`path-mismatch`,`copy destination changed`);return e};if(verifyTarget(),s?.errorCode)throw copyError(Object.assign(Error(s.errorMessage),{code:s.errorCode}));let S=s?s.method:`copy`;if(S!==`clone`&&S!==`copy-file-range`&&S!==`copy`)throw new I(`helper-failed`,`native copy returned an unknown method`);s||copyFileDescriptorSync(n.fd,h.fd,{maxBytes:u}),verifySource();let C=verifyTarget();if(u!==void 0&&Number.isFinite(u)&&C.size>BigInt(u))throw new I(`too-large`,`copy exceeds maxBytes`);return Q.fchmodSync(h.fd,o),verifySource(),verifyTarget(),m.close(),_=!1,g?.close(),Object.freeze({...h,path:v.path,bytes:Number(C.size),method:S,identity:Object.freeze({dev:y.dev,ino:y.ino}),sourceIdentity:Object.freeze({dev:i.dev,ino:i.ino})})}catch(e){let t=copyError(e),n=[];if(h&&v)try{if(_){if(b.removeStagedFile(g.fd,Z.basename(v.path),h.fd)===`preserved`)throw new I(`path-mismatch`,`copy cleanup preserved a replacement`)}else y&&removeRecordedCreationFileSync(v.path,y,v.assertCurrent)}catch(e){n.push(e)}for(let e of[h,m,g])try{e?.close()}catch(e){n.push(e)}throw n.length?new I(t.code,t.message,{cause:AggregateError([t,...n],`copy and cleanup failed`),details:{path:v?.path,cleanup:`failed`}}):t}}function sameFileContentsSync(e,t,n={}){let r=Ye(n.maxBytes)??1/0,i=Math.min(r,2**53-1),tooLarge=()=>new I(`too-large`,`file comparison exceeds ${i} bytes`);for(let n of[e,t]){let e=Q.fstatSync(n,{bigint:!0});if(!e.isFile())throw new I(`not-file`,`file comparison requires regular-file descriptors`);if(e.size>BigInt(i))throw tooLarge()}let a=Buffer.allocUnsafe(Math.min(1048576,Math.max(1,i))),o=Buffer.allocUnsafe(a.length),s=0;for(;;){let n=Math.min(a.length,i-s);if(n===0){let n=Q.readSync(e,a,0,1,s),r=Q.readSync(t,o,0,1,s);if(n!==0||r!==0)throw tooLarge();return!0}let r=Mn(e,a.subarray(0,n),s),c=Mn(t,o.subarray(0,n),s);if(r!==c||!a.subarray(0,r).equals(o.subarray(0,c)))return!1;if(r<n)return!0;s+=r}}function swapAsciiCase(e){return e.replace(/[A-Za-z]/g,e=>{let t=e.toLowerCase();return e===t?e.toUpperCase():t})}function probeEntry(e,t,n){let r=swapAsciiCase(t);if(r===t)return;let i=n.has(t)&&n.has(r),a=Z.join(e,t),o,s;try{o=z(()=>Q.lstatSync(a,{bigint:!0}));try{let n=z(()=>Q.lstatSync(Z.join(e,r),{bigint:!0})),a=H(o,n);if(a||i){let n=new Set(Q.readdirSync(e)),o=n.has(t)&&n.has(r);if(i&&!o)return;s=a&&!o}else s=!1}catch(e){if(i||!E(e))return;s=!1}}catch{return}return z(()=>Q.lstatSync(a,{bigint:!0}),o),s}function probeTemporaryEntry(e){let t=`.fs-safe-case-probe-${oi()}`,n=x.sync(Q),r=new Kt(Z.join(e,t),n);try{r.start(),r.adopt(de(Ot(n,{tempPath:r.pathname,content:``,mode:384,sync:!1,onIdentity:r.onIdentity}))),de(r.assertCurrent());let i=probeEntry(e,t,new Set(Q.readdirSync(e)));return de(r.assertCurrent()),i}finally{de(r.finish({throwOnCleanupError:!0}))}}function probeDirectory(e,t,n){let r=O.native(e),i=B(r),a=new Set(Q.readdirSync(r)),o=n===void 0?void 0:probeEntry(r,n,a);for(let e of a){if(o!==void 0)break;o=probeEntry(r,e,a)}return o===void 0&&t&&(o=probeTemporaryEntry(r)),Re(r,i),O.native(e)===r?o:void 0}function probePathCaseInsensitiveSync(e,t={}){let n=Z.resolve(e),r=t.allowTemporaryProbe!==!1,i=!0;try{Q.lstatSync(n)}catch(e){if(!E(e))return;i=!1}if(i)try{return probeDirectory(Z.dirname(n),r,Z.basename(n))}catch{return}let a=Z.dirname(n);for(;;){let e=!1;try{e=Q.statSync(a).isDirectory()}catch{}if(e)try{return probeDirectory(a,r)}catch{return}let t=Z.dirname(a);if(t===a)return;a=t}}function syncFile(e){return typeof e==`number`?new Promise((t,n)=>Q.fsync(e,e=>e?n(e):t())):e.sync()}async function syncFileBestEffort(e){try{await syncFile(e)}catch(e){if(e?.code!==`EPERM`)throw e}}function syncFileBestEffortSync(e,t=Q){try{t.fsyncSync(e)}catch(e){if(e?.code!==`EPERM`)throw e}}function resolveFileCopyCloneMode(e){let t=resolveCopyCloneMode(e,`never`);if(t===`always`&&!P()?.copyFileExclusive)throw new I(`helper-unavailable`,`native file cloning is unavailable`);return t}function assertCopySourceCurrent(e,t){z(()=>Q.fstatSync(e.handle.fd,{bigint:!0}),t),z(()=>{let t=Q.lstatSync(e.realPath,{bigint:!0});if(t.isSymbolicLink()||!t.isFile())throw new I(`path-mismatch`,`copy source path changed`);return t},t)}async function writeCopyFileToFd(e,t,n,r){await transferFileHandle(t.handle,e,{maxBytes:n,sizeHint:t.size,signal:t.signal,assertBeforeMutation:r})}async function createNativeCopyFile(e,t,n,r,i,a){t.signal?.throwIfAborted();let o=he(e,`copyFileExclusive`);if(!o){if(t.clone===`always`)throw new I(`helper-unavailable`,`native file cloning is unavailable`);return}V(e);let s=t.signal?AbortSignal.any([t.signal]):void 0;try{return await o.copyFileExclusive(t.handle.fd,n,r,t.clone,i!==void 0&&Number.isFinite(i)?i:void 0,s)}catch(e){jt(e,a);let n=e?.code;if((n===`Cancelled`||n===`ABORT_ERR`)&&t.signal?.throwIfAborted(),n===`too-large`)throw new I(`too-large`,`file exceeds limit of ${i} bytes`,{cause:e});if(n===`ENOTSUP`&&t.clone!==`always`)return;throw n===`ENOTSUP`?new I(`unsupported-platform`,`native file cloning is unsupported`,{cause:e}):new I(`helper-failed`,`native file copy failed`,{cause:e})}finally{s&&(s.onabort=null)}}function assertNativeCopyCompleted(e,t){if(t?.errorCode){(t.errorCode===`Cancelled`||t.errorCode===`ABORT_ERR`)&&e.signal?.throwIfAborted();let n=[`ENOTSUP`,`EOPNOTSUPP`,`ENOSYS`,`EXDEV`,`EINVAL`].includes(t.errorCode);throw new I(t.errorCode===`too-large`?`too-large`:n?`unsupported-platform`:`helper-failed`,t.errorMessage??`native file copy failed`,{cause:Object.assign(Error(t.errorMessage??`native file copy failed`),{code:t.errorCode})})}e.signal?.throwIfAborted()}function replayPinnedInput(e,t){return t.kind===`stream`?{kind:`stream`,stageBeforePublish:!0,stream:(async function*(){let t=0,n=Buffer.alloc(65536);for(;;){let r=li(e,n,0,n.length,t);if(!r)return;t+=r,yield n.subarray(0,r)}})()}:t}const Ji=vi.isUint8Array;function streamChunkBytes(e){return Buffer.isBuffer(e)?e:Ji(e)?snapshotByteView(e):Buffer.from(e)}async function writePinnedInput(e,t,n,r){if(t.kind===`link`)throw new I(`helper-failed`,`link copying requires the link publication path`);if(t.kind===`file`){await writeCopyFileToFd(typeof e==`number`?e:e.fd,t,n,r);return}let i=0,write=async t=>{if(i+=t.byteLength,n!==void 0&&i>n)throw new I(`too-large`,`file exceeds limit of ${n} bytes (got at least ${i})`);await writeAllToFile(e,t,{assertBeforeMutation:r})};if(t.kind===`buffer`)await write(typeof t.data==`string`?Buffer.from(t.data,t.encoding??`utf8`):t.data);else for await(let e of t.stream)await write(streamChunkBytes(e))}function nativeStagedFileMode(e,t,n,r,i){if(typeof e.stagedFileMetadata!=`function`)return;let a=e.stagedFileMetadata(t,n,r);if(!a||typeof a.mode!=`bigint`||a.mode<0n||a.mode>4294967295n||typeof a.nlink!=`bigint`||a.nlink!==1n||(a.mode&61440n)!=32768n)throw new I(`path-mismatch`,`staged entry no longer names the exclusive created file`);let o=Number(a.mode&4095n);if(i!==void 0&&o!==i)throw new I(`insecure-permissions`,`filesystem did not enforce the staged file mode`);return o}const Yi=/* @__PURE__ */ new WeakMap,Xi=/* @__PURE__ */ new WeakMap;function unavailable$4(e,t,n){let r=new I(`helper-unavailable`,`native no-replace ${e} is unsupported on this filesystem (${t})`,{cause:n,details:{capability:`rename-noreplace`}});return Xi.set(r,t),r}function noReplaceUnavailable(e,t,n=!1){try{let r=e?.code;if(r!==`FS_SAFE_INTERNAL_RENAME_NOREPLACE_UNSUPPORTED`&&!(n&&[`EINVAL`,`ENOSYS`,`ENOTSUP`,`EOPNOTSUPP`].includes(r??``)))return;let i=process.platform===`darwin`?`renameatx_np RENAME_EXCL`:process.platform===`win32`?`native no-replace rename`:`renameat2 RENAME_NOREPLACE`;return unavailable$4(t,r===`FS_SAFE_INTERNAL_RENAME_NOREPLACE_UNSUPPORTED`?e.message:`${i}: ${r}`,e)}catch{return}}function rememberNoReplaceUnavailable(e,t,n){let r=Xi.get(n);if(!r)return;let i=Q.fstatSync(t,{bigint:!0}).dev,a=Yi.get(e);a||Yi.set(e,a=/* @__PURE__ */ new Map),!a.has(i)&&a.size>=128&&a.delete(a.keys().next().value),a.set(i,r)}function cachedNoReplaceUnavailable(e,t,n=`publication`){if(Yi.has(e))return cachedNoReplaceDevice(e,Q.fstatSync(t,{bigint:!0}).dev,n)}function cachedNoReplaceDevice(e,t,n){let r=Yi.get(e);if(!r)return;let i=r.get(t);return i?unavailable$4(n,i):void 0}function classifyNativeRenameFailure(e){try{let t=e?.code;if(t===`FS_SAFE_INTERNAL_RENAME_SOURCE_IDENTITY_MISMATCH`||t===`FS_SAFE_INTERNAL_RENAME_NOREPLACE_UNSUPPORTED`)return`uncommitted`}catch{}return`indeterminate`}function createStagedFileReceipt(e,t,n){return Object.freeze({directory:e,temporaryBasename:t,identity:Object.freeze({dev:n.dev,ino:n.ino,mode:Number(n.mode&4095n),nlink:n.nlink,size:n.size,uid:Number(n.uid),gid:Number(n.gid),mtimeNs:n.mtimeNs,ctimeNs:n.ctimeNs})})}function stagedFailure(e,t,n){t=noReplaceUnavailable(t,`${e} publication`)??t;let r=`helper-failed`;try{r=t instanceof I?t.code:t?.code===`EEXIST`?`already-exists`:`helper-failed`}catch{}return new I(r,r===`helper-unavailable`&&t instanceof I?t.message:`staged ${e} ${n.phase} failed`,{cause:t,details:n})}async function settleStagedFile(e){let t=e.failure?[e.failure.error]:[],n;try{n=await e.cleanup()}catch(e){n=`failed`,t.push(e)}let r=`closed`;for(let n of e.close)try{await n()}catch(e){r=`close-failed`,t.push(e)}if(n!==`failed`&&n!==`preserved`&&r!==`close-failed`&&(!e.failure||e.publication.status===`not-published`))return;let i=t.length>1?AggregateError(t,`staged operation and settlement failed`):t.length===1?t[0]:new I(`not-removable`,`staged cleanup preserved an unverified entry`),a=Object.freeze({temporaryBasename:e.temporaryBasename,publication:e.publication,status:n,resources:r});throw stagedFailure(`file`,i,{phase:e.failure?e.phase:`cleanup`,publication:e.publication,cleanup:a})}function timestampSeconds(e){return String(Number(e/1000000000n)+Number(e%1000000000n)/1e9)}function captureCopyMetadata(e,t){let restoreNative,n=P();if(process.platform===`win32`){if(n?.readCopyMetadata&&n.restoreCopyMetadata){let t=n.readCopyMetadata(e),r=n.restoreCopyMetadata.bind(n);restoreNative=e=>r(e,t)}else if(st())throw new I(`helper-unavailable`,`native Windows copy metadata preservation is unavailable`)}else if(n?.restoreCopyFileTimes){let e=n.restoreCopyFileTimes.bind(n),{atimeNs:r,mtimeNs:i}=t;restoreNative=t=>e(t,r,i)}else if(st())throw new I(`helper-unavailable`,`native copy timestamp preservation is unavailable`);return Object.freeze({atimeNs:t.atimeNs,mtimeNs:t.mtimeNs,restoreNative})}function restoreCopyMetadata(e,t){t&&(t.restoreNative?t.restoreNative(e):Q.futimesSync(e,timestampSeconds(t.atimeNs),timestampSeconds(t.mtimeNs)))}var __addDisposableResource$5=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var dispose,r;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);dispose=t[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);dispose=t[Symbol.dispose],n&&(r=dispose)}if(typeof dispose!=`function`)throw TypeError(`Object not disposable.`);r&&(dispose=function(){try{r.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose,async:n})}else n&&e.stack.push({async:!0});return t},Zi=(function(e){return function(t){function fail(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var n,r=0;function next(){for(;n=t.stack.pop();)try{if(!n.async&&r===1)return r=0,t.stack.push(n),Promise.resolve().then(next);if(n.dispose){var e=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(e).then(next,function(e){return fail(e),next()})}else r|=1}catch(e){fail(e)}if(r===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return next()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});function assertNativeStaging(e){if([e.closeOwnedFd,e.createStagedFile,e.stagedFileMatches,e.removeStagedFile,e.renameReplaceAsync,e.renameNoReplaceAsync].some(e=>typeof e!=`function`))throw new I(`helper-unavailable`,`native retained-directory staging is unavailable`)}function assertBasename(e,t){if(!e||e===`.`||e===`..`||e.includes(`/`)||e.includes(`\0`)||t&&/[\\:\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(e))throw new I(`invalid-path`,`publication requires one direct-child basename`)}const Qi=Object.freeze({status:`not-published`});var $i=class NativeStagedFile{#e;#t;#n;#r;#i;#a={status:`open`,publication:Qi};#o;#s;#c=!1;#l;#u;#d;constructor(e){let t=e.name??`.fs-safe-${oi()}.tmp`;assertBasename(t,e.portableNames!==!1),this.#t=V(e.binding),this.#e={...e,name:t},this.#n=e.assertBeforeMutation,this.#r=e.permissionPolicy===`private-creation`,this.#i=e.permissionPolicy!==void 0}static async create(e,t,n){let r;try{r=new NativeStagedFile(e)}catch(t){try{e.closeParentFd(e.parentFd)}catch(e){throw AggregateError([t,e],`staged owner construction and close failed`)}throw t}return await r.#y(t,n),r}static async write(e,t,n,r,i,a,o){let s={stack:[],error:void 0,hasError:!1};try{let c=i.overwrite===!1&&i.input.kind===`buffer`&&i.input.stageBeforePublish===!1,l=__addDisposableResource$5(s,await NativeStagedFile.create({binding:e,parentFd:t,closeParentFd:n,directory:r,mode:i.mode,sync:i.sync,portableNames:!1,assertBeforeMutation:i.assertBeforeMutation,name:c?i.basename:void 0,strictFileSync:i.strictFileSync,permissionPolicy:i.private?`private-creation`:i.verifyPosixMode===!0?`mode-only`:void 0},i.input,i.maxBytes),!0);l.#c=i.rejectFinalSymlink===!0,i.input.kind===`file`&&await i.input.verifySource(),c&&(l.#h(),i.assertBeforeMutation?.(),l.#i&&l.#h());let u;try{let e=c?l.#x(i.basename,!1,i.onPublished):l.publish(i.basename,{overwrite:i.overwrite!==!1},i.onPublished);u=e instanceof Promise?await e:e}catch(n){if(!l.#l||st()||i.input.kind===`file`&&i.input.clone===`always`)throw n;l.#u=`failed`;let r;try{r=e.removeStagedFile(t,l.#e.name,l.#p()),l.#u=r}catch(e){throw l.#d={error:e},n}if(r!==`removed`&&r!==`name-absent`)throw n;return rememberNoReplaceUnavailable(e,t,l.#l),await o(replayPinnedInput(l.#p(),i.input))}let d=u.staged.identity;try{c?await i.verifyPublished?.(l.#p(),d,a,{fd:t,binding:e}):await i.verifyPublished?.(l.#p(),d,a)}catch(e){throw i.overwrite===!1&&i.input.kind!==`file`&&i.input.stageBeforePublish===!0?stagedFailure(`file`,e,{phase:`publish`,publication:u}):e}return{dev:d.dev,ino:d.ino}}catch(e){s.error=e,s.hasError=!0}finally{let e=Zi(s);e&&await e}}get receipt(){if(!this.#o)throw new I(`helper-failed`,`staged file preparation is incomplete`);return this.#o}#f(){if(this.#a.status!==`open`)throw new I(`helper-failed`,`staged file is closed`);return this.#a}#p(){let e=this.#f();if(e.fileFd===void 0)throw new I(`helper-failed`,`staged file has not been created`);return e.fileFd}#m(e,t){let n=this.#p(),r=this.#r?void 0:nativeStagedFileMode(this.#e.binding,this.#e.parentFd,e,n,this.#i?t:void 0);if(r!==void 0)return r;let i=this.#e.binding.stagedFileMatches(this.#e.parentFd,e,n)?Q.fstatSync(n,{bigint:!0}):void 0;if(!i||i.nlink!==1n)throw new I(`path-mismatch`,`staged entry no longer names the exclusive created file`);return this.#_(n,i,t),Number(i.mode&4095n)}#h(){if(this.#f().publication.status!==`not-published`)throw new I(`helper-failed`,`staged file publication has already been attempted`);this.#g(),this.#m(this.#e.name,384)}#g(){bn(this.#e.binding,this.#e.parentFd,this.#e.directory)}#_(e,t,n){if(this.#r&&assertPrivateCreationFile(t,e),this.#i&&Number(t.mode&4095n)!==n)throw new I(`insecure-permissions`,`filesystem did not enforce the staged file mode`)}#v(e){this.#_(e,Q.fstatSync(e,{bigint:!0}),384)}async#y(e,t){try{let n=this.#e.mode;if(!Number.isInteger(n)||n<0||n>4095)throw new I(`invalid-path`,`invalid staged file mode`);let r=e.kind===`file`&&this.#i?e.signal:void 0;if(e.kind===`file`&&this.#i&&(r?.throwIfAborted(),e.clone===`always`))throw new I(`helper-unavailable`,`required cloning cannot verify staged permissions before copying`);this.#g();let i=this.#f();this.#r&&assertDarwinCreationAcl(this.#e.parentFd,`file`),this.#n?.(),this.#r&&assertDarwinCreationAcl(this.#e.parentFd,`file`);let a=e.kind===`file`&&!this.#i?await createNativeCopyFile(this.#e.binding,e,this.#e.parentFd,this.#e.name,t,Z.join(this.#e.directory.realPath,this.#e.name)):void 0;if(i.fileFd=a?.fd,i.fileFd===void 0){this.#n?.(),this.#r&&assertDarwinCreationAcl(this.#e.parentFd,`file`);try{i.fileFd=await this.#e.binding.createStagedFile(this.#e.parentFd,this.#e.name)}catch(e){throw jt(e,Z.join(this.#e.directory.realPath,this.#e.name)),e}}let o=i.fileFd;e.kind===`file`&&assertNativeCopyCompleted(e,a);let s=this.#n,c=s?.();this.#r&&(q(c,`assertBeforeMutation`),assertPrivateCreationFile(Q.fstatSync(o,{bigint:!0}),o)),Q.fchmodSync(o,384),this.#i&&this.#v(o);let l=this.#i?()=>{q(this.#n?.(),`assertBeforeMutation`),r?.throwIfAborted(),this.#v(o)}:this.#n;a||await writePinnedInput(o,e,t,l),e.kind===`file`&&restoreCopyMetadata(o,e.metadata),this.#i&&this.#v(o),this.#e.sync!==!1&&await(this.#e.strictFileSync?syncFile(o):syncFileBestEffort(o));let u=Q.fstatSync(o,{bigint:!0});this.#o=createStagedFileReceipt(this.#e.directory,this.#e.name,u),this.#h()}catch(e){let{receipt:t,error:n}=this.#S();throw n||t.status===`preserved`?stagedFailure(`file`,n?AggregateError([e,n],`preparation and cleanup failed`):e,{phase:`prepare`,publication:t.publication,cleanup:t}):e}}async assertCurrent(){this.#h()}publish(e,t,n){return this.#s?Promise.reject(stagedFailure(`file`,new I(`helper-failed`,`staged file publication is pending`),{phase:`publish`,publication:this.#a.status===`closed`?this.#a.receipt.publication:this.#a.publication})):this.#s=Promise.resolve().then(()=>this.#b(e,t,n)).finally(()=>{this.#s=void 0})}async#b(e,t,n){let r=t?.overwrite;try{let t=this.#f();if(assertBasename(e,this.#e.portableNames!==!1),e===this.#e.name||typeof r!=`boolean`)throw new I(`invalid-path`,`publication needs a distinct basename and explicit overwrite policy`);this.#h(),L(Z.join(this.#e.directory.realPath,e),this.#c),this.#n?.(),this.#n&&(this.#h(),L(Z.join(this.#e.directory.realPath,e),this.#c));try{r?await this.#e.binding.renameReplaceAsync(this.#e.parentFd,this.#e.name,this.#e.parentFd,e):await this.#e.binding.renameNoReplaceAsync(this.#e.parentFd,this.#e.name,this.#e.parentFd,e)}catch(n){t.publication=Object.freeze({status:`indeterminate`,basename:e,overwrite:r});let i=r?void 0:noReplaceUnavailable(n,`publication`,!0);throw i&&this.#a===t&&t.status===`open`?(t.publication=Qi,this.#l=i,i):(classifyNativeRenameFailure(n)===`uncommitted`&&(t.publication=Qi),n)}let i=this.#x(e,r,n);return i instanceof Promise?await i:i}catch(e){throw Dt(e)?e:stagedFailure(`file`,e,{phase:`publish`,publication:this.#a.status===`closed`?this.#a.receipt.publication:this.#a.publication})}}#x(e,t,n){let r=Object.freeze({status:`published`,staged:this.receipt,basename:e,overwrite:t});this.#f().publication=r,n?.(r.staged.identity);let i=this.#m(e,384);this.#g();let a=this.#p();(this.#e.mode!==384||i!==384)&&Q.fchmodSync(a,this.#e.mode);let verify=()=>(this.#m(e,this.#e.mode),this.#g(),r);return this.#e.sync===!1?verify():Promise.resolve().then(async()=>(((this.#e.mode&384)!=384||(i&~this.#e.mode)!==0)&&await(this.#e.strictFileSync?syncFile(a):syncFileBestEffort(a)),await syncFileBestEffort(this.#e.parentFd),verify()))}#S(){if(this.#a.status===`closed`)return this.#a;let e=this.#f();e.status=`closing`;let t=`not-needed`,n=[];if(e.publication.status===`indeterminate`)t=`preserved`;else if(this.#u)t=this.#u,this.#d&&n.push(this.#d.error);else if(e.publication.status===`not-published`&&e.fileFd!==void 0)try{t=this.#e.binding.removeStagedFile(this.#e.parentFd,this.#e.name,e.fileFd)}catch(e){t=`failed`,n.push(e)}let r=`closed`;for(let[t,i]of[[e.fileFd,this.#t],[this.#e.parentFd,this.#e.closeParentFd]])if(t!==void 0)try{i(t)}catch(e){r=`close-failed`,n.push(e)}let i=Object.freeze({temporaryBasename:this.#e.name,publication:e.publication,status:t,resources:r}),a=n.length?stagedFailure(`file`,n.length===1?n[0]:AggregateError(n,`staged cleanup failed`),{phase:`cleanup`,publication:e.publication,cleanup:i}):void 0;return this.#a={status:`closed`,receipt:i,error:a},this.#a}async cleanup(){this.#s&&await this.#s.catch(()=>{});let e=this.#S();if(e.error)throw e.error;return e.receipt}async[Symbol.asyncDispose](){let e=await this.cleanup();if(e.status===`preserved`)throw new I(`not-removable`,`staged cleanup preserved an unverified entry`,{details:{phase:`cleanup`,publication:e.publication,cleanup:e}})}};$i.create;const ea=$i.write,ta=/* @__PURE__ */ new WeakMap;function registerRootHandleContext(e,t){ta.set(e,t)}function directoryOpenFlags(){return process.platform===`win32`?`r`:Q.constants.O_RDONLY|Q.constants.O_DIRECTORY|Q.constants.O_NOFOLLOW|Q.constants.O_NONBLOCK}function isWindowsDirectorySyncUnsupported(e){if(process.platform!==`win32`)return!1;let t=e.code;return t===`EACCES`||t===`EINVAL`||t===`EISDIR`||t===`ENOSYS`||t===`ENOTSUP`||t===`EPERM`}function isWindowsDirectoryOpenUnsupported(e){if(process.platform!==`win32`)return!1;let t=e.code;return t===`EINVAL`||t===`EISDIR`||t===`ENOSYS`||t===`ENOTSUP`}function unsupportedOutcome(e){let t=e.code;return t?{status:`unsupported`,code:t}:{status:`unsupported`}}async function createDirectoryReceipt(e,t){return cn(e,t,O.native)}async function assertDirectoryReceiptCurrent(e,t){mn(e,t,O.native)}function assertOpenDirectoryIdentity(e,t,n){z(()=>{let r=Q.fstatSync(e,{bigint:!0});if(!r.isDirectory())throw new I(`not-file`,`${n} must be a real directory: ${t.path}`);return r},wn(t).identity)}async function assertOpenDirectoryCurrent(e,t,n){assertOpenDirectoryIdentity(e.fd,t,n),await assertDirectoryReceiptCurrent(t,n)}var PinnedDirectoryImpl=class{receipt;#e;#t;#n;#r=!1;constructor(e,t,n){this.#t=e,this.#e=t,this.receipt=Tn(t),this.#n=n}async assertCurrent(){if(this.#r)throw new I(`helper-failed`,`${this.#n} pin is already closed`);await assertOpenDirectoryCurrent(this.#t,this.#e,this.#n)}async sync(){await this.assertCurrent();try{await this.#t.sync()}catch(e){if(!isWindowsDirectorySyncUnsupported(e))throw e;return await this.assertCurrent(),unsupportedOutcome(e)}return await this.assertCurrent(),{status:`synced`}}async close(){this.#r||(this.#r=!0,await this.#t.close())}};async function pinDirectory(e,t={}){let n=t.label??`directory`,r=typeof e==`string`?await createDirectoryReceipt(e,n):fn(e);await assertDirectoryReceiptCurrent(r,n);let i=await $.open(D(r.path),directoryOpenFlags());try{return await assertOpenDirectoryCurrent(i,r,n),new PinnedDirectoryImpl(i,r,n)}catch(e){throw await i.close().catch(()=>void 0),e}}async function syncDirectory(e,t={}){let n=t.label??`directory`,r=typeof e==`string`?await createDirectoryReceipt(e,n):fn(e),i;try{i=await pinDirectory(r,{label:n})}catch(e){if(!isWindowsDirectoryOpenUnsupported(e))throw e;return await assertDirectoryReceiptCurrent(r,n),unsupportedOutcome(e)}try{return await i.sync()}finally{await i.close()}}function syncDirectorySync(e,t={}){let n=t.label??`directory`,r=typeof e==`string`?cn(e,n):fn(e);mn(r,n);let i;try{i=Q.openSync(D(r.path),directoryOpenFlags())}catch(e){if(!isWindowsDirectoryOpenUnsupported(e))throw e;return mn(r,n),unsupportedOutcome(e)}try{assertOpenDirectoryIdentity(i,r,n),mn(r,n);try{Q.fsyncSync(i)}catch(e){if(!isWindowsDirectorySyncUnsupported(e))throw e;return mn(r,n),unsupportedOutcome(e)}return mn(r,n),{status:`synced`}}finally{Q.closeSync(i)}}async function syncDirectoryBestEffort(e){await syncDirectory(e).catch(()=>void 0)}async function readCopyLinkTarget(e){return await $.readlink(e,{encoding:`buffer`})}function assertCopyLinkAvailable(){let e=P();if(process.platform===`darwin`&&!e?.createCopySymlink)throw new I(`helper-unavailable`,`exclusive macOS link copying requires the native helper; link(2) follows its source`);if(process.platform===`win32`&&(!e?.copyLinkExclusive||!e.publishCopyLink||!e.removeCopyLink))throw new I(`helper-unavailable`,`copying Windows links without following them requires the native helper`);if(e&&process.platform!==`win32`&&!e.createCopySymlink)throw new I(`helper-unavailable`,`native link copying is unavailable`)}async function admitCopyLink(e,t,n){let r=await F(Z.dirname(e),{bigint:!0});e=Z.join(r.realPath,Z.basename(e));let i=Q.lstatSync(e,{bigint:!0});if(!i.isSymbolicLink())return;let a=process.platform===`win32`?void 0:await readCopyLinkTarget(e),verifySource=async()=>{n?.throwIfAborted(),await A(r);let t=z(()=>Q.lstatSync(e,{bigint:!0}),i);if(!t.isSymbolicLink()||t.mtimeNs!==i.mtimeNs||t.ctimeNs!==i.ctimeNs)throw new I(`path-mismatch`,`copy source link changed`)};return await verifySource(),{kind:`link`,stageBeforePublish:!0,sourcePath:e,identity:i,target:a,preserveMetadata:t,signal:n,verifySource}}async function copyLinkAtParent(e,t,n,r){let i=`.fs-safe-${oi()}.tmp`,a=Z.join(n.realPath,i),o=Z.join(n.realPath,e.basename),s,c,l,assertStage=()=>{W(n);let e=z(()=>Q.lstatSync(a,{bigint:!0}),s);if(!e.isSymbolicLink()||e.nlink!==1n)throw new I(`path-mismatch`,`copy link stage changed`)};try{if(await t.verifySource(),await A(n),process.platform===`win32`){if(!r?.binding.copyLinkExclusive)throw new I(`helper-unavailable`,`native Windows link copying is unavailable`);let a=await F(Z.dirname(t.sourcePath),{bigint:!0});c=await $.open(a.realPath,Q.constants.O_RDONLY),z(()=>Q.fstatSync(c.fd,{bigint:!0}),a.stat),await t.verifySource(),e.assertBeforeMutation?.(),W(n),s=r.binding.copyLinkExclusive(c.fd,Z.basename(t.sourcePath),r.fd,i,t.identity.dev,t.identity.ino,t.preserveMetadata,e.mode)}else{if(r&&!r.binding.createCopySymlink)throw new I(`helper-unavailable`,`native link copying is unavailable`);if(e.assertBeforeMutation?.(),W(n),r?.binding.createCopySymlink){let n=r.binding.createCopySymlink(r.fd,i,t.target,e.mode,t.preserveMetadata?t.identity.atimeNs:void 0,t.preserveMetadata?t.identity.mtimeNs:void 0);if(s={dev:pe(n.dev),ino:pe(n.ino)},n.errorCode)throw Object.assign(Error(n.errorMessage),{code:n.errorCode})}else Q.symlinkSync(t.target,a),s=Q.lstatSync(a,{bigint:!0});!r&&t.preserveMetadata&&(assertStage(),Q.lutimesSync(a,timestampSeconds(t.identity.atimeNs),timestampSeconds(t.identity.mtimeNs)))}if(assertStage(),await t.verifySource(),e.assertBeforeMutation?.(),t.signal?.throwIfAborted(),assertStage(),process.platform===`win32`)r.binding.publishCopyLink(r.fd,i,e.basename,s.dev,s.ino);else if(r){let t=r.binding.renameNoReplace;if(!t)throw new I(`helper-unavailable`,`native link publication is unavailable`);try{t(r.fd,i,r.fd,e.basename)}catch(e){if(!noReplaceUnavailable(e,`link copy publication`,!0)||st()||process.platform!==`linux`)throw e;assertStage(),Q.linkSync(a,o)}}else Q.linkSync(a,o);if(e.onPublished?.(s),W(n),!z(()=>Q.lstatSync(o,{bigint:!0}),s).isSymbolicLink())throw new I(`path-mismatch`,`published copy link changed`);return e.sync!==!1&&await syncDirectoryBestEffort(n.realPath),await t.verifySource(),s}catch(e){throw l={error:e},e}finally{let e;try{if(s){W(n);let e=Q.lstatSync(a,{bigint:!0,throwIfNoEntry:!1});if(e){if(z(()=>e,s),!e.isSymbolicLink())throw new I(`path-mismatch`,`copy link cleanup identity changed`);process.platform===`win32`?r.binding.removeCopyLink(r.fd,i,s.dev,s.ino):Q.unlinkSync(a)}}}catch(t){e={error:t}}try{await c?.close()}catch(t){e={error:e?K(t,e.error,`copy link cleanup and close failed`):t}}if(e)throw l?K(e.error,l.error,`copy link operation and cleanup failed`):e.error}}function foldedName(e){return e.normalize(`NFD`).replace(/[^\u0131]+/gu,e=>e.toLowerCase().toUpperCase().toLowerCase()).normalize(`NFC`)}function asciiCasePair(e,t){return/^[\x00-\x7f]*$/.test(e)&&/^[\x00-\x7f]*$/.test(t)&&e.toLowerCase()===t.toLowerCase()}function createMutationDenyMatcher(){let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,observe=t=>(e.has(t)||e.set(t,un(t)),e.get(t)),prospectiveInside=(e,n)=>{let r=Z.parse(e).root;if(r!==Z.parse(n).root)return!1;let i=e.slice(r.length).split(Z.sep),a=n.slice(r.length).split(Z.sep).slice(0,i.length);if(i.length!==a.length||!i.every((e,t)=>foldedName(e)===foldedName(a[t]))||i.every((e,t)=>e===a[t]))return!1;let o=Z.join(r,...a),s=observe(e),c=observe(o);if(!s||!c)return!0;if(s.canonicalAncestor!==c.canonicalAncestor||s.missingSegments.length===0||s.missingSegments.length!==c.missingSegments.length)return!1;let l=s.missingSegments,u=c.missingSegments;if(!l.every((e,t)=>foldedName(e)===foldedName(u[t])))return!1;let d=l.findIndex((e,t)=>e!==u[t]);return d===-1||!(d===0&&asciiCasePair(l[0],u[0])&&(t.has(s.canonicalAncestor)||t.set(s.canonicalAncestor,probePathCaseInsensitiveSync(Z.join(s.canonicalAncestor,l[0]),{allowTemporaryProbe:!1})),t.get(s.canonicalAncestor)===!1))};return(e,t,n,r=!1)=>k(t,e)&&(n||k(e,t))||r&&k(e,t)?!0:(n||e.split(Z.sep).length===t.split(Z.sep).length)&&prospectiveInside(t,e)||r&&prospectiveInside(e,t)}function resolveMutationComparablePaths(e){ht(e,`path contains a NUL byte`),w(e,`filesystem`,`mutation path uses a Windows filesystem namespace alias`);let t=Ce(e);w(t,`filesystem`,`mutation path uses a Windows filesystem namespace alias`);let n=C(t,`native`);return w(n,`filesystem`,`mutation path uses a Windows filesystem namespace alias`),/* @__PURE__ */ new Set([t,n])}function strictMutationComparablePaths(e){let t=Ce(e);w(t,`filesystem`,`mutation path uses a Windows filesystem namespace alias`);let n=t,r=Z.parse(t).root;for(;n!==r;)try{Q.lstatSync(D(n));break}catch(e){if(!E(e))throw e;n=Z.dirname(n)}let i=O.native(D(n));w(i,`filesystem`,`mutation path uses a Windows filesystem namespace alias`);let a=n===t?i:Z.resolve(i,`.${Z.sep}${t.slice(n.length)}`);return w(a,`filesystem`,`mutation path uses a Windows filesystem namespace alias`),Z.relative(Z.resolve(t),Z.resolve(a))===``?[t]:[t,a]}function policyPathEntries(e,t){let n=[];for(let r of e??[]){if(t&&(!r||!Z.isAbsolute(r)))throw new I(`invalid-path`,`deny mutation paths must be non-empty absolute paths`);if(r.length===0)throw new I(`invalid-path`,`deny mutation paths must be non-empty`);if(ht(r,`deny mutation path contains a NUL byte`),w(r,`filesystem`,`deny mutation path uses a Windows filesystem namespace alias`),!t&&!Z.isAbsolute(r))throw new I(`invalid-path`,`deny mutation paths must be absolute`);n.push(t?Ce(r):r)}return n}function assertMutationNotDenied(e,t,n={},r=`root`){if(!t?.paths?.length&&!t?.prefixes?.length)return;let i=r===`sync-root-lock`,a=i?strictMutationComparablePaths:resolveMutationComparablePaths,o=a(e),s=createMutationDenyMatcher();for(let e of[`paths`,`prefixes`])for(let r of policyPathEntries(t[e],i)){let t=a(r);for(let r of o)for(let i of t)if(s(r,i,e===`prefixes`,n.protectAncestors))throw new I(`denied-path`,`path is denied by denyMutations policy`)}}function mergeDenyMutationPolicies(e,t){return e?t?{paths:[...e.paths??[],...t.paths??[]],prefixes:[...e.prefixes??[],...t.prefixes??[]]}:e:t}function sameNativeIdentity(e,t){return ut(e)&&ut(t)&&BigInt(e.dev)===BigInt(t.dev)&&BigInt(e.ino)===BigInt(t.ino)}function unavailable$3(e){return new I(`helper-unavailable`,e)}function assertParentAdmissionAvailable(e){if(typeof e.openBeneath!=`function`)throw unavailable$3(`native parent directory admission is unavailable`);V(e),se(e,`openBeneath`)}function openExactNativeRootSync(e,t){assertParentAdmissionAvailable(e),w(t.rootPath,`filesystem`,`native root uses a Windows filesystem namespace alias`);let n=(Et()?.flags??Q.constants.O_RDONLY)|(Q.constants.O_DIRECTORY??0),r=Q.openSync(D(t.rootPath),n),i=!0,close=()=>{i&&(i=!1,Q.closeSync(r))};try{let e=z(()=>Q.fstatSync(r,{bigint:!0}),t.rootIdentity);if(!e.isDirectory())throw new I(`path-mismatch`,`native root is not a directory`);return{fd:r,stat:e,close,[Symbol.dispose]:close}}catch(e){try{close()}catch(t){throw K(t,e,`native root admission and close failed`)}throw e}}function openExactNativeRootAdmissionSync(e,t){return{directoryFlags:(Et()?.flags??Q.constants.O_RDONLY)|(Q.constants.O_DIRECTORY??0),exactRoot:!0,reportCloseErrors:t.reportCloseErrors,operation:t.operation,root:openExactNativeRootSync(e,t),rootPath:t.rootPath}}function borrowNativeRootParent(e){let t={dir:e.rootPath,realPath:e.rootPath,stat:e.root.stat};return W(t),{fd:e.root.fd,guard:t,close(){}}}async function openNativeRootAdmission(e,t){assertParentAdmissionAvailable(e);let n=(t.searchOnly?Et()?.flags??Q.constants.O_RDONLY:Q.constants.O_RDONLY)|(Q.constants.O_DIRECTORY??0);w(t.rootPath,`filesystem`,`native root uses a Windows filesystem namespace alias`);let r=Q.openSync(D(t.rootPath),n),close=async()=>{if(r<0)return;let e=r;r=-1,Q.closeSync(e)},i={get fd(){return r},close,[Symbol.asyncDispose]:close};try{let e=typeof t.rootIdentity?.dev==`bigint`&&typeof t.rootIdentity.ino==`bigint`,r;if(e)z(()=>Q.fstatSync(i.fd,{bigint:!0}),t.rootIdentity),r=!0;else if(process.platform===`win32`){let e=Q.fstatSync(i.fd,{bigint:!0});r=!t.rootIdentity||sameNativeIdentity(t.rootIdentity,e)}else{let e=Q.fstatSync(i.fd,{bigint:!0});r=!t.rootIdentity||vn(t.rootIdentity,e)}if(!r)throw new I(`path-mismatch`,`root path changed during ${t.operation??`native admission`}`);return{directoryFlags:n,exactRoot:e,reportCloseErrors:t.reportCloseErrors,operation:t.operation??`native admission`,root:i,rootPath:t.rootPath}}catch(e){try{await i.close()}catch(n){if(process.platform!==`win32`||t.reportCloseErrors)throw K(n,e,`native root admission and close failed`)}throw e}}async function openNativeParentAdmission(e,t,n,r){assertParentAdmissionAvailable(e);let i=V(e),a=t.directoryFlags??Q.constants.O_RDONLY|(Q.constants.O_DIRECTORY??0);w(n,`relative`,`native parent uses a Windows filesystem namespace alias`);let o=e.openBeneath(t.root.fd,n,a);if(!o||!Number.isInteger(o.fd)||o.fd<0)throw unavailable$3(`native parent directory admission did not provide a descriptor`);let s=o.fd;try{let a=n?Z.join(t.rootPath,...n.split(`/`)):t.rootPath;if((r===`native-directory`||r===`native-publication`)&&process.platform===`win32`&&t.exactRoot&&typeof e.observeDirectory==`function`){let t=z(()=>Q.fstatSync(s,{bigint:!0})),n;try{n=ye(e,a,t)}catch(e){if(e?.code!==`OBSERVATION_UNAVAILABLE`)throw e}if(n)return w(n.realPath,`filesystem`,`native parent uses a Windows filesystem namespace alias`),B(n.realPath,t,t),{fd:s,close:()=>i(s),guard:{dir:n.realPath,realPath:n.realPath,stat:t}}}let o=O.native(D(a));if(w(o,`filesystem`,`native parent uses a Windows filesystem namespace alias`),r===`native-publication`&&process.platform!==`win32`&&t.exactRoot){let t=En(e,s,o);return{fd:s,close:()=>i(s),guard:{dir:o,realPath:o,stat:t.stat},stagedDirectory:t.directory}}if(r===`native-directory`&&process.platform!==`win32`&&t.exactRoot){let t=Cn(s,o,e);return t.disposeObservation?.(),{fd:s,close:()=>i(s),guard:{dir:o,realPath:o,stat:t.stat},stagedDirectory:t.directory}}let c=process.platform===`win32`?void 0:Sn(s,o),l=t.exactRoot?await Pe(o,z(()=>Q.fstatSync(s,{bigint:!0}))):Q.lstatSync(D(o),{bigint:!0});if(process.platform===`win32`&&!t.exactRoot){let e=Q.fstatSync(s,{bigint:!0});if(l.isSymbolicLink()||!sameNativeIdentity(l,e))throw new I(`path-mismatch`,`${t.operation} parent changed during resolution`)}else if(process.platform!==`win32`&&(l.isSymbolicLink()||!vn(l,c.identity)))throw new I(`path-mismatch`,`${t.operation} parent changed during resolution`);return{fd:s,close:()=>i(s),guard:{dir:o,realPath:o,stat:l},stagedDirectory:c}}catch(e){try{i(s)}catch(n){if(process.platform!==`win32`||t.reportCloseErrors)throw K(n,e,`native parent admission and close failed`)}throw e}}function assertWindowsPolicyParentCurrent(e){z(()=>Q.fstatSync(e.fd,{bigint:!0}),e.guard.stat),Re(e.guard.dir,{dev:e.guard.stat.dev,ino:e.guard.stat.ino,realPath:e.guard.realPath})}function closeWindowsPolicyParentAfterFailure(e,t,n,r=!1){try{e(t)}catch(e){if(r)throw n?K(e,n.error,`native parent admission and close failed`):e}}function windowsParentObservation(e,t,n){return An(n.dir,n.realPath,n.stat,typeof e.observeDirectory==`function`?()=>{let r=z(()=>Q.fstatSync(t,{bigint:!0}),n.stat),i;try{i=ye(e,n.dir,r)}catch(e){if(e?.code===`OBSERVATION_UNAVAILABLE`)return;throw e}return{canonicalPath:i.realPath,identity:{dev:r.dev,ino:r.ino,mode:r.mode,nlink:r.nlink}}}:void 0)}async function openWindowsPolicyParent(e,t,n,r,i,a){try{let t=await openNativeParentAdmission(e,{...n,root:{fd:r},rootPath:i,exactRoot:!0},a,`native-directory`),o={...t.guard,stat:t.guard.stat};return{fd:t.fd,guard:o,observation:windowsParentObservation(e,t.fd,o)}}catch(e){throw S(e)?new I(t.mutationAdmission.rejectParentSymlinks?`symlink`:`path-mismatch`,`native write parent changed during policy admission`,{cause:e instanceof Error?e:void 0}):e}}function sameAbsolutePath(e,t){return Z.relative(Z.resolve(e),Z.resolve(t))===``}function createPathSegmentRoute(e){let t=Array(e.length+1),n=0;for(let r=0;r<e.length;r+=1)t[r]=n,n+=e[r].length,r+1<e.length&&(n+=Z.sep.length);return t[e.length]=n,Object.freeze({joined:e.join(Z.sep),offsets:Object.freeze(t)})}function joinPathSegmentRoute(e,t,n,r){let i=t.offsets[n];if(i===void 0)throw RangeError(`path segment offset is outside the route`);let a=t.joined.slice(i);return a?r===void 0?Z.join(e,a):Z.join(e,a,r):r===void 0?e:Z.join(e,r)}const na=/* @__PURE__ */ new WeakMap;function canReuseParentWithMutationAssertion(e,t,n){if(e===void 0)return!0;let r=na.get(e);return r?.rootPath===t&&r.targetPath===n}function unsupportedSpelling(){return new I(`path-alias`,`Windows compatibility writes require lower-case ASCII destination components`)}function effectiveDestination(e,t,n){let r,i;try{r=O.native(t)}catch(n){if(!E(n))throw n;let a=t,o=[];for(;;)try{Q.lstatSync(a);break}catch(t){if(!E(t)||a===e)throw t;let n=Z.dirname(a);if(n===a)throw t;o.unshift(Z.basename(a)),a=n}let s=O.native(a);r=Z.join(s,...o),o.length>1&&Z.resolve(s)===s&&o.every(e=>/^[a-z0-9._-]+$/.test(e)&&e!==`.`&&e!==`..`&&!e.endsWith(`.`))&&(i=Object.freeze({parentPath:s,parts:Object.freeze(o),nextIndex:0}))}let a=M({rootPath:e,candidatePath:r,rootIdentity:n});if(!a)throw unsupportedSpelling();let o=a.relativePath;if(!o||!o.split(Z.sep).every(e=>/^[a-z0-9._-]+$/.test(e)&&!e.endsWith(`.`)))throw unsupportedSpelling();return{path:a.path,missing:a.admission===`exact`&&a.path===r?i:void 0}}function observeMissingDestination(e){if(!(e.parts.length-e.nextIndex<2))try{let t=e.parentPath,n=B(t);for(let r=e.nextIndex;r<e.parts.length;r++){let i=Z.join(t,e.parts[r]),a;try{a=Q.lstatSync(i,{bigint:!0})}catch(a){if(!j(a,`ENOENT`)||O.native(t)!==t)return;B(t,n);try{Q.lstatSync(i)}catch(n){return!j(n,`ENOENT`)||O.native(t)!==t?void 0:Object.freeze({parentPath:t,parts:e.parts,nextIndex:r})}return}if(r===e.parts.length-1)return;n=B(i,void 0,a),t=i}}catch{}}function assertRootFallbackWritePath(e,t){if(e!==void 0&&t!==e)throw new I(`path-mismatch`,`compatibility write destination changed after lock selection`)}function createRootWriteLockBinding(e){let{rootPath:t}=e,n=e.rootIdentity&&Object.freeze({dev:e.rootIdentity.dev,ino:e.rootIdentity.ino}),r=effectiveDestination(t,e.targetPath,n),i=r.path,a=r.missing,o=Z.relative(t,i),s=!0,assertCurrent=()=>{if(!s)throw new I(`path-mismatch`,`compatibility lock observation expired`);let e=a&&observeMissingDestination(a);if(e){a=e;return}a=void 0;let r=effectiveDestination(t,i,n);assertRootFallbackWritePath(i,r.path),a=r.missing};return na.set(assertCurrent,Object.freeze({rootPath:t,targetPath:i})),Object.freeze({targetPath:i,relativePath:o,relativeLockPath:o.split(Z.sep).join(`/`),assertCurrent,dispose(){s=!1,a=void 0,na.delete(assertCurrent)}})}var __addDisposableResource$4=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var dispose,r;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);dispose=t[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);dispose=t[Symbol.dispose],n&&(r=dispose)}if(typeof dispose!=`function`)throw TypeError(`Object not disposable.`);r&&(dispose=function(){try{r.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose,async:n})}else n&&e.stack.push({async:!0});return t},ra=(function(e){return function(t){function fail(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var n,r=0;function next(){for(;n=t.stack.pop();)try{if(!n.async&&r===1)return r=0,t.stack.push(n),Promise.resolve().then(next);if(n.dispose){var e=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(e).then(next,function(e){return fail(e),next()})}else r|=1}catch(e){fail(e)}if(r===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return next()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});function mkdirPosixPolicyChild(e,t,n){if(!n||n===`.`||n===`..`||n.includes(`/`)||n.includes(`\0`)||process.platform===`win32`&&n.includes(`\\`))throw new I(`invalid-path`,`native parent creation requires one direct-child basename`);let r=e.mkdirChildBeneath;if(typeof r==`function`){let i=r.call(e,t,n,511);if(typeof i==`boolean`)return i}return se(e,`mkdirBeneath`),e.mkdirBeneath(t,n,511),!1}function normalizePosixParentOpenError(e,t){return S(e)?t.mutationAdmission?.rejectParentSymlinks?new I(`symlink`,`symlink path component not allowed`,U(e)):new I(`path-mismatch`,`native write parent changed during policy admission`,U(e)):e}async function describePosixParent(e,t){let n=O.native(t),r=Sn(e,n),i=await Pe(n,r.identity);return{fd:e,guard:{dir:n,realPath:n,stat:i},stagedDirectory:r,observation:An(n,r.realPath,i)}}function tryDescribePolicyPosixParent(e,t,n){try{let r=Cn(t,n,e);return{fd:t,guard:{dir:r.directory.realPath,realPath:r.directory.realPath,stat:r.stat},stagedDirectory:r.directory,observation:r.observation,policyDirectory:r}}catch(e){if(!(e instanceof I)||e instanceof pn||e.code!==`path-mismatch`&&e.code!==`not-file`)throw e;return}}async function capturePolicyAwareNativeParent(e,t,n,r,i,a=!1){let o={stack:[],error:void 0,hasError:!1};try{se(e,`openBeneath`);let s=n.root.fd,c=V(e),l=r?void 0:/* @__PURE__ */ new Map,disposeObservation=e=>{let t=l?.get(e);l?.delete(e),t?.()};__addDisposableResource$4(o,{[Symbol.dispose](){for(let e of l?.values()??[])e()}},!1);let capturePolicyParent=(t,n)=>{let r=tryDescribePolicyPosixParent(e,t,n),i=r?.policyDirectory?.disposeObservation;return i&&l.set(t,i),r},assertCurrent=e=>r?assertWindowsPolicyParentCurrent(e):e.policyDirectory?xn(e.policyDirectory):Dn(e.stagedDirectory),closeAfterFailure=(e,t)=>{disposeObservation(e),r?closeWindowsPolicyParentAfterFailure(c,e,t,n.reportCloseErrors):c(e)},u;async function authorize(e){let n=Object.freeze(e);return await(u?u.authorize(n):r?t.mutationAdmission.authorize(n):t.mutationAdmission?.authorize(n))}let d=r?void 0:t.relativeParentPath.split(`/`).filter(Boolean),f=d&&createPathSegmentRoute(d),p=f&&joinPathSegmentRoute(t.rootPath,f,0,t.basename),m=d?.length?Z.join(t.rootPath,...d):t.rootPath,h=r?void 0:t.mutationAdmission?.beginParentWalk?.();h&&!sameAbsolutePath(h,p)&&(h=void 0);let g,_;try{r?(g=await openWindowsPolicyParent(e,t,n,s,t.rootPath,t.relativeParentPath),_=g.fd):_=e.openBeneath(s,t.relativeParentPath,i).fd}catch(e){if(e?.code!==`ENOENT`||!t.mkdir)throw r?e:(await authorize({targetPath:p,mutationPath:p,phase:`parent`}),normalizePosixParentOpenError(e,t))}if(_!==void 0)try{g??=h?capturePolicyParent(_,m):void 0,g||=(h=void 0,await describePosixParent(_,m));let e=Z.join(g.guard.realPath,t.basename);return await authorize({targetPath:e,mutationPath:e,phase:`parent`}),assertCurrent(g),g}catch(e){throw closeAfterFailure(_,{error:e}),e}d??=t.relativeParentPath.split(`/`).filter(Boolean),f??=createPathSegmentRoute(d);let v;if(r){let n=B(t.rootPath,z(()=>Q.fstatSync(s,{bigint:!0}))),r={dir:t.rootPath,realPath:t.rootPath,stat:n};v={fd:s,guard:r,observation:windowsParentObservation(e,s,r)}}else{let e=h?capturePolicyParent(s,t.rootPath):void 0;e||(h=void 0),v=e??await describePosixParent(s,t.rootPath)}let y,b=t.rootPath,x;p??=joinPathSegmentRoute(t.rootPath,f,0,t.basename),r&&canReuseParentWithMutationAssertion(t.assertBeforeMutation,t.rootPath,p)&&(u=t.mutationAdmission?.beginNativeParentWalk?.()??t.mutationAdmission?.beginSharedParentWalk?.(),u&&u.retainedTargetPath!==p&&(u.dispose(),u=void 0));let S=i|(Q.constants.O_NOFOLLOW??0);try{if(!r){let e=h??p;await authorize({targetPath:e,mutationPath:e,phase:`parent`}),assertCurrent(v)}for(let i=0;i<d.length;i+=1){let o=d[i],s=r?void 0:Z.join(b,o),l,p,m=!1,g;try{r?(l=await openWindowsPolicyParent(e,t,n,v.fd,b,o),p=l.fd):p=e.openBeneath(v.fd,o,S).fd}catch(c){if(!(r?c?.code===`ENOENT`:E(c)))throw r?c:normalizePosixParentOpenError(c,t);let d=(r?u?.retainedTargetPath:h)??joinPathSegmentRoute(b,f,i,t.basename);s??=Z.join(b,o);let _=Object.freeze({targetPath:d,mutationPath:s,phase:`parent-create`});if(g=r?u?.tryAuthorizeAtParent(_,v.observation):t.mutationAdmission?.tryAuthorizeAtParent?.(_,v.observation),g||(g=await authorize(r?{..._}:_),assertCurrent(v)),r?t.assertBeforeMutation&&(t.assertBeforeMutation(),assertCurrent(v)):(t.assertBeforeMutation?.(),assertCurrent(v)),r){let r=e.mkdirChildBeneath;if(typeof r!=`function`)throw new I(`helper-unavailable`,`native direct-child parent creation is unavailable`);m=r.call(e,v.fd,o,511)===!0,l=await openWindowsPolicyParent(e,t,n,v.fd,b,o),p=l.fd}else if(a&&e.mkdirOpenChildBeneath)try{let t=e.mkdirOpenChildBeneath(v.fd,o,511,S);p=t.fd,m=t.created}catch(e){throw normalizePosixParentOpenError(e,t)}else{m=mkdirPosixPolicyChild(e,v.fd,o);try{p=e.openBeneath(v.fd,o,S).fd}catch(e){throw normalizePosixParentOpenError(e,t)}}}try{l||(l=h?capturePolicyParent(p,s):void 0,l||=(h=void 0,await describePosixParent(p,s)),sameAbsolutePath(l.guard.realPath,s)||(h=void 0));let n=r?joinPathSegmentRoute(l.guard.realPath,f,i+1,t.basename):void 0;u&&n!==u.retainedTargetPath&&(u.dispose(),u=void 0);let a;if(m&&g&&(r?u:t.mutationAdmission?.advanceCreatedDirectory)){let n;try{let t=r?windowsParentObservation(e,v.fd,{...v.guard,stat:z(()=>Q.fstatSync(v.fd,{bigint:!0}),v.guard.stat)}):v.policyDirectory?jn(v.policyDirectory):An(b,v.stagedDirectory.realPath,Dn(v.stagedDirectory));n=Object.freeze({admission:g,parent:t,child:l.observation})}catch{}n&&(a=r?u.advanceCreatedDirectory(n):t.mutationAdmission.advanceCreatedDirectory(n))}let o=n??h??joinPathSegmentRoute(l.guard.realPath,f,i+1,t.basename);if(!r||!a){let e={targetPath:o,mutationPath:o,phase:`parent`};r||(Object.freeze(e),m&&(a??=t.mutationAdmission?.tryAuthorizeAtParent?.(e,l.observation))),a||(await authorize(e),assertCurrent(l))}}catch(e){throw closeAfterFailure(p,{error:e}),e}let _=y;disposeObservation(v.fd),v=l,y=l.fd,b=l.guard.realPath,_!==void 0&&c(_)}if(y===void 0)throw new I(`path-mismatch`,`native write parent admission did not complete`);return y=void 0,v}catch(e){throw x={error:e},e}finally{u?.dispose(),y!==void 0&&closeAfterFailure(y,x)}}catch(e){o.error=e,o.hasError=!0}finally{ra(o)}}function windowsReservedDeviceSegment(e){let t=e.indexOf(`.`),n=e.slice(0,t<0?e.length:t).toUpperCase();return ie.has(n)}function ordinaryWindowsSegments(e){return e===``||e.includes(`/`)||e.includes(`\0`)?!1:e.split(`\\`).every(e=>me(e,{allowDotPrefix:!0})&&!e.endsWith(`.`)&&!e.endsWith(` `)&&!windowsReservedDeviceSegment(e))}function ordinaryPosixSegments(e){return e!==``&&!e.includes(`\\`)&&e.split(`/`).every(e=>me(e,{allowDotPrefix:!0}))}function exactNonzeroRootIdentity(e){return typeof e?.dev==`bigint`&&typeof e.ino==`bigint`&&e.dev!==0n&&e.ino!==0n?Object.freeze({dev:e.dev,ino:e.ino}):void 0}function ordinarySharedAbsoluteInsideRoot(e,t,n){if(!Z.isAbsolute(t)||t.includes(`\0`)||Z.resolve(t)!==t||(process.platform===`win32`?t.startsWith(`\\\\`)||t.includes(`/`):t.includes(`\\`)))return!1;let r=M({rootPath:e,candidatePath:t,rootIdentity:n});return r?.admission===`exact`&&r.path===t&&(r.relativePath===``||(process.platform===`win32`?ordinaryWindowsSegments(r.relativePath):ordinaryPosixSegments(r.relativePath)))}function simpleSharedRoute(e){if(process.versions.bun||e.policy.mutationSymlinks!==`reject`||!e.originalPath||e.originalPath.startsWith(`~`)||Z.isAbsolute(e.originalPath)||!(process.platform===`win32`?ordinaryWindowsSegments(e.originalPath)&&!e.rootReal.startsWith(`\\\\`)&&!e.rootReal.includes(`/`):ordinaryPosixSegments(e.originalPath)&&!e.rootReal.includes(`\\`))||Z.resolve(e.rootReal)!==e.rootReal)return;let t=exactNonzeroRootIdentity(e.rootIdentity);if(!t)return;let n=Z.resolve(e.rootReal,e.originalPath);if(n===e.selectedTarget&&ordinarySharedAbsoluteInsideRoot(e.rootReal,n,t)&&![...e.policy.denyMutations?.paths??[],...e.policy.denyMutations?.prefixes??[]].some(n=>n!==Z.resolve(n)||!ordinarySharedAbsoluteInsideRoot(e.rootReal,n,t)))return{route:n,rootIdentity:t}}function snapshotPinnedMutationPolicy(e,t){if(e===void 0&&t===void 0)return;let n=e===void 0?void 0:Object.freeze({paths:e.paths===void 0?void 0:Object.freeze([...e.paths]),prefixes:e.prefixes===void 0?void 0:Object.freeze([...e.prefixes])});return Object.freeze({denyMutations:n,mutationSymlinks:t})}async function canonicalMutationEntryPath(e){let t=await xe(Z.dirname(e));return Z.join(t,Z.basename(e))}function simplePinnedRoute(e,t){if(!t||process.platform===`win32`||process.versions.bun||t.startsWith(`~`)||t.includes(`\\`)||t.includes(`\0`)||t.split(`/`).some((e,t)=>e===`.`||e===`..`||e===``&&t!==0))return;let n=Z.resolve(e,t);return k(e,n)&&n!==e?n:void 0}function nonzeroObservationIdentity(e){return e.entry.dev!==0n&&e.entry.ino!==0n&&e.identity.dev!==0n&&e.identity.ino!==0n}function captureEpoch(e,t,n,r){let i=/* @__PURE__ */ new Map,observe=e=>{if(!i.has(e)){let t=un(e);if(!t)throw Error(`incomplete mutation observation`);i.set(e,t)}return i.get(e)};try{let a=observe(e),o=observe(t);if(a.canonicalPath!==e||o.canonicalPath!==t||o.ancestor!==o.canonicalAncestor||o.entry.dev!==o.identity.dev||o.entry.ino!==o.identity.ino)return;let comparables=t=>Object.freeze((t??[]).map(t=>{if(!t||!Z.isAbsolute(t)||t.includes(`\0`))throw Error(`invalid policy observation`);let n=Z.resolve(t);if(r.kind===`shared`&&(!r.rootIdentity||t!==n||!ordinarySharedAbsoluteInsideRoot(e,n,r.rootIdentity)))throw Error(`ineligible shared policy observation`);let i=observe(n);if(r.kind===`shared`&&(i.canonicalPath!==n||i.ancestor!==i.canonicalAncestor||!nonzeroObservationIdentity(i)))throw Error(`incomplete shared policy observation`);return Object.freeze([n,i.canonicalPath])})),s=comparables(n.denyMutations?.paths),c=comparables(n.denyMutations?.prefixes);return r.kind===`shared`&&(!r.rootIdentity||a.entry.dev!==r.rootIdentity.dev||a.entry.ino!==r.rootIdentity.ino||a.identity.dev!==r.rootIdentity.dev||a.identity.ino!==r.rootIdentity.ino||!nonzeroObservationIdentity(a)||!nonzeroObservationIdentity(o))?void 0:Object.freeze({mode:b().mode,target:o,paths:s,prefixes:c,observations:Object.freeze([...i.values()]),session:r})}catch{return}}function epochCurrent(e,t){return!process.versions.bun&&e.mode===e.session.nativeMode&&b().mode===e.mode&&(t?_n(e.observations,t):e.observations.every(ln))&&b().mode===e.mode}function assertCachedNotDenied(e,t){let n=createMutationDenyMatcher();if(t.paths.some(t=>t.some(t=>n(e,t,!1)))||t.prefixes.some(t=>t.some(t=>n(e,t,!0))))throw new I(`denied-path`,`path is denied by denyMutations policy`)}function reusableRequest(e,t){return e.targetPath===t.target.path&&(e.phase===`parent`&&e.mutationPath===e.targetPath||e.phase===`parent-create`&&gn(t.target)>1&&e.mutationPath===dn(t.target))}function reusableSharedCreateRequest(e,t){return e.phase===`parent-create`&&e.targetPath===t.target.path&&e.mutationPath===dn(t.target)}function reusableSharedRequest(e,t){return e.phase===`parent`?e.targetPath===t.target.path&&e.mutationPath===e.targetPath:reusableSharedCreateRequest(e,t)}function nonzeroDirectoryObservation(e){return e.identity.dev!==0n&&e.identity.ino!==0n}function advanceAuthorizedDirectory(e,t,n){if(!e||!t||n.admission!==t||t.epoch!==e||t.session!==e.session||t.childPath!==n.child.path||e.session.kind===`shared`&&(!nonzeroDirectoryObservation(n.parent)||!nonzeroDirectoryObservation(n.child)))return;let r=e.observations.map(e=>yn(e,n.parent,n.child));if(r.some(e=>!e))return;let i=r,a=i.find(t=>t.path===e.target.path);if(!a||a.missingOffset!==e.target.missingOffset+1)return;let o=Object.freeze({...e,target:a,observations:Object.freeze(i)});if(kn(a,n.child)&&epochCurrent(o,[n.parent,n.child]))return assertCachedNotDenied(a.path,o),assertCachedNotDenied(n.child.path,o),o}async function preparePinnedWriteMutationAdmission(e){if(!e.policy)return{relativeParentPath:e.defaultRelativeParentPath};let t=e.policy,n=simplePinnedRoute(e.rootReal,e.originalPath),r=simpleSharedRoute({rootReal:e.rootReal,rootIdentity:e.rootIdentity,originalPath:e.originalPath,selectedTarget:e.resolvedTargetPath,policy:t}),i=r??(process.platform===`win32`&&e.originalPath?.includes(`/`)?simpleSharedRoute({rootReal:e.rootReal,rootIdentity:e.rootIdentity,originalPath:e.originalPath.replaceAll(`/`,`\\`),selectedTarget:e.resolvedTargetPath,policy:t}):void 0),a,o,s,c=await xe(Z.dirname(e.resolvedTargetPath)),l=M({rootPath:e.rootReal,candidatePath:c,rootIdentity:e.rootIdentity});if(!l)throw G();let u=l.relativePath,authorizeFully=async n=>{let r=await e.resolveCurrent();await assertMutationNotDenied(n.targetPath,t.denyMutations),sameAbsolutePath(n.targetPath,n.mutationPath)||await assertMutationNotDenied(n.mutationPath,t.denyMutations);let[i,a]=await Promise.all([canonicalMutationEntryPath(r.resolved),canonicalMutationEntryPath(n.targetPath)]);if(!sameAbsolutePath(i,a))throw new I(`path-mismatch`,`write target changed during mutation policy admission`);return r},createSharedParentWalk=n=>{let r=Object.freeze({kind:`shared`,route:n.route,selectedTarget:e.resolvedTargetPath,nativeMode:b().mode,rootIdentity:n.rootIdentity,authorizationToken:Object.freeze({})}),i=!1,a=!1,o,s,disable=()=>{a=!0,o=void 0,s=void 0};return Object.freeze({retainedTargetPath:r.route,tryAuthorizeAtParent(e,t){if(i||a||!o&&!s)return;if(s){disable();return}let n=o;if(!n||n.session!==r||!reusableSharedCreateRequest(e,n)||!kn(n.target,t)||!nonzeroDirectoryObservation(t)||!epochCurrent(n,[t]))disable();else return assertCachedNotDenied(e.targetPath,n),assertCachedNotDenied(e.mutationPath,n),s=Object.freeze({epoch:n,childPath:e.mutationPath,session:r}),s},async authorize(n){s&&disable();let c=o;if(!i&&!a&&c?.session===r&&reusableSharedRequest(n,c)&&epochCurrent(c)){assertCachedNotDenied(n.targetPath,c),assertCachedNotDenied(n.mutationPath,c);return}c&&disable();let l=!i&&!a&&n.targetPath===r.route,u=l?captureEpoch(e.rootReal,r.route,t,r):void 0;l&&(!u||!reusableSharedRequest(n,u))&&disable();let d=await authorizeFully(n);if(i||a||!u)o=void 0;else if(d.resolved!==r.route||d.resolved!==r.selectedTarget||!epochCurrent(u))disable();else if(o=u,n.phase!==`parent`)return s=Object.freeze({epoch:u,childPath:n.mutationPath,session:r}),s},advanceCreatedDirectory(e){let t=s,n=o;if(s=void 0,o=void 0,i||a||n?.session!==r){disable();return}let c=advanceAuthorizedDirectory(n,t,e);if(!c)disable();else return o=c,r.authorizationToken},dispose(){i=!0,disable()}})},d=Object.freeze({rejectParentSymlinks:t.mutationSymlinks===`reject`,beginParentWalk:n?()=>(a=Object.freeze({kind:`pinned`,route:n,selectedTarget:e.resolvedTargetPath,nativeMode:b().mode,authorizationToken:Object.freeze({})}),o=void 0,s=void 0,n):void 0,beginSharedParentWalk:r?()=>createSharedParentWalk(r):void 0,beginNativeParentWalk:i?()=>createSharedParentWalk(i):void 0,tryAuthorizeAtParent(e,t){s=void 0;let n=o;if(!n||n.session!==a||!reusableRequest(e,n)||!kn(n.target,t)||!epochCurrent(n,[t]))o=void 0;else return assertCachedNotDenied(e.targetPath,n),assertCachedNotDenied(e.mutationPath,n),e.phase===`parent-create`?(s=Object.freeze({epoch:n,childPath:e.mutationPath,session:n.session}),s):n.session.authorizationToken},async authorize(r){if(s=void 0,o&&o.session===a&&reusableRequest(r,o)&&epochCurrent(o))return assertCachedNotDenied(r.targetPath,o),assertCachedNotDenied(r.mutationPath,o),r.phase===`parent-create`?(s=Object.freeze({epoch:o,childPath:r.mutationPath,session:o.session}),s):void 0;o=void 0;let i=a,c=i&&n===r.targetPath?captureEpoch(e.rootReal,n,t,i):void 0,l=await authorizeFully(r);if(c&&c.session===a&&l.resolved===n&&epochCurrent(c)&&(o=c,r.phase===`parent-create`&&reusableRequest(r,c)))return s=Object.freeze({epoch:c,childPath:r.mutationPath,session:c.session}),s},advanceCreatedDirectory:n?e=>{let t=s;s=void 0;let n=o;o=void 0;let r=advanceAuthorizedDirectory(n,t,e);if(r)return o=r,r.session.authorizationToken}:void 0});return{relativeParentPath:u?u.split(Z.sep).join(Z.posix.sep):``,mutationAdmission:d}}function existingCreationParent(e){if(e.private||e.policy||e.assertBeforeMutation!==void 0||l()?.beforeRootFallbackMutation||!e.originalPath||e.directory!==Z.dirname(e.target))return;let t=e.originalPath.split(Z.sep===`\\`?/[\\/]/:`/`);if(t.some(e=>!me(e,{allowDotPrefix:!0})||e.endsWith(`.`))||Z.join(e.root.rootReal,...t)!==e.target)return;let n;assertRootIdentityCurrentSync(e.root,e=>{n=e});try{let t=B(e.directory,void 0,e.directory===e.root.rootReal?n:void 0);return O.native(D(e.directory))===e.directory?{path:e.directory,identity:t,relative:Z.relative(e.root.rootReal,e.directory).split(Z.sep).join(`/`),flags:(Et()?.flags??Q.constants.O_RDONLY)|(Q.constants.O_DIRECTORY??0)|(Q.constants.O_NOFOLLOW??0)}:void 0}catch{return}}function probeNativeCreationPath(e,t){if(typeof t!=`string`)return;let n=t.split(Z.sep===`\\`?/[\\/]/:`/`);if(n.some(e=>!me(e,{allowDotPrefix:!0})||e.endsWith(`.`)))return;let r=Z.join(e.rootReal,...n);assertRootIdentityCurrentSync(e);try{if(Q.lstatSync(D(r),{throwIfNoEntry:!1}))return}catch{return}let i=existingCreationParent({root:e,target:r,directory:Z.dirname(r),mkdir:!0,originalPath:t,resolveCurrent:async()=>r});if(i)return{rootReal:e.rootReal,rootWithSep:e.rootWithSep,resolved:r,parent:i}}var __addDisposableResource$3=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var dispose,r;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);dispose=t[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);dispose=t[Symbol.dispose],n&&(r=dispose)}if(typeof dispose!=`function`)throw TypeError(`Object not disposable.`);r&&(dispose=function(){try{r.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose,async:n})}else n&&e.stack.push({async:!0});return t},ia=(function(e){return function(t){function fail(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var n,r=0;function next(){for(;n=t.stack.pop();)try{if(!n.async&&r===1)return r=0,t.stack.push(n),Promise.resolve().then(next);if(n.dispose){var e=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(e).then(next,function(e){return fail(e),next()})}else r|=1}catch(e){fail(e)}if(r===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return next()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});function rootWriteQueueKey(e,t){return`${e.rootReal}\0${t}`}function buildAtomicWriteTempPath(e){return Z.join(Z.dirname(e),`.fs-safe-${oi()}.tmp`)}const aa=/* @__PURE__ */ new WeakSet;function isNativeCreateCollision(e){return typeof e==`object`&&!!e&&aa.has(e)}function unavailable$2(){throw new I(`helper-unavailable`,`native confined creation is unavailable`)}async function withNativeDirectory(e,t,n){let r=P(`openBeneath`,`mkdirChildBeneath`);if(!r?.openBeneath||!r.mkdirChildBeneath||e.private&&process.platform===`win32`)return unavailable$2();let i=e.selectedParent??existingCreationParent(e);if(i){let a;try{let n={stack:[],error:void 0,hasError:!1};try{let o=__addDisposableResource$3(n,openExactNativeRootSync(r,{rootPath:e.root.rootReal,rootIdentity:e.root.rootIdentity}),!1),s=V(r),c=i.path===e.root.rootReal,l=c?o.fd:r.openBeneath(o.fd,i.relative,i.flags).fd;__addDisposableResource$3(n,{[Symbol.dispose](){c||s(l)}},!1),z(()=>c?o.stat:Q.fstatSync(l,{bigint:!0}),i.identity),verifyMkdirDirectory(r,l,i.path);let u={dir:i.path,realPath:i.path,stat:i.identity};return a={value:await t(r,l,()=>{let t;if(assertRootIdentityCurrentSync(e.root,e=>{t=e}),c){if(B(i.path,i.identity,t),O.native(D(i.path))!==i.path)throw new I(`path-mismatch`,`directory changed during operation`)}else W(u)})},a.value}catch(e){n.error=e,n.hasError=!0}finally{ia(n)}}catch(e){if(a&&n)try{await n(a.value)}catch(t){throw K(t,e,`creation handoff and cleanup failed`)}throw e}}let a=e.directory===e.target,canonicalTarget=async e=>a?await xe(e):Z.join(await xe(Z.dirname(e)),Z.basename(e)),o=e.resolveCurrent;if(e={...e,directory:await xe(e.directory),target:await canonicalTarget(e.target),resolveCurrent:async()=>await canonicalTarget(await o())},!k(e.root.rootReal,e.directory))throw new I(`outside-workspace`,`creation parent is outside root`);let s=V(r),c;try{let n={stack:[],error:void 0,hasError:!1};try{let i=await openNativeRootAdmission(r,{rootPath:e.root.rootReal,rootIdentity:e.root.rootIdentity,operation:`create`,reportCloseErrors:!0,searchOnly:!0}),o=__addDisposableResource$3(n,i.root,!0),u=[];__addDisposableResource$3(n,{[Symbol.dispose](){let e=[];for(let t of u.reverse())try{s(t)}catch(t){e.push(t)}if(e.length)throw AggregateError(e,`creation directory close failed`)}},!1);let d=[];function assertCurrent(){assertRootIdentityCurrentSync(e.root);for(let e of d)W(e)}async function authorize(t){if(Z.relative(e.target,await e.resolveCurrent())!==``)throw new I(`path-mismatch`,`creation route changed during admission`);await assertMutationNotDenied(e.target,e.policy?.denyMutations),await assertMutationNotDenied(t,e.policy?.denyMutations),assertCurrent()}let f=o.fd,p=e.root.rootReal,m=(Et()?.flags??Q.constants.O_RDONLY)|(Q.constants.O_DIRECTORY??0)|(Q.constants.O_NOFOLLOW??0);if(!e.private&&!(a&&e.directory===e.root.rootReal)){if(!M({rootPath:e.root.rootReal,candidatePath:e.target,rootIdentity:e.root.rootIdentity}))throw new I(`outside-workspace`,`creation target is outside root`);let n=Z.relative(e.root.rootReal,e.directory).split(Z.sep).join(`/`),o=await preparePinnedWriteMutationAdmission({rootReal:e.root.rootReal,rootIdentity:e.root.rootIdentity,resolvedTargetPath:e.target,defaultRelativeParentPath:n,originalPath:e.originalPath,policy:e.policy??{},resolveCurrent:async()=>({resolved:await e.resolveCurrent()})}),s=await capturePolicyAwareNativeParent(r,{rootPath:e.root.rootReal,rootIdentity:e.root.rootIdentity,relativeParentPath:n,basename:a?``:Z.basename(e.target),mkdir:e.mkdir,mode:384,input:{kind:`buffer`,data:``},mutationAdmission:o.mutationAdmission,assertBeforeMutation:e.assertBeforeMutation},i,process.platform===`win32`,m,!0);return u.push(s.fd),d.push(s.guard),assertCurrent(),c={value:await t(r,s.fd,assertCurrent)},c.value}for(let t of Z.relative(p,e.directory).split(Z.sep).filter(Boolean)){let n=Z.join(p,t),i,a=!1;try{i=r.openBeneath(f,t,m).fd}catch(o){if(!e.mkdir||!E(o))throw o;if(await l()?.beforeRootFallbackMutation?.(`mkdir`,n),await authorize(n),e.private&&assertDarwinCreationAcl(f,`directory`),e.assertBeforeMutation?.(),assertCurrent(),r.mkdirOpenChildBeneath){let n=r.mkdirOpenChildBeneath(f,t,e.private?448:511,m);a=n.created,i=n.fd}else a=r.mkdirChildBeneath(f,t,e.private?448:511),i=r.openBeneath(f,t,m).fd}u.push(i);let o=z(()=>Q.fstatSync(i,{bigint:!0}));if(!o.isDirectory())throw new I(`not-file`,`creation parent is not a directory`);d.push({dir:n,realPath:n,stat:o}),assertCurrent(),a&&e.private&&await assertPrivateDirectory(n),f=i,p=n}return await authorize(e.target),e.private&&(await assertPrivateDirectory(p),assertCurrent()),c={value:await t(r,f,assertCurrent)},c.value}catch(e){n.error=e,n.hasError=!0}finally{let e=ia(n);e&&await e}}catch(e){if(c&&n)try{await n(c.value)}catch(t){throw K(t,e,`creation handoff and cleanup failed`)}throw e}}function tryMkdirNativeDirectChild(e,t,n){if(!me(t,{allowDotPrefix:!0})||t.endsWith(`.`)||l()?.beforeRootFallbackMutation)return!1;assertRootIdentityCurrentSync(e);let r=Z.join(e.rootReal,t);try{let e=Q.lstatSync(D(r),{throwIfNoEntry:!1});if(e&&(!e.isDirectory()||O.native(D(r))!==r))return!1}catch{return!1}try{return mkdirNativeRootChild({root:e,target:r},n),!0}catch(e){throw j(e,`ENOTDIR`)?Ve(e):e}}async function tryMkdirRootNative(e){if(e.private&&process.platform===`win32`)return!1;try{return!e.private&&!e.policy&&!e.assertBeforeMutation&&!l()?.beforeRootFallbackMutation&&e.originalPath===Z.basename(e.target)&&Z.dirname(e.target)===e.root.rootReal&&e.directory===e.target?(mkdirNativeRootChild(e),!0):await withNativeDirectory(e,async(e,t,n)=>(n(),!0))}catch(e){throw j(e,`ENOTDIR`)?Ve(e):e}}function verifyMkdirDirectory(e,t,n){let r=hn(e,t,n);try{if(r?.())return}finally{r?.dispose()}Cn(t,n)}function ensureNativeRootCurrent(e){assertRootIdentityCurrentSync(e);let t=P(`openBeneath`,`mkdirChildBeneath`);if(!t?.openBeneath||!t.mkdirChildBeneath)return unavailable$2();if(t.verifyRootDirectory){let n=V(t),r=t.verifyRootDirectory(e.rootReal,e.rootIdentity.dev,e.rootIdentity.ino);if(r===null)return;if(r?.fallbackFd!==void 0&&r.fallbackFd!==null){let i={stack:[],error:void 0,hasError:!1};try{let a=r.fallbackFd;if(!Number.isInteger(a)||a<0)throw new I(`helper-failed`,`invalid root fallback descriptor`);if(__addDisposableResource$3(i,{[Symbol.dispose](){n(a)}},!1),r.errorCode||r.closeErrorCode)throw new I(`helper-failed`,`invalid root verification result`);ensureNativeRootCurrentLegacy(e,t);return}catch(e){i.error=e,i.hasError=!0}finally{ia(i)}}let i=r?.errorCode?rootVerificationError(r.errorCode,r.errorMessage,r.errorErrno):void 0,a=r?.closeErrorCode?Object.assign(Error(r.closeErrorMessage),{code:r.closeErrorCode,...typeof r.closeErrorErrno==`number`?{errno:r.closeErrorErrno}:{}}):void 0;throw i&&a?K(a,i,`root verification and close failed`):i||a?i??a:new I(`helper-failed`,`invalid root verification result`)}ensureNativeRootCurrentLegacy(e,t)}function rootVerificationError(e,t,n){let r=Object.assign(Error(t),{code:e,...typeof n==`number`?{errno:n}:{}});return e===`path-mismatch`||e===`OBSERVATION_REDIRECTED`?new I(`path-mismatch`,`root identity changed during verification`,{cause:r}):r}function ensureNativeRootCurrentLegacy(e,t){let n={stack:[],error:void 0,hasError:!1};try{verifyMkdirDirectory(t,__addDisposableResource$3(n,openExactNativeRootSync(t,{rootPath:e.rootReal,rootIdentity:e.rootIdentity}),!1).fd,e.rootReal),assertRootIdentityCurrentSync(e)}catch(e){n.error=e,n.hasError=!0}finally{ia(n)}}function mkdirNativeRootChild(e,t){let n={stack:[],error:void 0,hasError:!1};try{let r=P(`openBeneath`,`mkdirChildBeneath`);if(!r?.openBeneath||!r.mkdirChildBeneath)return unavailable$2();let i=__addDisposableResource$3(n,openExactNativeRootSync(r,{rootPath:e.root.rootReal,rootIdentity:e.root.rootIdentity}),!1);verifyMkdirDirectory(r,i.fd,e.root.rootReal);let a=(t===void 0?Et()?.flags??Q.constants.O_RDONLY:Q.constants.O_RDONLY)|(Q.constants.O_DIRECTORY??0)|(Q.constants.O_NOFOLLOW??0),o=Z.basename(e.target),s=r.mkdirOpenChildBeneath?r.mkdirOpenChildBeneath(i.fd,o,t??511,a):{created:r.mkdirChildBeneath(i.fd,o,t??511),fd:r.openBeneath(i.fd,o,a).fd},c=V(r);__addDisposableResource$3(n,{[Symbol.dispose](){c(s.fd)}},!1),assertRootIdentityCurrentSync(e.root),verifyMkdirDirectory(r,s.fd,e.target),verifyMkdirDirectory(r,i.fd,e.root.rootReal),t!==void 0&&s.created&&(bt(s,t),verifyMkdirDirectory(r,s.fd,e.target),verifyMkdirDirectory(r,i.fd,e.root.rootReal),assertRootIdentityCurrentSync(e.root))}catch(e){n.error=e,n.hasError=!0}finally{ia(n)}}async function tryOpenCreateRootNative(e){let t=P(`openBeneath`,`mkdirChildBeneath`,`removeStagedFile`,`openCreateBeneath`);if(!t?.removeStagedFile||!t.openCreateBeneath)return unavailable$2();let n=e.existingFlags&Q.constants.O_RDWR?384:128;if(typeof e.mode!=`number`)throw Object.assign(/* @__PURE__ */ TypeError(`mode must be a number`),{code:`ERR_INVALID_ARG_TYPE`});if(!Number.isInteger(e.mode)||e.mode<0||e.mode>4294967295)throw Object.assign(/* @__PURE__ */ RangeError(`mode must be an unsigned 32-bit integer`),{code:`ERR_OUT_OF_RANGE`});let creationMode=()=>{let t=process.umask(),r=e.mode&4095&~t;return(r&n)===n?r:void 0};return creationMode()===void 0?unavailable$2():await withNativeDirectory(e,async(t,r,i)=>{let a={stack:[],error:void 0,hasError:!1};try{if(e.assertBeforeMutation?.(),i(),creationMode()===void 0)throw new I(`helper-unavailable`,`native creation cannot preserve the requested permissions during handoff`);let o=V(t),s;try{s=t.openCreateBeneath(r,Z.basename(e.target),e.flags,e.mode&4095)}catch(t){throw j(t,`EEXIST`)&&typeof t==`object`&&t&&aa.add(t),jt(t,e.target),t}let c=!0,closeRaw=()=>{c&&(c=!1,o(s))};__addDisposableResource$3(a,{[Symbol.dispose]:closeRaw},!1);try{let a=z(()=>Q.fstatSync(s,{bigint:!0}));if(!a.isFile()||a.nlink!==1n)throw new I(`path-mismatch`,`created file changed`);if(process.platform!==`win32`&&(Number(a.mode)&n)!==n)throw new I(`helper-unavailable`,`created permissions do not permit a FileHandle handoff`);i();let l=await $.open(e.target,e.existingFlags),u=!1;try{z(()=>Q.fstatSync(l.fd,{bigint:!0}),a),u=!0,i(),closeRaw();let n=t.openBeneath(r,``,(Et()?.flags??Q.constants.O_RDONLY)|(Q.constants.O_DIRECTORY??0)).fd,s=!0;return{handle:l,async cleanupCreated(){s&&(z(()=>Q.fstatSync(l.fd,{bigint:!0}),a),t.removeStagedFile(n,Z.basename(e.target),l.fd))},releaseCreationParent(){s&&(s=!1,o(n))}}}catch(n){if(!c&&u)try{t.removeStagedFile(r,Z.basename(e.target),l.fd)}catch{}throw await l.close(),n}}catch(n){if(c)try{t.removeStagedFile(r,Z.basename(e.target),s)}catch{}throw n}}catch(e){a.error=e,a.hasError=!0}finally{ia(a)}},async e=>{let t={stack:[],error:void 0,hasError:!1};try{__addDisposableResource$3(t,e.handle,!0),__addDisposableResource$3(t,{[Symbol.dispose]:e.releaseCreationParent},!1),await e.cleanupCreated()}catch(e){t.error=e,t.hasError=!0}finally{let e=ia(t);e&&await e}})}const oa=ft;async function assertNoPathAliasEscape(e){let t=await _t({absolutePath:e.absolutePath,rootPath:e.rootPath,boundaryLabel:e.boundaryLabel,policy:e.policy});(e.policy?.allowFinalSymlinkForUnlink!==!0||t.kind!==`symlink`)&&await assertNoHardlinkedFinalPath({filePath:t.canonicalPath,root:t.rootPath,boundaryLabel:e.boundaryLabel,allowFinalHardlinkForUnlink:e.policy?.allowFinalHardlinkForUnlink})}async function assertNoHardlinkedFinalPath(e){if(e.allowFinalHardlinkForUnlink)return;let t=e.filePath,n=e.root,r=e.boundaryLabel;w(t);let i;try{i=Q.statSync(t)}catch(e){if(E(e))return;throw e}if(i.isFile()&&i.nlink>1)throw Error(`Hardlinked path is not allowed under ${r} (${ce(n)}): ${ce(t)}`)}async function inheritWriteTargetMode(e){try{let t=M({rootPath:e.rootWithSep,candidatePath:e.targetPath,rootIdentity:e.rootIdentity});if(!t)throw G();let n=t.path,r=await it(()=>Q.lstatSync(n,{bigint:!0}));if(r.isSymbolicLink())throw new I(`path-alias`,`path alias escape blocked`);if(!r.isFile())throw new I(`not-file`,`not a file`);if(r.nlink>1n)throw R();let i=await $.open(n,ke());try{await it(()=>Q.fstatSync(i.fd,{bigint:!0}),r)}finally{await i.close().catch(()=>void 0)}try{let t=O.native(n),i=M({rootPath:e.rootWithSep,candidatePath:t,rootIdentity:e.rootIdentity});if(!i)throw G();let a=i.path;await it(async()=>{let e=Q.statSync(a,{bigint:!0});if(!e.isFile())throw new I(`not-file`,`not a file`);if(e.nlink>1n)throw R();return e},r)}catch(e){throw E(e)?new I(`path-mismatch`,`write target changed during mode inheritance`,{cause:e}):e}return e.requestedMode??Number(r.mode&511n)}catch(t){if(!E(t))throw t;return e.requestedMode??384}}function sameDirectoryFacts(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.mode===t.mode&&e.nlink===t.nlink}function isDirectoryCollision(e){return j(e,`EEXIST`)||e instanceof I&&e.code===`already-exists`}function inspectGuardCurrent(e){let t=B(e.dir,e.stat);if(O.native(e.dir)!==e.realPath)throw new I(`path-mismatch`,`directory changed during operation`);return t}function observedGuard(e){return An(e.dir,e.realPath,e.stat)}function createdDirectoryEvidence(e,t,n){try{let r=inspectGuardCurrent(t),i=B(n),a=O.native(n);if(a!==n)return;let o=B(n,i);if(!sameDirectoryFacts(i,o))return;let s=An(n,a,o),c=Object.freeze({admission:e,parent:An(t.dir,t.realPath,r),child:s});return Object.freeze({receipt:c,guard:Object.freeze({dir:n,realPath:a,stat:o})})}catch{return}}function captureExactDirectoryGuard(e){return Ge(e,`native`,{bigint:!0})}function suppliedExactRootIdentity(e){return typeof e?.dev==`bigint`&&typeof e.ino==`bigint`?{dev:e.dev,ino:e.ino}:void 0}function assertGuardMatchesRootIdentity(e,t){if(e.stat.dev!==t.dev||e.stat.ino!==t.ino)throw T()}function isPromiseLike(e){return typeof e?.then==`function`}function realpathOrThrowNotFile(e){try{let t=O.native(D(e));return w(t,`filesystem`,`canonical directory uses a Windows filesystem namespace alias`),Ce(t)}catch(e){throw E(e)?Ve(e instanceof Error?e:void 0):e}}async function mkdirPathComponentsWithGuards(e){let t=e.rootReal;w(t,`filesystem`,`root directory uses a Windows filesystem namespace alias`);let n=e.targetPath;w(n,`filesystem`,`target directory uses a Windows filesystem namespace alias`);let r=Ce(t),i=Ce(n),a=suppliedExactRootIdentity(e.rootIdentity),o=captureExactDirectoryGuard(r),s=a??{dev:o.stat.dev,ino:o.stat.ino};assertGuardMatchesRootIdentity(o,s),w(o.realPath);let c=Ce(o.realPath),l=c===r?o:captureExactDirectoryGuard(c);assertGuardMatchesRootIdentity(l,s);let u={candidatePath:i,rootIdentity:s},d=M({rootPath:r,...u})??(c===r?void 0:M({rootPath:c,...u}));if(!d||Je(d.relativePath))throw new I(`outside-workspace`,`directory is outside workspace root`);let f=c,p=l,m=d.relativePath.split(Z.sep).filter(Boolean),h,g=e.retainedTargetPath&&sameAbsolutePath(Z.dirname(e.retainedTargetPath),i)?e.retainedTargetPath:void 0,_=g?Z.dirname(g):void 0;for(let t=0;t<m.length;t+=1){let n=m[t],r=Z.join(f,n),i=p;w(i.realPath,`filesystem`,`canonical parent directory uses a Windows filesystem namespace alias`);let a=!1,o;e.revalidateParentAfterBeforeComponent||y(i,`native`),e.beforeComponent&&await e.beforeComponent(r),e.revalidateParentAfterBeforeComponent&&y(i,`native`);let l=!0;if(e.beforeCreateComponent){let n=!1;try{Q.lstatSync(r)}catch(e){if(!E(e))throw e;n=!0}if(l=n,n){let n=_;n||=(h??=createPathSegmentRoute(m),joinPathSegmentRoute(r,h,t+1));let a=e.beforeCreateComponent(r,n,g,observedGuard(i));isPromiseLike(a)?(o=await a,y(i,`native`)):(o=a,e.synchronousAuthorizationIncludesFence||inspectGuardCurrent(i))}}if(l&&e.createMissing!==!1){e.assertBeforeMutation?.(),inspectGuardCurrent(i);try{e.private?await createDirectoryWithAdmission(r,{private:!0,mode:e.mode,assertBeforeMutation:e.assertBeforeMutation},{expectedParentIdentity:{dev:i.stat.dev,ino:i.stat.ino,realPath:i.realPath}}):e.synchronousMkdir?Q.mkdirSync(r,{mode:e.mode}):await $.mkdir(r,{mode:e.mode}),a=!0}catch(e){if(!isDirectoryCollision(e))throw e}}let u,d;if(a&&o&&e.afterCreateComponent&&(d=createdDirectoryEvidence(o,i,r),d&&(u=e.afterCreateComponent(d.receipt))),e.beforeUseComponent&&!u){let n=_;n||=(h??=createPathSegmentRoute(m),joinPathSegmentRoute(r,h,t+1)),await e.beforeUseComponent(r,n,g),y(i,`native`)}let v=u?void 0:Q.lstatSync(r);if(v&&(e.rejectSymlinks&&v.isSymbolicLink()||!v.isSymbolicLink()&&!v.isDirectory()))throw Ve();let b=u&&d?d.receipt.child.canonicalPath:realpathOrThrowNotFile(r),S=M({rootPath:c,candidatePath:b,rootIdentity:s});if(!S)throw new I(`outside-workspace`,`directory escaped workspace root`);let C=S.path;if(v?.isSymbolicLink()){if(!Q.statSync(C).isDirectory())throw Ve();p=captureExactDirectoryGuard(C),w(p.realPath,`filesystem`,`canonical directory uses a Windows filesystem namespace alias`),y(i,`native`),g=void 0,_=void 0,f=C}else p=u&&d?d.guard:captureExactDirectoryGuard(C),w(p.realPath,`filesystem`,`canonical directory uses a Windows filesystem namespace alias`),(!u||!d)&&y(i,`native`),a&&e.finalizeCreatedMode&&e.mode!==void 0&&(await ue(wt(x.async($),{dirPath:p.dir,mode:e.mode,expectedIdentity:p.stat})),y(i,`native`),y(p,`native`)),f=C}return f}function mutationWalkOptions(e,t,n,r,i){let a=canReuseParentWithMutationAssertion(n,r,i)?e.beginSharedParentWalk?.():void 0;return{dispose:()=>a?.dispose(),options:{rejectSymlinks:e.rejectParentSymlinks,revalidateParentAfterBeforeComponent:!0,retainedTargetPath:a?.retainedTargetPath,synchronousAuthorizationIncludesFence:a!==void 0,afterCreateComponent:a?.advanceCreatedDirectory,beforeCreateComponent:(n,r,i,o)=>{let s=i??t(r),c=Object.freeze({targetPath:s,mutationPath:n,phase:`parent-create`});return a?.tryAuthorizeAtParent(c,o)??a?.authorize(c)??e.authorize(c)},beforeUseComponent:async(n,r,i)=>{let o=i??t(r),s=Object.freeze({targetPath:o,mutationPath:o,phase:`parent`});await(a?.authorize(s)??e.authorize(s))}}}}async function tryMkdirAtExactParent(e,t,n){if(l()?.beforeRootFallbackMutation||typeof e.rootIdentity.dev!=`bigint`||typeof e.rootIdentity.ino!=`bigint`||e.rootIdentity.dev===0n||e.rootIdentity.ino===0n)return!1;let r=Object.freeze({dev:e.rootIdentity.dev,ino:e.rootIdentity.ino}),i=n.beginSharedParentWalk?.();if(!i)return!1;try{if(Z.resolve(i.retainedTargetPath)!==Z.resolve(t))return!1;let n=Z.dirname(t),a;try{a=await F(n,{bigint:!0})}catch{return!1}try{return Q.lstatSync(t,{bigint:!0}),!1}catch(e){if(!j(e,`ENOENT`))return!1}let o=M({rootPath:e.rootReal,candidatePath:n,rootIdentity:r});if(o?.admission!==`exact`||o.path!==n||a.realPath!==n)return!1;await i.authorize(Object.freeze({targetPath:t,mutationPath:t,phase:`parent`})),await A(a);try{return Q.lstatSync(t,{bigint:!0}),!1}catch(e){if(!j(e,`ENOENT`))return!1}W(a);let s=i.tryAuthorizeAtParent(Object.freeze({targetPath:t,mutationPath:t,phase:`parent-create`}),An(n,a.realPath,a.stat));if(!s)return!1;try{await $.mkdir(t)}catch(e){if(j(e,`EEXIST`))return!1;throw e}let observeCreated=async()=>{let i=await F(t,{bigint:!0}),o=B(n,a.stat);Re(e.rootReal,r);let s=M({rootPath:e.rootReal,candidatePath:i.realPath,rootIdentity:r});if(i.realPath!==t||i.dir!==t||s?.admission!==`exact`||s.path!==t)throw new I(`path-mismatch`,`created directory changed during operation`);return{childGuard:i,parentAfter:o}};try{let e=await observeCreated();if(i.advanceCreatedDirectory(Object.freeze({admission:s,parent:An(n,a.realPath,e.parentAfter),child:An(t,e.childGuard.realPath,e.childGuard.stat)})))return!0}catch{}await i.authorize(Object.freeze({targetPath:t,mutationPath:t,phase:`parent`})),await A(a),Re(e.rootReal,r),L(t,!0);let c=await observeCreated();return await A(a),await A(c.childGuard),Re(e.rootReal,r),!0}finally{i.dispose()}}async function prepareRootWriteTarget(e,t,n,r,i=!1){let a=Z.basename(t),o={rootReal:e.rootReal,rootIdentity:e.rootIdentity,targetPath:Z.dirname(t),assertBeforeMutation:n,private:i,mode:i?448:void 0},s=r?mutationWalkOptions(r,e=>Z.join(e,a),n,e.rootReal,t):void 0,c;try{c=await mkdirPathComponentsWithGuards(s?{...o,...s.options}:o)}finally{s?.dispose()}return Z.join(c,a)}async function mkdirPathFallback(e,t,n,r=!1,i,a=!1){let o={rootReal:t.rootReal,targetPath:t.resolved,assertBeforeMutation:n,rootIdentity:e.rootIdentity,synchronousMkdir:!a&&!i&&!n&&!l()?.beforeRootFallbackMutation,rejectSymlinks:r,private:a,mode:a?448:void 0,beforeComponent:l()?.beforeRootFallbackMutation?e=>l()?.beforeRootFallbackMutation?.(`mkdir`,e):void 0},s=i?mutationWalkOptions(i,e=>e,n,e.rootReal,t.resolved):void 0;try{let t=await mkdirPathComponentsWithGuards(s?{...o,...s.options,rejectSymlinks:r||i.rejectParentSymlinks}:o);if(a){let n=await F(t,{bigint:!0});await assertPrivateDirectory(t),await A(n),await assertRootIdentityCurrent(e)}}finally{s?.dispose()}}function writeSelectionChanged(e){return new I(`path-mismatch`,`write target changed during operation`,U(e))}function ordinarySharedWriteRoute(e,t,n){if(process.versions.bun||t===``||t.startsWith(`~`)||t.includes(`\0`)||Z.isAbsolute(t))return!1;if(process.platform===`win32`){if(!ordinaryWindowsSegments(t))return!1}else if(t.includes(`\\`)||t.split(`/`).some(e=>e===``||e===`.`||e===`..`))return!1;let r=Z.resolve(e.rootReal,t),i=M({rootPath:e.rootReal,candidatePath:r,rootIdentity:e.rootIdentity});return i?.admission===`exact`&&N(i.path,r)&&N(r,n)}function deoptPreparationFailure(e){if(e instanceof I&&e.code===`path-mismatch`)throw e}function capturePreparedTargetObservation(e){let t;try{t=z(()=>Q.lstatSync(e,{bigint:!0}))}catch(e){return j(e,`ENOENT`)?Object.freeze({exists:!1}):deoptPreparationFailure(e)}if(t.isSymbolicLink())return;let n;try{n=O.native(e)}catch(e){return deoptPreparationFailure(e)}if(N(n,e))return Object.freeze({exists:!0,stat:t})}function samePreparedTargetFacts(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.mode===t.mode&&e.nlink===t.nlink}function assertPreparedTargetCurrent(e){if(!e.target.exists){try{Q.lstatSync(e.selectedTargetPath,{bigint:!0})}catch(e){if(j(e,`ENOENT`))return;throw writeSelectionChanged(e)}throw writeSelectionChanged()}try{let t=z(()=>Q.lstatSync(e.selectedTargetPath,{bigint:!0}),e.target.stat);if(t.isSymbolicLink()||!samePreparedTargetFacts(e.target.stat,t))throw writeSelectionChanged()}catch(e){throw e instanceof I&&e.code===`path-mismatch`?e:writeSelectionChanged(e)}}function assertPreparedRootWriteParentCurrent(e,t=!1){try{if(b().mode!==e.nativeMode)throw writeSelectionChanged();if(!N(e.parentGuard.dir,e.rootPath))Re(e.rootPath,e.rootIdentity);else if(e.parentGuard.stat.dev!==e.rootIdentity.dev||e.parentGuard.stat.ino!==e.rootIdentity.ino)throw writeSelectionChanged();let n=B(e.parentGuard.dir,e.parentGuard.stat);if(n.mode!==e.parentGuard.stat.mode||n.nlink!==e.parentGuard.stat.nlink||!N(O.native(e.parentGuard.dir),e.parentGuard.realPath))throw writeSelectionChanged();t&&assertPreparedTargetCurrent(e)}catch(e){throw e instanceof I&&e.code===`path-mismatch`?e:writeSelectionChanged(e)}}async function prepareCompleteRootWriteParent(e,t,n){if(!t.mutationAdmission||!t.selectedTargetAdmission||typeof e.rootIdentity.dev!=`bigint`||typeof e.rootIdentity.ino!=`bigint`||!ordinarySharedWriteRoute(e,n,t.targetPath)||!N(t.resolvedPath.resolved,t.targetPath))return;let r=Z.dirname(t.targetPath),i=M({rootPath:e.rootReal,candidatePath:r,rootIdentity:e.rootIdentity});if(i?.admission!==`exact`||!N(i.path,r))return;let a;try{a=await F(r,{bigint:!0})}catch(e){return deoptPreparationFailure(e)}if(!N(a.dir,r)||!N(a.realPath,r))return;let o=capturePreparedTargetObservation(t.targetPath);if(o)return Object.freeze({operationTargetPath:t.targetPath,selectedTargetPath:t.targetPath,parentGuard:a,rootPath:e.rootReal,rootIdentity:Object.freeze({dev:e.rootIdentity.dev,ino:e.rootIdentity.ino}),nativeMode:b().mode,target:o})}async function prepareSharedRootWriteTarget(e,t){let{guardedTarget:n}=t,r=n.resolvedPath.resolved,i=n.mutationAdmission,a=i?l()?.beforePinnedWriteParentAdmission:void 0;i&&await a?.(r);let o=t.mkdir!==!1&&canReuseParentWithMutationAssertion(t.assertBeforeMutation,e.rootReal,n.targetPath)&&a===void 0?await prepareCompleteRootWriteParent(e,n,t.relativePath):void 0;return{targetPath:t.mkdir===!1?n.targetPath:o?.selectedTargetPath??await prepareRootWriteTarget(e,r,t.assertBeforeMutation,i),mutationAdmission:i,preparedParent:o}}function createRootWriteSelectionForFd(e,t){let n=z(()=>Q.fstatSync(t,{bigint:!0}));return Object.freeze({...e,identity:Object.freeze({dev:n.dev,ino:n.ino})})}function inspectRegularSelectionPath(e,t,n){let r;try{r=z(()=>n?Q.statSync(e,{bigint:!0}):Q.lstatSync(e,{bigint:!0}),t)}catch(e){throw e instanceof I&&e.code===`path-mismatch`?e:writeSelectionChanged(e)}if(!n&&r.isSymbolicLink()||!r.isFile())throw writeSelectionChanged();if(r.nlink>1n)throw R();return r}function inspectSelectionBindingSync(e,t,n){if(inspectRegularSelectionPath(t.selectedPath,t.identity,!1),!N(t.operationTargetPath,t.selectedPath)){let n;try{n=O.native(t.operationTargetPath)}catch(e){throw writeSelectionChanged(e)}let r=M({rootPath:e.rootReal,candidatePath:n,rootIdentity:e.rootIdentity});if(!r)throw G();inspectRegularSelectionPath(r.path,t.identity,!0)}if(n!==void 0)try{z(()=>Q.fstatSync(n,{bigint:!0}),t.identity)}catch(e){throw e instanceof I&&e.code===`path-mismatch`?e:writeSelectionChanged(e)}}function assertRootWritePathSelectionSync(e,t){if(!N(t.operationTargetPath,t.selectedPath)){let n;try{n=O.native(t.operationTargetPath)}catch(e){throw writeSelectionChanged(e)}let r=M({rootPath:e.rootReal,candidatePath:n,rootIdentity:e.rootIdentity});if(!r)throw G();let i=inspectRegularSelectionPath(t.selectedPath,void 0,!1);inspectRegularSelectionPath(r.path,i,!0)}W(t.parentGuard)}function assertRootWriteSelectionSync(e,t,n){inspectSelectionBindingSync(e,t,n),W(t.parentGuard)}async function authorizeRootWritePathSelection(e,t){let n=!N(e.operationTargetPath,e.selectedPath);await e.mutationAdmission.authorize(Object.freeze({targetPath:e.operationTargetPath,mutationPath:e.operationTargetPath,phase:`parent`})),t?.(n),n&&(await e.selectedTargetAdmission.authorize(e.selectedPath),t?.(!1))}async function prepareRootWritePathSelection(e){let{preparedParent:t,...n}=e;if(t&&(!N(t.operationTargetPath,e.operationTargetPath)||!N(t.parentGuard.dir,Z.dirname(e.operationTargetPath))))throw writeSelectionChanged();let r=Object.freeze({...n,parentGuard:t?.parentGuard??await F(Z.dirname(e.selectedPath),{bigint:!0})});if(await authorizeRootWritePathSelection(r,t?e=>assertPreparedRootWriteParentCurrent(t,!e):void 0),t){if(!N(t.selectedTargetPath,e.selectedPath))throw writeSelectionChanged()}else await A(r.parentGuard);return r}async function prepareGuardedRootWritePathSelection(e,t,n=t,r){if(e?.mutationAdmission){if(!e.selectedTargetAdmission)throw writeSelectionChanged();return await prepareRootWritePathSelection({mutationAdmission:e.mutationAdmission,selectedTargetAdmission:e.selectedTargetAdmission,operationTargetPath:n,selectedPath:t,preparedParent:r})}}async function refreshRootWritePathSelection(e){await authorizeRootWritePathSelection(e),await A(e.parentGuard)}async function refreshRootWriteSelection(e,t,n){await authorizeRootWritePathSelection(t),inspectSelectionBindingSync(e,t,n),await A(t.parentGuard)}async function refreshRetainedRootWriteAdmission(e,t,n){await l()?.beforePinnedWriteParentAdmission?.(t.operationTargetPath),await refreshRootWriteSelection(e,t,n)}async function resolveGuardedWritePathInRoot(e,t){let n=await resolvePathInRoot(e,t.relativePath,{aliasErrorCode:`path-alias`,rejectAmbiguousParents:!0,allowFinalSymlink:t.allowFinalSymlink,...ze(t.mutationSymlinks)});if(await assertMutationNotDenied(n.resolved,t.denyMutations,t.protectDeniedAncestors?{protectAncestors:!0}:void 0),await(t.shouldAssertNoPathAlias?.(n)??!0))try{await assertNoPathAliasEscape({absolutePath:n.resolved,rootPath:n.rootReal,boundaryLabel:`root`})}catch(e){throw ve(e,n.resolved)||new I(`path-alias`,`path alias escape blocked`,U(e))}return n}async function resolveGuardedWriteTargetInRoot(e,t){let n=t.denyMutations===void 0&&t.mutationSymlinks===void 0?void 0:snapshotPinnedMutationPolicy(t.denyMutations,t.mutationSymlinks),resolveCurrent=async()=>await resolveGuardedWritePathInRoot(e,{...t,denyMutations:n?.denyMutations,mutationSymlinks:n?.mutationSymlinks}),r=await resolveCurrent();if(!n)return{resolvedPath:r,targetPath:r.resolved};let i=Z.relative(r.rootReal,Z.dirname(r.resolved)),a=await preparePinnedWriteMutationAdmission({rootReal:r.rootReal,rootIdentity:e.rootIdentity,resolvedTargetPath:r.resolved,originalPath:t.relativePath,defaultRelativeParentPath:i?i.split(Z.sep).join(Z.posix.sep):``,policy:n,resolveCurrent}),o=Object.freeze({async authorize(t){let r=M({rootPath:e.rootReal,candidatePath:t,rootIdentity:e.rootIdentity});if(!r)throw G();await resolveGuardedWritePathInRoot(e,{relativePath:r.relativePath,denyMutations:n.denyMutations,mutationSymlinks:n.mutationSymlinks})}});return{resolvedPath:r,targetPath:Z.join(r.rootReal,...a.relativeParentPath.split(`/`).filter(Boolean),Z.basename(r.resolved)),mutationAdmission:a.mutationAdmission,selectedTargetAdmission:o}}async function resolvePinnedWriteTargetInRoot(e,t,n,r,i=!0,a){let o=r===void 0&&a===void 0?void 0:snapshotPinnedMutationPolicy(r,a),s=o?async()=>await resolveGuardedWritePathInRoot(e,{relativePath:t,denyMutations:o.denyMutations,mutationSymlinks:o.mutationSymlinks}):void 0,{rootReal:c,rootWithSep:l,resolved:u}=s?await s():await resolveGuardedWritePathInRoot(e,{relativePath:t}),d=Z.relative(c,u);if(Z.isAbsolute(d))throw G();let f=d?d.split(Z.sep).join(Z.posix.sep):``,p=Z.posix.basename(f);if(!p||p===`.`||p===`/`)throw new I(`invalid-path`,`invalid target path`);if(!i)try{let e=Q.statSync(u,{throwIfNoEntry:!1});if(e)throw!e.isFile()&&!e.isDirectory()?new I(`not-file`,`not a file`):e.isFile()&&e.nlink>1?R():new I(`already-exists`,`file already exists`)}catch(e){if(!E(e))throw e}let m=i?await inheritWriteTargetMode({targetPath:u,rootWithSep:l,rootIdentity:e.rootIdentity,requestedMode:n}):n??384,h=Z.posix.dirname(f)===`.`?``:Z.posix.dirname(f),g;return o&&({relativeParentPath:h,mutationAdmission:g}=await preparePinnedWriteMutationAdmission({rootReal:c,rootIdentity:e.rootIdentity,resolvedTargetPath:u,originalPath:t,defaultRelativeParentPath:h,policy:o,resolveCurrent:s})),{rootReal:c,targetPath:u,relativeParentPath:h,basename:p,mode:m,mutationAdmission:g}}function createCopyPublicationObserver(e,t){let n;return{onPublished(r){let i=Object.freeze({path:e,dev:r.dev,ino:r.ino});try{q(t?.(i),`onDestinationPublished`)}catch(e){throw n={error:e},e}},rethrowObserverFailure(e){if(n&&(e===n.error||e instanceof I&&e.cause===n.error&&e.details?.phase===`publish`))throw n.error}}}const sa=Symbol(`onCopyPublication`),ca=Symbol(`onCopySourceAdmission`);function closeWriteFd(e,t){if(t!==void 0)try{e(t)}catch(e){return{error:e}}}function readParentIdentity(e,t){let n=z(()=>Q.fstatSync(e,{bigint:!0}));if(!n.isDirectory()||!vn(t.stat,n))throw new I(`path-mismatch`,`native write parent identity changed`);return n}function assertNamedParentCurrent(e,t,n){if(typeof e.observeDirectory==`function`)try{if(ye(e,t.dir,n).realPath!==t.realPath)throw new I(`path-mismatch`,`native write parent pathname changed`);return}catch(e){if(e?.code!==`OBSERVATION_UNAVAILABLE`)throw e}W({...t,stat:n})}async function runPinnedWriteWindows(e,t,n,r,i){se(e,`openBeneath`,`renameNoReplace`,`renameReplace`,`fstatIdentity`);let a=V(e),o=i.realPath,s,c,l,u,d,f=``,p=!1,m=!1,h=t.overwrite===!1&&t.input.kind!==`file`&&t.input.stageBeforePublish===!0,g,_=Object.freeze({status:`not-published`}),v=`prepare`,y,closeTemp=async()=>{let e=c,t=s;c=void 0,s=void 0,e?await e.close():t!==void 0&&a(t)};try{f=`.fs-safe-${oi()}.tmp`,t.assertBeforeMutation?.();let n=t.input.kind===`file`&&!t.private?await createNativeCopyFile(e,t.input,r,f,t.maxBytes,Z.join(o,f)):void 0;if(t.private){let e=Q.fstatSync(r,{bigint:!0});c=await createFileHandle(Z.join(o,f),{private:!0,mode:384,assertBeforeMutation:t.assertBeforeMutation},{expectedParentIdentity:{dev:e.dev,ino:e.ino,realPath:o}}),s=c.fd}else if(n)s=n.fd;else try{s=e.openBeneath(r,f,Nt(Q.constants.O_WRONLY|Q.constants.O_CREAT|Q.constants.O_EXCL)).fd}catch(e){throw jt(e,Z.join(o,f)),e}let y=z(()=>Q.fstatSync(s,{bigint:!0}));if(d=y,t.input.kind===`file`&&assertNativeCopyCompleted(t.input,n),(y.mode&128n)==0n&&Q.fchmodSync(s,384),n||await writePinnedInput(s,t.input,t.maxBytes,t.assertBeforeMutation),t.input.kind===`file`&&restoreCopyMetadata(s,t.input.metadata),t.sync!==!1&&(t.strictFileSync?Q.fsyncSync(s):syncFileBestEffortSync(s)),t.input.kind===`file`&&await t.input.verifySource(),h){let e=readParentIdentity(r,i);g=createStagedFileReceipt(Object.freeze({path:i.dir,realPath:i.realPath,identity:Object.freeze({dev:e.dev,ino:e.ino})}),f,Q.fstatSync(s,{bigint:!0}))}if(v=`publish`,L(Z.join(o,t.basename),t.rejectFinalSymlink),t.assertBeforeMutation?.(),t.assertBeforeMutation){assertNamedParentCurrent(e,i,readParentIdentity(r,i)),u=e.openBeneath(r,f,Nt(Q.constants.O_RDONLY)).fd;let n=z(()=>Q.fstatSync(u,{bigint:!0}),y),a=z(()=>Q.fstatSync(s,{bigint:!0}),y);if(!n.isFile()||!a.isFile()||n.nlink!==1n||a.nlink!==1n)throw new I(`path-mismatch`,`native write stage changed before publication`);L(Z.join(o,t.basename),t.rejectFinalSymlink)}t.input.kind===`file`&&t.input.signal?.throwIfAborted();try{t.overwrite===!1?e.renameNoReplace(r,f,r,t.basename):e.renameReplace(r,f,r,t.basename)}catch(e){throw h&&classifyNativeRenameFailure(e)===`indeterminate`&&(_=Object.freeze({status:`indeterminate`,basename:t.basename,overwrite:!1})),e}p=!0,g&&(_=Object.freeze({status:`published`,staged:g,basename:t.basename,overwrite:!1})),t.onPublished?.(y);let b=t.overwrite===!1&&t.input.kind===`buffer`&&t.input.stageBeforePublish!==!1&&!t.private&&!t.assertBeforeMutation&&e.openPublicationMetadata;l=b?b(r,t.basename):e.openBeneath(r,t.basename,Nt(Q.constants.O_RDONLY)).fd;let x=z(()=>Q.fstatSync(l,{bigint:!0}),y);if(!x.isFile())throw new I(`path-mismatch`,`native write target changed after rename`);let S=(x.mode&128n)!==BigInt(t.mode&128);try{S&&Q.fchmodSync(l,t.mode),t.sync!==!1&&(t.strictFileSync?Q.fsyncSync(s):syncFileBestEffortSync(s))}catch(e){throw h||(closeWriteFd(a,l),l=void 0),t.input.kind!==`file`&&!t.input.stageBeforePublish&&Ct({parentPath:o,parentFd:r,basename:t.basename,created:d}),e}return t.sync!==!1&&syncFileBestEffortSync(r),t.overwrite===!1&&t.input.kind===`buffer`&&t.input.stageBeforePublish===!1?await t.verifyPublished?.(l,y,i,{fd:r,binding:e}):await t.verifyPublished?.(l,y,i),m=!0,{dev:x.dev,ino:x.ino}}catch(e){throw y={error:e},e}finally{let e=t.private&&s===void 0&&hasPreservedCreationArtifacts(y?.error);if(h||e)await settleStagedFile({temporaryBasename:f,publication:_,phase:v,failure:y,cleanup:async()=>e||_.status===`indeterminate`?`preserved`:p||s===void 0?`not-needed`:await kt({pathname:Z.join(o,f),handle:{fd:s},identity:d,parentGuard:i,throwOnCleanupError:!0}),close:[()=>{l!==void 0&&a(l)},()=>{u!==void 0&&a(u)},closeTemp,()=>a(r),()=>n.close()]});else{let e=closeWriteFd(a,l),t=closeWriteFd(a,u),i;try{await closeTemp()}catch(e){i={error:e}}p||Ct({parentPath:o,parentFd:r,basename:f,created:d});let s=closeWriteFd(a,r);await n.close().catch(()=>void 0);let c=e??t??i??s;if(m&&c)throw c.error}}}var __addDisposableResource$2=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var dispose,r;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);dispose=t[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);dispose=t[Symbol.dispose],n&&(r=dispose)}if(typeof dispose!=`function`)throw TypeError(`Object not disposable.`);r&&(dispose=function(){try{r.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose,async:n})}else n&&e.stack.push({async:!0});return t},la=(function(e){return function(t){function fail(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var n,r=0;function next(){for(;n=t.stack.pop();)try{if(!n.async&&r===1)return r=0,t.stack.push(n),Promise.resolve().then(next);if(n.dispose){var e=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(e).then(next,function(e){return fail(e),next()})}else r|=1}catch(e){fail(e)}if(r===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return next()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});const ua=[`openBeneath`,`mkdirBeneath`,`renameNoReplace`,`renameReplace`],da=[...ua,`createStagedFile`,`stagedFileMatches`,`removeStagedFile`,`renameReplaceAsync`,`renameNoReplaceAsync`];function pinnedWriteCapabilities(e){let t=process.platform===`win32`,n=t?[...ua,`fstatIdentity`]:da;return e.input.kind===`file`&&!e.private&&(t||!e.verifyPosixMode)?[...n,`copyFileExclusive`]:n}function getPinnedWriteNativeBinding(e){return P(...pinnedWriteCapabilities(e))}async function runPinnedWriteNative(e,t,n){let r={stack:[],error:void 0,hasError:!1};try{se(e,...pinnedWriteCapabilities(t));let i=V(e),a=process.platform===`win32`;a||assertNativeStaging(e);let o=Q.constants.O_RDONLY|(Q.constants.O_DIRECTORY??0),s=t.overwrite===!1&&t.input.kind!==`file`&&t.input.stageBeforePublish===!0,c=await openNativeRootAdmission(e,{rootPath:t.rootPath,rootIdentity:t.rootIdentity,operation:`native write`,reportCloseErrors:s}),l=c.root;__addDisposableResource$2(r,a?void 0:l,!0);let u,d=!1,f;__addDisposableResource$2(r,{[Symbol.dispose](){!a&&u!==void 0&&i(u)}},!1);try{let r,s,f;if(t.mutationAdmission){let n=await capturePolicyAwareNativeParent(e,t,c,a,o);u=n.fd,r=n.guard.realPath,s=n.stagedDirectory,f=n.guard.stat}else{t.mkdir&&(t.assertBeforeMutation?.(),e.mkdirBeneath(l.fd,t.relativeParentPath,511));let n=await openNativeParentAdmission(e,c,t.relativeParentPath,`native-publication`);u=n.fd,r=n.guard.realPath,s=n.stagedDirectory,f=n.guard.stat}let p={dir:r,realPath:r,stat:f};if(t.input.kind===`link`)return await copyLinkAtParent(t,t.input,p,{binding:e,fd:u});if(t.overwrite===!1)try{if(Q.lstatSync(Z.join(r,t.basename),{throwIfNoEntry:!1}))throw Object.assign(/* @__PURE__ */ Error(`destination already exists`),{code:`EEXIST`})}catch(e){if(e.code!==`ENOENT`)throw e}if(a)return d=!0,await runPinnedWriteWindows(e,t,l,u,p);if(t.overwrite===!1&&(t.input.kind!==`buffer`||t.input.stageBeforePublish!==!1)){let r=cachedNoReplaceUnavailable(e,u);if(r){if(st()||t.input.kind===`file`&&t.input.clone===`always`)throw r;return await n(t.input)}}let m=u;return u=void 0,await ea(e,m,i,s,t,p,n)}catch(e){throw f={error:e},e}finally{if(a&&!d){let e=[];if(u!==void 0)try{i(u)}catch(t){e.push(t)}try{await l.close()}catch(t){e.push(t)}if(s&&e.length>0)throw AggregateError([...f?[f.error]:[],...e],`native create admission and close failed`)}}}catch(e){r.error=e,r.hasError=!0}finally{let e=la(r);e&&await e}}function validatePinnedRelativePath(e){if(typeof e==`string`&&e.length!==0&&e!==`.`){if(e.includes(`\0`))throw new I(`invalid-path`,`relative path contains a NUL byte`);if(e.startsWith(`/`)||e===`..`||e.startsWith(`../`)||e.startsWith(`..\\`))throw new I(`invalid-path`,`relative path must not escape root`);for(let t of e.split(process.platform===`win32`?/[\\/]/:`/`))if(t===`..`)throw new I(`invalid-path`,`relative path must not contain '..'`)}}function assertPinnedWriteMode(e,t,n=!1){if(process.platform===`win32`)return;let r=Q.fstatSync(e,{bigint:!0});if(n&&assertPrivateCreationFile(r,e),Number(r.mode&4095n)!==t)throw new I(`insecure-permissions`,`filesystem did not enforce the requested file mode`)}async function preparePinnedWriteMode(e,t,n,r=!1){return process.platform===`win32`?n:(q(n?.(),`assertBeforeMutation`),t!==384&&(r&&assertPrivateCreationFile(Q.fstatSync(e.fd,{bigint:!0}),e.fd),await e.chmod(384)),pinnedWriteModeAssertion(e.fd,384,n,r))}function pinnedWriteModeAssertion(e,t,n,r=!1){return()=>{q(n?.(),`assertBeforeMutation`),assertPinnedWriteMode(e,t,r)}}async function publishCopyStage(e){let{identity:t,temporaryPath:n,targetPath:r}=e,assertCurrent=()=>{W(e.parentGuard);let r=Q.lstatSync(n,{bigint:!0}),i=Q.fstatSync(e.fd,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.nlink!==1n||!H(r,t)||!H(i,t))throw new I(`path-mismatch`,`exclusive copy stage changed before publication`)};if(assertCurrent(),e.assertBeforeMutation?.(),e.assertBeforeMutation&&assertCurrent(),Q.lstatSync(r,{throwIfNoEntry:!1}))throw new I(`already-exists`,`destination already exists`);e.onPublicationAttempt?.();let i=!1;try{Q.linkSync(n,r)}catch(t){if(!isHardlinkFallbackError(t))throw t;publishThroughPlaceholder(e,assertCurrent),i=!0}let a=!1,o;try{e.onPublished?.(t)}catch(e){a=!0,o=e}try{if(i){if(W(e.parentGuard),Q.lstatSync(n,{throwIfNoEntry:!1}))throw new I(`path-mismatch`,`renamed copy stage still exists`);let i=Q.lstatSync(r,{bigint:!0});if(!i.isFile()||i.isSymbolicLink()||i.nlink!==1n||!H(i,t))throw new I(`path-mismatch`,`renamed copy target changed after publication`)}else{let verifyPair=()=>{W(e.parentGuard);let i=Q.lstatSync(Z.dirname(n),{bigint:!0}),a=Q.lstatSync(n,{bigint:!0}),o=Q.lstatSync(r,{bigint:!0});if(i.isSymbolicLink()||!i.isDirectory()||!H(i,e.parentGuard.stat)||a.isSymbolicLink()||!a.isFile()||a.nlink!==2n||o.isSymbolicLink()||!o.isFile()||o.nlink!==2n||!H(a,t)||!H(o,t))throw new I(`path-mismatch`,`published copy temporary name changed before cleanup`)};verifyPair(),e.beforeTemporaryUnlink&&(await e.beforeTemporaryUnlink(),verifyPair()),Q.unlinkSync(n)}}catch(e){throw new I(`helper-failed`,`published copy temporary cleanup failed`,{cause:a?AggregateError([o,e],`observer and cleanup failed`):e,details:{publication:`published`,path:r,dev:t.dev,ino:t.ino,cleanup:`failed`}})}if(a)throw o}function isEmptyPlaceholder(e,t){return e.isFile()&&!e.isSymbolicLink()&&e.nlink===1n&&e.size===0n&&H(e,t)}function publishThroughPlaceholder(e,t){let{targetPath:n,temporaryPath:r}=e;t();let i;try{re(n),i=Q.openSync(n,Q.constants.O_WRONLY|Q.constants.O_CREAT|Q.constants.O_EXCL|(Q.constants.O_NOFOLLOW??0),384)}catch(e){throw At(e,`EEXIST`)?new I(`already-exists`,`destination already exists`,{cause:e}):e}let a;try{try{a=Q.fstatSync(i,{bigint:!0})}finally{Q.closeSync(i)}t();let e=Q.lstatSync(n,{bigint:!0,throwIfNoEntry:!1});if(!e||!isEmptyPlaceholder(e,a))throw new I(`path-mismatch`,`exclusive copy placeholder changed before publication`);Q.renameSync(r,n)}catch(t){try{W(e.parentGuard);let t=Q.lstatSync(n,{bigint:!0,throwIfNoEntry:!1});if(t){if(!a)throw new I(`path-mismatch`,`copy placeholder identity unavailable for cleanup`);isEmptyPlaceholder(t,a)&&Q.unlinkSync(n)}}catch(e){throw new I(`helper-failed`,`unpublished copy placeholder cleanup failed`,{cause:AggregateError([t,e],`publication and cleanup failed`),details:{publication:`not-published`,path:n,cleanup:`failed`,...a?{dev:a.dev,ino:a.ino}:{}}})}throw t}}async function openPublicationHandle(e,t){let n=ke(),r=await $.open(e,n).catch(async t=>{if(!At(t,`EACCES`)||process.arch!==`x64`&&process.arch!==`arm64`)throw t;let n=process.platform===`linux`?2097152:void 0;if(n===void 0)throw t;return $.open(e,n|Q.constants.O_NOFOLLOW)});try{let n=Q.fstatSync(r.fd,{bigint:!0}),i=Q.lstatSync(e,{bigint:!0});if(!n.isFile()||!i.isFile()||i.isSymbolicLink()||!H(n,t)||!H(i,t))throw new I(`path-mismatch`,`publication descriptor handoff identity changed`);return r}catch(e){throw await r.close().catch(()=>void 0),e}}async function runPinnedStagedWrite(e,t,n){let r=process.platform!==`win32`&&(e.verifyPosixMode===!0||e.private===!0),i=Z.join(t,e.basename),a=Z.join(t,`.fs-safe-${oi()}.tmp`),o=Q.constants.O_WRONLY|Q.constants.O_CREAT|Q.constants.O_EXCL|(process.platform!==`win32`&&`O_NOFOLLOW`in Q.constants?Q.constants.O_NOFOLLOW:0),s,c,u,d,f=!1,p=e.overwrite===!1&&e.input.kind!==`file`&&e.input.stageBeforePublish===!0,m,h=Object.freeze({status:`not-published`}),g=`prepare`,_;try{e.assertBeforeMutation?.(),re(a),s=e.private?await createFileHandle(a,{private:!0,mode:384,assertBeforeMutation:e.assertBeforeMutation},creationAdmissionFromParent(n)):await $.open(a,o,r?384:e.mode);let _=Q.fstatSync(s.fd,{bigint:!0});c=_;let v=e.assertBeforeMutation,y=r?await preparePinnedWriteMode(s,Number(c.mode&4095n),v,e.private):v;r&&assertPinnedWriteMode(s.fd,384,e.private),await writePinnedInput(s,e.input,e.maxBytes,y),r&&assertPinnedWriteMode(s.fd,384,e.private);let b=Q.fstatSync(s.fd,{bigint:!0}),x=Q.lstatSync(a,{bigint:!0});if(x.isSymbolicLink()||!Be(x,b))throw new I(`path-mismatch`,`fallback temp path changed during write`);let S=b;Q.fchmodSync(s.fd,e.mode),e.input.kind===`file`&&restoreCopyMetadata(s.fd,e.input.metadata),r&&(assertPinnedWriteMode(s.fd,e.mode,e.private),v=pinnedWriteModeAssertion(s.fd,e.mode,e.assertBeforeMutation,e.private)),e.sync!==!1&&(e.strictFileSync?await s.sync():await syncFileBestEffort(s)),e.input.kind===`file`&&await e.input.verifySource(),p&&(m=createStagedFileReceipt(Object.freeze({path:n.dir,realPath:n.realPath,identity:Object.freeze({dev:n.stat.dev,ino:n.stat.ino})}),Z.basename(a),Q.fstatSync(s.fd,{bigint:!0})));let C=S,w=process.platform!==`win32`&&(!!(e.mode&256)||process.platform===`linux`&&(process.arch===`x64`||process.arch===`arm64`));return g=`publish`,await Gt([n],async()=>{L(i,e.rejectFinalSymlink),e.overwrite===!1?await publishCopyStage({temporaryPath:a,targetPath:i,fd:s.fd,identity:c,parentGuard:n,assertBeforeMutation:v,onPublicationAttempt:()=>{m&&(h=Object.freeze({status:`indeterminate`,basename:e.basename,overwrite:!1}))},onPublished:t=>{f=!0,m&&(h=Object.freeze({status:`published`,staged:m,basename:e.basename,overwrite:!1})),e.onPublished?.(t)},beforeTemporaryUnlink:w?async()=>{u=await openPublicationHandle(i,S);let e=s;s=void 0;try{await e.close()}catch(e){d={error:e}}}:void 0}):(v?.(),await $.rename(a,i),f=!0,e.onPublished?.(_)),await l()?.afterPinnedWriteFallbackRename?.(i),e.sync!==!1&&await syncDirectoryBestEffort(t);let r=Q.lstatSync(i,{bigint:!0});if(r.isSymbolicLink())throw new I(`path-mismatch`,`fallback target changed during write`);if(!Be(r,S)){if(e.onRenameIdentityMismatch!==`verify-content`||e.input.kind!==`buffer`)throw new I(`path-mismatch`,`fallback target changed during write`);let t=Ze(e.input.data,e.input.encoding);await u?.close(),u=await $.open(i,ke());let n=Q.fstatSync(u.fd,{bigint:!0});if(Ze(await we(u,1/0))!==t)throw new I(`path-mismatch`,`fallback target changed during write`);_=n,C=n}}),await e.verifyPublished?.((u??s).fd,_,n),r&&assertPinnedWriteMode((u??s).fd,e.mode,e.private),{dev:C.dev,ino:C.ino}}catch(e){throw _={error:e},e}finally{let t=e.private&&!s&&hasPreservedCreationArtifacts(_?.error);if(p||t)await settleStagedFile({temporaryBasename:Z.basename(a),publication:h,phase:g,failure:_,cleanup:async()=>t||h.status===`indeterminate`?`preserved`:f?_?.error instanceof I&&_.error.details?.cleanup===`failed`?`failed`:`not-needed`:s?await kt({pathname:a,handle:s,identity:c,parentGuard:n,throwOnCleanupError:!0}):`not-needed`,close:[async()=>{await u?.close()},async()=>{if(await s?.close(),d)throw d.error}]});else try{!f&&s&&await kt({pathname:a,handle:s,identity:c,parentGuard:n})}finally{await u?.close().catch(()=>void 0),await s?.close().catch(()=>void 0)}}}function assertSafeBasename(e){if(!e||e===`.`||e===`..`||e.includes(`/`)||process.platform===`win32`&&e.includes(`\\`)||e.includes(`\0`))throw new I(`invalid-path`,`invalid target path`)}function fastParentGuardDeopt(e){return e instanceof I&&(e.code===`path-mismatch`||e.code===`not-file`)}const fa=[`rootPath`,`relativeParentPath`,`basename`,`maxBytes`,`rootIdentity`],pa=[`targetPath`,`renameIdentity`];function copyOwnEnumerableExcept(e,t){let n={};for(let r of Reflect.ownKeys(e))t.includes(r)||Object.getOwnPropertyDescriptor(e,r)?.enumerable&&Object.defineProperty(n,r,{value:Reflect.get(e,r),enumerable:!0,writable:!0,configurable:!0});return n}async function runPinnedWriteHelper(e){let{rootPath:t,relativeParentPath:n,basename:r,maxBytes:i,rootIdentity:a}=e,o={...copyOwnEnumerableExcept(e,fa),rootPath:t,relativeParentPath:n,basename:r,maxBytes:Ye(i),rootIdentity:a};if(assertSafeBasename(o.basename),validatePinnedRelativePath(o.relativeParentPath),w(o.rootPath,`filesystem`,`pinned write root uses a Windows filesystem namespace alias`),w(o.relativeParentPath,`relative`,`pinned write parent uses a Windows filesystem namespace alias`),w(o.basename,`relative`,`pinned write basename uses a Windows filesystem namespace alias`),a!==void 0&&(o.rootIdentity={dev:a.dev,ino:a.ino}),o.mutationAdmission){let e=Z.join(o.rootPath,...o.relativeParentPath.split(`/`).filter(Boolean),o.basename);await l()?.beforePinnedWriteParentAdmission?.(e)}if(o.onRenameIdentityMismatch===`verify-content`)return await runPinnedWriteFallback(o);let s=getPinnedWriteNativeBinding(o);return s?await runPinnedWriteNative(s,o,e=>runPinnedWriteFallback({...o,input:e})):await runPinnedWriteFallback(o)}async function runPinnedWriteWithRenamePolicy(e){let{targetPath:t,renameIdentity:n}=e,r=copyOwnEnumerableExcept(e,pa);if(n!==`verify-content-with-lock`)return await runPinnedWriteHelper(r);let i=r.relativeParentPath?`${r.relativeParentPath}/${r.basename}`:r.basename;return await withPinnedWriteRenameIdentityLock({rootPath:r.rootPath,targetPath:t,relativeTargetPath:i},async()=>await runPinnedWriteHelper({...r,onRenameIdentityMismatch:`verify-content`}))}async function withPinnedWriteRenameIdentityLock(e,t){let n=Z.join(e.rootPath,`.fs-safe-write-${Ze(e.relativeTargetPath)}.lock`);return await Qt(e.rootPath,{managerKey:`fs-safe.write:${e.targetPath}`,lockPath:n,staleMs:3e4,timeoutMs:5e3,payload:()=>({pid:process.pid,createdAt:(/* @__PURE__ */ new Date()).toISOString()}),retry:{retries:5,minTimeout:100,maxTimeout:2e3,factor:2}},t)}async function runPinnedWriteFallback(e){let t=process.platform!==`win32`&&(e.verifyPosixMode===!0||e.private===!0),n=typeof e.rootIdentity?.dev==`bigint`&&typeof e.rootIdentity.ino==`bigint`?{dev:e.rootIdentity.dev,ino:e.rootIdentity.ino}:void 0,r=e.mutationAdmission;n&&await Pe(e.rootPath,n);let i=e.relativeParentPath?Z.join(e.rootPath,...e.relativeParentPath.split(`/`)):e.rootPath,a,o=!1,s=Z.join(i,e.basename),c=r?.beginParentWalk?.(),u=c!==void 0&&Z.relative(Z.resolve(c),Z.resolve(s))===``,d;if(u){try{a=await F(i,{bigint:!0})}catch(e){if(e?.code!==`ENOENT`){if(!fastParentGuardDeopt(e))throw e;d=e}}a&&(await r.authorize(Object.freeze({targetPath:s,mutationPath:s,phase:`parent`})),await A(a),o=!0)}if(d&&await r.authorize(Object.freeze({targetPath:s,mutationPath:s,phase:`parent`})),!a){let t={rootReal:e.rootPath,targetPath:i,rootIdentity:e.rootIdentity,createMissing:e.mkdir,assertBeforeMutation:e.assertBeforeMutation,beforeComponent:async t=>{e.mkdir&&await l()?.beforeRootFallbackMutation?.(`mkdir`,t)}};i=await mkdirPathComponentsWithGuards(r?{...t,rejectSymlinks:r.rejectParentSymlinks,revalidateParentAfterBeforeComponent:!0,synchronousAuthorizationIncludesFence:!0,retainedTargetPath:c,afterCreateComponent:r.advanceCreatedDirectory,beforeCreateComponent:(t,n,i,a)=>{if(d)throw d;let o=Object.freeze({targetPath:i??Z.join(n,e.basename),mutationPath:t,phase:`parent-create`});return r.tryAuthorizeAtParent?.(o,a)??r.authorize(o)},beforeUseComponent:async(t,n,i)=>{let a=i??Z.join(n,e.basename);await r.authorize(Object.freeze({targetPath:a,mutationPath:a,phase:`parent`}))}}:t)}a??=await F(i,{bigint:!0});let f=Z.join(i,e.basename);if(r&&!o&&(await r.authorize(Object.freeze({targetPath:f,mutationPath:f,phase:`parent`})),await A(a)),e.input.kind===`link`)return await copyLinkAtParent(e,e.input,a);if(e.overwrite===!1&&e.input.kind!==`file`&&!e.input.stageBeforePublish){let assertBeforeMutation=()=>{L(f,e.rejectFinalSymlink),e.assertBeforeMutation?.()},n=await Gt([a],async()=>(assertBeforeMutation(),e.private?await createFileHandle(f,{private:!0,mode:384,assertBeforeMutation},creationAdmissionFromParent(a)):(re(f),await $.open(f,Q.constants.O_WRONLY|Q.constants.O_CREAT|Q.constants.O_EXCL,t?384:e.mode))),{onPostGuardFailure:async e=>{await e.close().catch(()=>void 0)}}),r=!0,o=!1,s;try{let c=Q.fstatSync(n.fd,{bigint:!0});s=c;let l=t?await preparePinnedWriteMode(n,Number(s.mode&4095n),assertBeforeMutation,e.private):assertBeforeMutation;t&&assertPinnedWriteMode(n.fd,384,e.private),await writePinnedInput(n,e.input,e.maxBytes,l),t&&assertPinnedWriteMode(n.fd,384,e.private),Q.fchmodSync(n.fd,e.mode),t&&assertPinnedWriteMode(n.fd,e.mode,e.private),e.sync!==!1&&(e.strictFileSync?await n.sync():await syncFileBestEffort(n));let u=Q.fstatSync(n.fd,{bigint:!0});return e.sync!==!1&&await syncDirectoryBestEffort(i),r=!1,await e.verifyPublished?.(n.fd,c,a),t&&assertPinnedWriteMode(n.fd,e.mode,e.private),o=!0,{dev:u.dev,ino:u.ino}}finally{try{r&&await kt({pathname:f,handle:n,identity:s,parentGuard:a})}finally{o?await n.close():await n.close().catch(()=>void 0)}}}return await runPinnedStagedWrite(e,i,a)}async function copyFileInRoot(e,t,n){if(t.signal?.throwIfAborted(),resolveCopyCloneMode(t.clone,`never`),t.sourceSymlinks!==void 0&&t.sourceSymlinks!==`reject`&&t.sourceSymlinks!==`copy-link`)throw new I(`invalid-path`,`sourceSymlinks must be reject or copy-link`);if(t.sourceSymlinks===`copy-link`){if(typeof t.source!=`string`)throw new I(`invalid-path`,`sourceSymlinks: copy-link requires an absolute-path string source; open/stat capabilities cannot observe links without following them`);let n=await admitCopyLink(Nn(t.source),t.preserveMetadata===!0,t.signal).catch(e=>{throw pt(e)});if(n){if(t.overwrite===!0)throw new I(`invalid-path`,`copy-link cannot overwrite an existing destination; omit overwrite or use false`);assertCopyLinkAvailable();let r=t.mode??(t.preserveSourceMode?Number(n.identity.mode&4095n):void 0);await copyInputInRoot(e,{...t,overwrite:!1},n,r);return}}let r=resolveFileCopyCloneMode(t.clone),i,a;if(typeof t.source==`string`)ht(t.source,`source path contains a NUL byte`),w(t.source,`filesystem`,`source path uses a Windows filesystem namespace alias`),{opened:i,identity:a}=await n(t.source,{hardlinks:t.sourceHardlinks});else{i=await t.source.root.open(t.source.relativePath,t.sourceHardlinks===void 0?void 0:{hardlinks:t.sourceHardlinks});try{a=z(()=>Q.fstatSync(i.handle.fd,{bigint:!0}))}catch(e){throw await i.handle.close().catch(()=>void 0),e}}try{if(t.maxBytes!==void 0&&i.stat.size>t.maxBytes)throw new I(`too-large`,`file exceeds limit of ${t.maxBytes} bytes (got ${i.stat.size})`);let n;try{n=t.preserveMetadata?captureCopyMetadata(i.handle.fd,a):void 0}catch(e){throw pt(e)}let o=t.admitSource?.(a,i.realPath),verifySource=async()=>{t.signal?.throwIfAborted();try{o?.verify()}catch(e){throw new Pt(e)}typeof t.source!=`string`&&await t.source.root.stat(`.`),assertCopySourceCurrent(i,a)},s=o?.mode??t.mode??(t.preserveSourceMode?Number(a.mode&4095n):void 0);await copyInputInRoot(e,t,{kind:`file`,handle:i.handle,size:i.stat.size,clone:r,signal:t.signal,metadata:n,verifySource},s,()=>assertCopySourceCurrent(i,a))}finally{await i.handle.close().catch(()=>{})}}async function copyInputInRoot(e,t,n,r,i=n.verifySource){if(r!==void 0&&(!Number.isInteger(r)||r<0||r>4095))throw new I(`invalid-path`,`invalid copy mode`);await St(rootWriteQueueKey(e,t.relativePath),async()=>{let a=await resolvePinnedWriteTargetInRoot(e,t.relativePath,r,t.denyMutations,t.overwrite!==!1,t.mutationSymlinks);await St(a.targetPath,async()=>{await i();let r=createCopyPublicationObserver(a.targetPath,t.onDestinationPublished);try{await runPinnedWriteHelper({rootPath:a.rootReal,relativeParentPath:a.relativeParentPath,basename:a.basename,mkdir:t.mkdir!==!1,mode:a.mode,overwrite:t.overwrite!==!1,rejectFinalSymlink:t.mutationSymlinks!==void 0,maxBytes:t.maxBytes,sync:t.durable!==!1,assertBeforeMutation:t.signal||t.assertBeforeMutation?()=>{if(t.signal?.aborted)throw new Pt(t.signal.reason);t.assertBeforeMutation?.()}:void 0,verifyPublished:t.verifyPublished,onPublished:r.onPublished,input:n,rootIdentity:e.rootIdentity,mutationAdmission:a.mutationAdmission})}catch(e){throw r.rethrowObserverFailure(e),t.signal?.aborted&&e===t.signal.reason?e:Ue(e)?new I(`already-exists`,`copy destination already exists`,{cause:e}):pt(e)}await n.verifySource()})})}const ma=ke(),ha=ke({followSymlinks:!0});async function openLocalFileDescriptor(e,t){oe(e);let n=l(),r,i=!1;try{r=z(()=>{let n=Q.lstatSync(e,{bigint:!0});if(i=!0,n.isSymbolicLink()&&t?.symlinks!==`follow-within-root`)throw new I(`symlink`,`symlink not allowed`);if(!n.isFile()&&!n.isSymbolicLink())throw new I(`not-file`,`not a file`);return n})}catch(e){if(e instanceof I||i)throw e}r&&n?.afterPreOpenLstat&&await n.afterPreOpenLstat(e);let a=(t?.symlinks===`follow-within-root`?ha:ma)|(t?.readWrite?Q.constants.O_RDWR:0);n?.beforeOpen&&await n.beforeOpen(e,a);let o;try{o=await $.open(e,a).catch(t=>recordFileOpenFailure(E(t)?Qe():t,e))}catch(e){throw S(e)?new I(`symlink`,`symlink open blocked`,{cause:e}):j(e,`EISDIR`)?new I(`not-file`,`not a file`):e}try{n?.afterOpen&&await n.afterOpen(e,o);let i,a;try{a=z(()=>{if(i=Q.fstatSync(o.fd,{bigint:!0}),!i.isFile())throw new I(`not-file`,`not a file`);return i},r&&!r.isSymbolicLink()?r:void 0)}catch(t){throw i&&[0n,1n].includes(i.nlink)&&await recordPreOpenFileChange(t,o,e,r,i),t}if(!a.isFile())throw new I(`not-file`,`not a file`);let s=He(a);if(t?.hardlinks===`reject`&&s.nlink>1)throw R();return{handle:o,stat:s,identity:a,preOpenStat:r}}catch(e){throw await o.close().catch(()=>{}),e}}async function resolveOpenedFileRealPathForFd(e,t,n){let r=typeof t.dev==`bigint`||typeof t.ino==`bigint`?{bigint:!0}:void 0,i=process.platform===`linux`?[`/proc/self/fd/${e}`,`/dev/fd/${e}`]:[];for(let e of i)try{let n=e.startsWith(`/proc/`)?Q.readlinkSync(e):void 0,i=n!==void 0&&!n.endsWith(` (deleted)`)?n:O.native(e);if(!Z.isAbsolute(i))continue;let a=r?Q.statSync(i,r):Q.statSync(i);if(Be(t,a))return{realPath:i,stat:a}}catch{}try{let e=O.native(n),i=r?Q.statSync(e,r):Q.statSync(e);if(Be(t,i))return{realPath:e,stat:i}}catch(e){if(!E(e))throw process.platform===`win32`&&e instanceof Error&&[`EPERM`,`EBADF`].includes(e.code??``)?openedPathResolutionError(e):e}let a=await resolveOpenedFileRealPathFromParent(t,n,r);if(a)return a;throw openedPathResolutionError()}async function resolveOpenedFileRealPathFromParent(e,t,n){let r;try{r=O.native(Z.dirname(t))}catch(e){if(E(e))return null;throw e}let i;try{i=await $.readdir(r)}catch(e){if(E(e))return null;throw e}for(let t of i.toSorted()){let i=Z.join(r,t);try{let t=n?Q.lstatSync(i,n):Q.lstatSync(i);if(t.isFile()&&Be(e,t)){let t=O.native(i),r=n?Q.statSync(t,n):Q.statSync(t);if(Be(e,r))return{realPath:t,stat:r}}}catch(e){if(!E(e))throw e}}return null}async function readOpenedFileSafely(e){let t=Ye(e.maxBytes);if(t!==void 0&&e.opened.stat.size>t)throw new I(`too-large`,`file exceeds limit of ${t} bytes (got ${e.opened.stat.size})`);return{buffer:await De(e.opened.handle,t??1/0,e.opened.stat.size),containment:e.opened.containment,realPath:e.opened.realPath,stat:e.opened.stat,exactIdentity:e.opened.exactIdentity}}var __addDisposableResource$1=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var dispose,r;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);dispose=t[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);dispose=t[Symbol.dispose],n&&(r=dispose)}if(typeof dispose!=`function`)throw TypeError(`Object not disposable.`);r&&(dispose=function(){try{r.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose,async:n})}else n&&e.stack.push({async:!0});return t},ga=(function(e){return function(t){function fail(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var n,r=0;function next(){for(;n=t.stack.pop();)try{if(!n.async&&r===1)return r=0,t.stack.push(n),Promise.resolve().then(next);if(n.dispose){var e=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(e).then(next,function(e){return fail(e),next()})}else r|=1}catch(e){fail(e)}if(r===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return next()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});function tryMkdirNativeParents(e,t,n){try{return mkdirOrdinaryNativeParents(e,t,n)}catch(e){throw j(e,`ENOTDIR`)?Ve(e):e}}function mkdirOrdinaryNativeParents(e,t,n){if(l()?.beforeRootFallbackMutation)return!1;let r=t.split(Z.sep===`\\`?/[\\/]/:`/`);if(r.length<2||r.some(e=>!me(e,{allowDotPrefix:!0})||e.endsWith(`.`)))return!1;let i;assertRootIdentityCurrentSync(e,e=>{i=e});let a=Z.join(e.rootReal,...r),o=Z.dirname(a);try{let e=Q.lstatSync(D(a),{throwIfNoEntry:!1});if(e&&(!e.isDirectory()||O.native(D(a))!==a))return!1}catch{return!1}let s;try{s=B(o)}catch(t){return j(t,`ENOENT`)?mkdirMissingParents(e,r,i,n):!1}try{if(O.native(D(o))!==o)return!1}catch{return!1}return mkdirExistingParent(e,r,s,n)}function mkdirMissingParents(e,t,n,r){let i=P(`openBeneath`,`mkdirChildBeneath`);if(!i?.openBeneath||!i.mkdirChildBeneath||!i.mkdirOpenChildBeneath&&r===void 0)return!1;let a=t.length-2,o,s;for(;;){o=Z.join(e.rootReal,...t.slice(0,a));try{if(s=B(o,void 0,a===0?n:void 0),O.native(D(o))!==o)return!1;break}catch(e){if(!j(e,`ENOENT`)||a===0)return!1;a--}}try{let n={stack:[],error:void 0,hasError:!1};try{let c=__addDisposableResource$1(n,openExactNativeRootSync(i,{rootPath:e.rootReal,rootIdentity:e.rootIdentity}),!1),l=V(i),u=[];__addDisposableResource$1(n,{[Symbol.dispose](){let e=[];for(let t of u.toReversed())try{l(t.fd)}catch(t){e.push(t)}if(e.length)throw AggregateError(e,`mkdir directory close failed`)}},!1);let d=(r===void 0?Et()?.flags??Q.constants.O_RDONLY:Q.constants.O_RDONLY)|(Q.constants.O_DIRECTORY??0)|(Q.constants.O_NOFOLLOW??0),f=c.fd;a>0&&(f=i.openBeneath(c.fd,t.slice(0,a).join(`/`),d).fd,u.push({fd:f,pathname:o}),z(()=>Q.fstatSync(f,{bigint:!0}),s));let assertCurrent=()=>{assertRootIdentityCurrentSync(e);for(let e of u)verifyMkdirDirectory(i,e.fd,e.pathname);verifyMkdirDirectory(i,c.fd,e.rootReal)};assertCurrent();for(let e of t.slice(a)){let t=i.mkdirOpenChildBeneath?i.mkdirOpenChildBeneath(f,e,r??511,d):{created:i.mkdirChildBeneath(f,e,r??511),fd:i.openBeneath(f,e,d).fd};o=Z.join(o,e),u.push({fd:t.fd,pathname:o}),assertCurrent(),r!==void 0&&t.created&&(bt(t,r),assertCurrent()),f=t.fd}return!0}catch(e){n.error=e,n.hasError=!0}finally{ga(n)}}catch(e){throw j(e,`ENOTDIR`)?Ve(e):e}}function mkdirExistingParent(e,t,n,r){let i={stack:[],error:void 0,hasError:!1};try{let a=Z.join(e.rootReal,...t),o=Z.dirname(a),s=P(`openBeneath`,`mkdirChildBeneath`);if(!s?.openBeneath||!s.mkdirChildBeneath)throw new I(`helper-unavailable`,`native confined creation is unavailable`);let c=__addDisposableResource$1(i,openExactNativeRootSync(s,{rootPath:e.rootReal,rootIdentity:e.rootIdentity}),!1);verifyMkdirDirectory(s,c.fd,e.rootReal);let l=(r===void 0?Et()?.flags??Q.constants.O_RDONLY:Q.constants.O_RDONLY)|(Q.constants.O_DIRECTORY??0)|(Q.constants.O_NOFOLLOW??0),u=V(s),d=s.openBeneath(c.fd,t.slice(0,-1).join(`/`),l).fd;__addDisposableResource$1(i,{[Symbol.dispose](){u(d)}},!1),z(()=>Q.fstatSync(d,{bigint:!0}),n),verifyMkdirDirectory(s,d,o),assertRootIdentityCurrentSync(e);let f=t.at(-1),p=s.mkdirOpenChildBeneath?s.mkdirOpenChildBeneath(d,f,r??511,l):{created:s.mkdirChildBeneath(d,f,r??511),fd:s.openBeneath(d,f,l).fd};return __addDisposableResource$1(i,{[Symbol.dispose](){u(p.fd)}},!1),assertRootIdentityCurrentSync(e),verifyMkdirDirectory(s,p.fd,a),B(o,n),verifyMkdirDirectory(s,d,o),verifyMkdirDirectory(s,c.fd,e.rootReal),r!==void 0&&p.created&&(bt(p,r),verifyMkdirDirectory(s,p.fd,a),verifyMkdirDirectory(s,d,o),verifyMkdirDirectory(s,c.fd,e.rootReal),assertRootIdentityCurrentSync(e)),!0}catch(e){i.error=e,i.hasError=!0}finally{ga(i)}}var RemovalPathReceipts=class{rootStat;directories;observeRoot=e=>{this.rootStat=e};observeDirectory(e,t){let n=this.directories??=/* @__PURE__ */ new Map;n.has(e)||n.set(e,{path:e,stat:t})}complete(e,t){let n=Z.dirname(t);if(!this.rootStat||!k(e,n))return;let r=[],i=n;for(;i!==e;){let e=this.directories?.get(i);if(!e)return;r.push(e);let t=Z.dirname(i);if(t===i)return;i=t}return r.reverse(),{rootStat:this.rootStat,parent:r.at(-1),directories:r}}};function directoryEntryName(e){if(!Ci(e))throw new I(`invalid-path`,`directory entry name is not valid UTF-8`);return e.toString(`utf8`)}async function readDirectoryNames(e){let t=await $.readdir(e);return t.some(e=>e.includes(`�`))?(await $.readdir(e,{encoding:`buffer`})).map(directoryEntryName):t}async function readDirectoryEntryName(e,t=!1){let n=t?e.readSync():await e.read();return n===null?void 0:directoryEntryName(Buffer.isBuffer(n)?n:n.name)}function openDirectoryNames(e){return $.opendir(e,{bufferSize:1,encoding:`buffer`})}function pathStatFromStats(e,t){let n=typeof e.mtimeMs==`bigint`?`mtimeNs`in e&&typeof e.mtimeNs==`bigint`?Number(e.mtimeNs)/1e6:e.mtime.getTime():e.mtimeMs,r=Xe(e),i=We(e.dev),a=We(e.gid),o=We(e.ino),s=e.isDirectory(),c=e.isFile(),l=e.isSymbolicLink(),u=We(e.mode),d=We(e.nlink),f=We(e.size),p=We(e.uid);return Object.defineProperty(t===void 0?{dev:i,gid:a,ino:o,isDirectory:s,isFile:c,isSymbolicLink:l,mode:u,mtimeMs:n,nlink:d,size:f,uid:p}:{name:t,dev:i,gid:a,ino:o,isDirectory:s,isFile:c,isSymbolicLink:l,mode:u,mtimeMs:n,nlink:d,size:f,uid:p},"exactIdentity",{value:r})}async function createRootDirectoryObservationGuard(e,t){let n=await F(t,{bigint:!0}),r=M({rootPath:e.rootReal,candidatePath:n.realPath,rootIdentity:e.rootIdentity});if(!r)throw new I(`outside-workspace`,`directory is outside workspace root`);return n.dir=r.path,n.realPath=r.path,n}function directoryChangedError(e){return e instanceof I&&e.code===`path-mismatch`?e:new I(`path-mismatch`,`directory changed during operation`,U(e))}async function assertRootDirectoryObservationGuard(e,t,n){if(te(t))throw new I(`path-mismatch`,`native directory observation cannot be revalidated`);let r=`identity`in t?t.identity:t.stat;if(t.dir===e.rootReal&&r.dev===e.rootIdentity.dev&&r.ino===e.rootIdentity.ino)try{n&&`identity`in t?assertReceiptDirectoryGuardSync(e,t,n):`identity`in t?ct(t):await A(t)}catch(e){throw T(e instanceof Error?e:void 0)}else{if(`identity`in t&&typeof e.rootIdentity.dev==`bigint`&&typeof e.rootIdentity.ino==`bigint`)try{$e(e.rootReal,e.rootIdentity)}catch(e){throw T(e instanceof Error?e:void 0)}else await assertRootIdentityCurrent(e);try{n&&`identity`in t?assertReceiptDirectoryGuardSync(e,t,n):`identity`in t?ct(t):await A(t)}catch(e){throw directoryChangedError(e)}}}function assertReceiptDirectoryGuardSync(e,t,n){if(n){let r=ye(n,t.dir,t.identity),i=M({rootPath:e.rootReal,candidatePath:r.realPath,rootIdentity:e.rootIdentity});if(!i||i.path!==t.realPath)throw new I(`path-mismatch`,`directory changed during operation`)}else{if(te(t))throw new I(`path-mismatch`,`native directory observation cannot be revalidated`);ct(t)}}function assertRootPathObservationReceiptCurrent(e,t,n){let{rootGuard:r,directoryGuard:i}=t;if(r.dir!==e.rootReal||r.realPath!==e.rootReal||r.identity.dev!==e.rootIdentity.dev||r.identity.ino!==e.rootIdentity.ino)throw T();if(r.dir===i.dir&&r.realPath===i.realPath&&r.identity.dev===i.identity.dev&&r.identity.ino===i.identity.ino)try{if(t.kind===`stat`&&t.target===r&&n&&!t.directoryObserver){if(n.isSymbolicLink()||!n.isDirectory()||O.native(r.dir)!==r.realPath)throw new I(`path-mismatch`,`root path changed during operation`)}else assertReceiptDirectoryGuardSync(e,i,t.directoryObserver)}catch(e){throw T(e instanceof Error?e:void 0)}else{try{$e(r.dir,r.identity)}catch(e){throw T(e instanceof Error?e:void 0)}try{assertReceiptDirectoryGuardSync(e,i,t.directoryObserver)}catch(e){throw directoryChangedError(e)}}}function normalizeDirectoryError(e){return E(e)?new I(`not-found`,`directory not found`,U(e)):e}async function listDirectoryPath(e,t,n,r){let i;if(r)i=directoryGuardFromReceipt(t,r);else try{i=await createRootDirectoryObservationGuard(e,t)}catch(e){throw e instanceof I&&e.code===`not-file`?new I(`not-found`,`directory not found`,{cause:e}):normalizeDirectoryError(e)}return await listGuardedDirectoryPath(e,i,n,r)}function directoryGuardFromReceipt(e,t){if(t.kind!==`directory`||t.targetPath!==e||t.directoryGuard.dir!==e||t.target!==t.directoryGuard||!te(t.directoryGuard)&&!t.directoryGuard.stat.isDirectory())throw new I(`path-mismatch`,`directory observation receipt does not match target`);return t.directoryGuard}async function listGuardedDirectoryPath(e,t,n,r){let i;try{let e=l()?.beforeRootListObservation;e&&await e(t.realPath,n);let r=(await readDirectoryNames(t.realPath)).sort();if(n){let e=t.realPath.endsWith(Z.sep)?t.realPath:`${t.realPath}${Z.sep}`;i=r.map(t=>pathStatFromStats(Q.lstatSync(`${e}${t}`,{bigint:!0}),t))}else i=r}catch(n){throw r?assertRootPathObservationReceiptCurrent(e,r):await assertRootDirectoryObservationGuard(e,t),normalizeDirectoryError(n)}return r?assertRootPathObservationReceiptCurrent(e,r):await assertRootDirectoryObservationGuard(e,t),i}async function openRootDirectoryListing(e,t,n,r){if(n.exactIdentity&&n.order!==`filesystem`)throw TypeError(`exact entry identities require filesystem order`);let i;if(r)i=directoryGuardFromReceipt(t,r);else{let n=await createRootDirectoryObservationGuard(e,t).catch(e=>{throw normalizeDirectoryError(e)});i=ot({stat:n.stat,identity:{dev:n.stat.dev,ino:n.stat.ino}},n.dir,n.realPath)}let a=mt(n.exactIdentity===!0&&process.platform===`win32`),assertCurrent=async()=>{n.signal?.throwIfAborted(),r?assertRootPathObservationReceiptCurrent(e,r):await assertRootDirectoryObservationGuard(e,i,a),n.signal?.throwIfAborted()},o={directory:i.realPath,names:/* @__PURE__ */ new Map},s=n.previousPaths?.directory===i.realPath?n.previousPaths.names:void 0,c,l,u,d=0,f=0,p=[],m=n.exactIdentity&&!process.versions.bun&&!process.versions.deno,h,g,_=!1,close=async()=>{let e=c;c=void 0;try{await e?.close()}catch(e){throw n.onCleanupFailure?.(e),e}};try{if(await assertCurrent(),n.order===`filesystem`)c=await openDirectoryNames(i.realPath);else if(n.snapshot)u=await listGuardedDirectoryPath(e,i,!0,r);else if(n.maxNames!==void 0){for(l=[],c=await openDirectoryNames(i.realPath);;){await assertCurrent();let e=await readDirectoryEntryName(c);if(await assertCurrent(),e===void 0)break;if(l.length>=n.maxNames)throw new I(`too-large`,`directory entry budget exceeded`);l.push(e)}await close()}else l=(await $.readdir(i.realPath,{encoding:`buffer`})).map(directoryEntryName);await assertCurrent(),l?.sort()}catch(e){let t=normalizeDirectoryError(e);try{await close()}catch(e){throw K(e,t,`directory setup and close both failed`)}throw t}let prepareBatch=async e=>{let t=e[d++];if(t===void 0)await assertCurrent();else if(!n.admitEntry())g=t;else{for(_&&await ii(),await assertCurrent(),_=!0,p=[],f=0;;){try{let e=pathStatFromStats(Q.lstatSync(Z.join(i.realPath,t),{bigint:!0}),t);if(p.push(e),e.isDirectory||e.isSymbolicLink||p.length>=(n.metadataBatchSize??32))break}catch(e){h={error:normalizeDirectoryError(e)};break}if(t=e[d++],t===void 0)break;if(!n.admitEntry()){g=t;break}}try{await assertCurrent()}catch(e){throw h?K(e,h.error,`directory observation and identity checks both failed`):e}}},v=u?()=>{try{n.signal?.throwIfAborted();let e=u[d++];return e?n.admitEntry()?{kind:`entry`,entry:e}:{kind:`limit`,name:e.name}:void 0}catch(e){throw normalizeDirectoryError(e)}}:void 0;return{paths:o,assertCurrent,nextSnapshot:v,async next(){try{if(v)return v();if(n.signal?.throwIfAborted(),l){f>=p.length&&!h&&g===void 0&&await prepareBatch(l);let e=p[f++];if(e)return{kind:`entry`,entry:e};if(h)throw h.error;return g===void 0?void 0:{kind:`limit`,name:g}}for(;;){m&&d++%32==31&&await ii(),await assertCurrent();let e=await readDirectoryEntryName(c,m);if(await assertCurrent(),e===void 0)return;if(!n.admitEntry())return{kind:`limit`,name:e};let t=s?.get(e)??Z.join(i.realPath,e);n.exactIdentity&&o.names.set(e,t);let r;try{let e=n.exactIdentity?z(()=>Q.lstatSync(t,{bigint:!0})):Q.lstatSync(t,{bigint:!0});r={stat:e,...n.exactIdentity?{identity:{dev:e.dev,ino:e.ino}}:{}}}catch(e){if(await assertCurrent(),n.skipVanished&&E(e))continue;throw e}return await assertCurrent(),{kind:`entry`,entry:pathStatFromStats(r.stat,e),identity:r.identity,...n.exactIdentity?{observation:r.stat}:{}}}}catch(e){throw normalizeDirectoryError(e)}},[Symbol.asyncDispose]:close}}function singleLinkFileIdentity(e){if(!e?.isFile()||e.isSymbolicLink()||e.nlink!==1&&e.nlink!==1n)return;let exact=e=>typeof e==`bigint`?e:Number.isSafeInteger(e)?BigInt(e):void 0,t=exact(e.dev),n=exact(e.ino);if(!(t===void 0||n===void 0||t<0n||n<0n||process.platform===`win32`&&(t===0n||n===0n)))return{dev:t,ino:n}}async function captureChangedObservedFile(e,t,n,r,i,a){try{let o=singleLinkFileIdentity(n),s=singleLinkFileIdentity(r);if(!o||!s||o.dev===s.dev&&o.ino===s.ino)return;await i(),a.failure={error:e,kind:`stat-leaf-changed:${t}`}}catch{}}async function missingObservedFileError(e,t,n,r,i){let a=new I(`path-mismatch`,`file changed during operation`,U(e));if(j(e,`ENOENT`)&&n?.isFile()&&!n.isSymbolicLink()&&(n.nlink===1||n.nlink===1n))try{await r(),i.failure={error:a,kind:`stat-leaf-missing:${t}`}}catch{}return a}async function statResolvedPathInRoot(e,t,n){let r={};try{return await je().run(async()=>{let i=!1;try{let a,o;if(n){if(n.kind!==`stat`||n.targetPath!==t)throw new I(`path-mismatch`,`file observation receipt does not match target`)}else{let n=t===e.rootReal?e.rootReal:Z.dirname(t);a=n===e.rootReal&&e.rootGuard?e.rootGuard:await createRootDirectoryObservationGuard(e,n);try{let e=l()?.beforeRootStatInitialObservation;if(e&&await e(t),o=z(()=>Q.lstatSync(t,{bigint:!0})),o.isSymbolicLink())throw new I(`path-mismatch`,`file changed during operation`)}catch(t){throw await assertRootDirectoryObservationGuard(e,a),t}}i=!0;let s=l()?.beforeRootStatObservation;s&&await s(t);let c,u,d=0,f=je(),inspect=(e=!0)=>(u=e?Q.lstatSync(t,{bigint:!0}):Q.lstatSync(t),d+=1,u);try{c=f.run(()=>n?Ie(inspect,n.target.identity):z(inspect,o))}catch(i){throw E(i)?await missingObservedFileError(i,t,n?`stat`in n.target?n.target.stat:void 0:o,()=>n?assertRootPathObservationReceiptCurrent(e,n):assertRootDirectoryObservationGuard(e,a),r):(f.has(i,`identity`)&&await captureChangedObservedFile(i,t,n?`stat`in n.target?n.target.stat:void 0:o,d===1?u:void 0,()=>n?assertRootPathObservationReceiptCurrent(e,n):assertRootDirectoryObservationGuard(e,a),r),i)}if(c.isSymbolicLink())throw new I(`path-mismatch`,`file changed during operation`);return n?assertRootPathObservationReceiptCurrent(e,n,c):await assertRootDirectoryObservationGuard(e,a),pathStatFromStats(c)}catch(e){throw!i&&E(e)?Qe(e instanceof Error?e:void 0):e}})}catch(e){let t=r.failure;throw t&&t.error===e&&at(e,t.kind),e}}async function*entriesInRoot(e,t,n){let r=n.maxEntries;if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw RangeError(`maxEntries must be a non-negative safe integer`);if(n.order!==void 0&&n.order!==`filesystem`&&n.order!==`sorted`)throw TypeError(`invalid root entries order: ${String(n.order)}`);n.signal?.throwIfAborted(),validatePinnedRelativePath(t);let i=await resolvePathInRoot(e,t,{...nt(n.symlinks),resolveCanonical:!0});n.signal?.throwIfAborted();let a=0,o=await openRootDirectoryListing(e,i.resolved,{order:n.order??`filesystem`,signal:n.signal,snapshot:!1,maxNames:r,metadataBatchSize:1,admitEntry:()=>r===void 0||a++<r}),s=!1,c;try{for(;;){let e=await o.next();if(n.signal?.throwIfAborted(),e===void 0)return;if(e.kind===`limit`)throw new I(`too-large`,`directory entry budget exceeded`);yield e.entry}}catch(e){throw s=!0,c=e,e}finally{try{await o[Symbol.asyncDispose]()}catch(e){throw s?K(e,c,`directory iteration and close both failed`):e}}}function stringifyJsonDocument(e,t,n){let r=JSON.stringify(e,t,n);if(typeof r!=`string`)throw TypeError(`value is not representable as a JSON document`);return r}function filterEntry(e,t){return t.kind===`symlink`?e.symlinkPolicy===`include`?e.entryFilter?.(t)??`include`:`skip`:e.entryFilter?.(t)??`include`}function validateBudget(e,t){if(t===void 0)return 1/0;if(!Number.isSafeInteger(t)||t<0)throw RangeError(`${e} must be a non-negative safe integer`);return t}function entryKind(e){return e.isSymbolicLink?`symlink`:e.isDirectory?`directory`:e.isFile?`file`:`other`}function limitEntry(e){return{relativePath:e,kind:`truncated`,size:0}}function walkRoot(e,t,n){let r,i,a=/* @__PURE__ */ new Set,o=0,s=!1,admitEntry=()=>o>=i?!1:(o+=1,!0),onLimit=e=>{if((n.limitBehavior??`truncate`)===`throw`)throw new I(`too-large`,`root walk budget exceeded at ${e||`.`}`);return s=!0,limitEntry(e)},onDirectoryError=(e,t)=>{if(n.signal?.aborted||(n.onDirectoryError??`throw`)===`throw`)throw t;return{relativePath:e,kind:`directory-error`,size:0,error:t}};async function*visit(t,o,c){if(o===0){if(![`skip`,`follow-within-root`,`include`].includes(n.symlinkPolicy))throw TypeError(`invalid root walk symlink policy: ${String(n.symlinkPolicy)}`);if(n.order!==void 0&&![`sorted`,`filesystem`].includes(n.order))throw TypeError(`invalid root walk order: ${String(n.order)}`);if(n.limitBehavior!==void 0&&![`truncate`,`throw`].includes(n.limitBehavior))throw TypeError(`invalid root walk limit behavior: ${String(n.limitBehavior)}`);if(n.onDirectoryError!==void 0&&![`throw`,`skip-and-report`].includes(n.onDirectoryError))throw TypeError(`invalid root walk directory error behavior: ${String(n.onDirectoryError)}`);r=validateBudget(`maxDepth`,n.maxDepth),i=validateBudget(`maxEntries`,n.maxEntries)}n.signal?.throwIfAborted();let l,u;try{let r=o===0?await expandRelativePathWithHome(t):t,s=o>0&&n.symlinkPolicy!==`follow-within-root`,d=o>0&&n.symlinkPolicy===`include`,f={absolutePath:c??Z.resolve(e.rootReal,r),rootPath:e.rootReal,rootCanonicalPath:e.rootReal,boundaryLabel:`root walk`,policy:s?ft.unlinkTarget:void 0},p,m;if(d){let t=await e.observeRoot(),n=await _e({...f,rootIdentity:t.identity},{kind:`directory`,rootGuard:t});m=n.resolved,p=n.receipt}else m=await _t(f);if(s&&m.kind===`symlink`){if(n.symlinkPolicy===`skip`)return;throw new I(`path-mismatch`,`root walk directory became a symlink: ${t}`)}if(!m.exists||m.kind!==`directory`)throw new I(`not-file`,`root walk path is not a directory: ${t||`.`}`);if(d&&(!p||p.directoryGuard.realPath!==m.canonicalPath))throw new I(`path-mismatch`,`root walk directory observation was not retained`);if(u=m.canonicalPath,a.has(m.canonicalPath))return;a.add(m.canonicalPath),n.signal?.throwIfAborted();let h=Z.relative(e.rootReal,m.canonicalPath).split(Z.sep).join(Z.posix.sep);o===0&&r!==t&&(t=h),l=await e.list(`./${h}`,{order:n.order??`sorted`,signal:n.signal,snapshot:i===1/0,admitEntry},p)}catch(e){yield onDirectoryError(t,e instanceof ee?e.error:e);return}let d=!1,f;try{let i=Z.posix.normalize(t.split(Z.sep).join(Z.posix.sep)),a=i===`.`||i===`./`?``:i.endsWith(`/`)?i:`${i}/`;for(;;){let i;try{i=l.nextSnapshot?l.nextSnapshot():await l.next(),n.signal?.throwIfAborted()}catch(e){yield onDirectoryError(t,e);return}if(i===void 0)return;let c=i.kind===`entry`?i.entry.name:i.name,d=a+c;if(i.kind===`limit`){yield onLimit(d);return}let f=i.entry,p=entryKind(f),m=f.size;if(p===`symlink`&&n.symlinkPolicy===`skip`)continue;if(p===`symlink`&&n.symlinkPolicy===`follow-within-root`){let t=await _t({absolutePath:Z.resolve(e.rootReal,d),rootPath:e.rootReal,rootCanonicalPath:e.rootReal,boundaryLabel:`root walk`});if(!t.exists)continue;let n=await e.stat(`./${Z.relative(e.rootReal,t.canonicalPath)}`);p=n.isDirectory?`directory`:n.isFile?`file`:`other`,m=n.size}let h={relativePath:d,kind:p,size:m},g=filterEntry(n,h);if(typeof g!=`string`){g=await g??`include`,n.signal?.throwIfAborted();try{await l.assertCurrent()}catch(e){yield onDirectoryError(t,e);return}}if(n.signal?.throwIfAborted(),![`include`,`skip`,`skip-subtree`].includes(g))throw TypeError(`invalid root walk entryFilter result: ${String(g)}`);if(g===`include`&&(yield h),p===`directory`&&g!==`skip-subtree`){if(o>=r){yield onLimit(d);return}if(yield*visit(d,o+1,n.symlinkPolicy===`include`?Z.join(u,c):void 0),s)return}}}catch(e){throw d=!0,f=e,e}finally{try{await l[Symbol.asyncDispose]()}catch(e){throw d?K(e,f,`directory walk and close both failed`):e}}}return visit(t,0)}const _a=BigInt(2**53-1);function identityMismatch(e){return new I(`path-mismatch`,`removal ancestor identity changed or could not be verified`,U(e))}function safeIdentityNumber(e){if(!(e<0n||e>_a))return Number(e)}function createRemovalDirectoryAssertion(e,t,n,r=process.platform){let i=safeIdentityNumber(t.dev),a=safeIdentityNumber(t.ino),o=i!==void 0&&a!==void 0&&(r!==`win32`||i!==0&&a!==0);return Object.freeze({path:e,dev:t.dev,ino:t.ino,numericDev:o?i:void 0,numericIno:o?a:void 0,platform:r,realPath:n})}function assertDirectoryType(e){if(typeof e?.isDirectory!=`function`||typeof e.isSymbolicLink!=`function`)throw identityMismatch();if(e.isSymbolicLink()||!e.isDirectory())throw Ve()}function assertExactObservation(e,t,n){if(assertDirectoryType(e),typeof e.dev!=`bigint`||typeof e.ino!=`bigint`||n===`win32`&&(e.dev===0n||e.ino===0n)||e.dev!==t.dev||e.ino!==t.ino)throw identityMismatch()}function assertNumericObservation(e){let t=Q.lstatSync(e.path);if(assertDirectoryType(t),!Number.isSafeInteger(t.dev)||t.dev<0||!Number.isSafeInteger(t.ino)||t.ino<0)throw identityMismatch();let n=!1,r=t.dev,i=e.numericDev;if(e.platform===`win32`&&r===0)n=!0;else if(r!==i)throw identityMismatch();let a=t.ino,o=e.numericIno;if(e.platform===`win32`&&a===0)n=!0;else if(a!==o)throw identityMismatch();n&&assertExactObservation(Q.lstatSync(e.path,{bigint:!0}),e,e.platform)}function assertRemovalDirectoryCurrent(e){if(e.numericDev!==void 0&&e.numericIno!==void 0?assertNumericObservation(e):B(e.path,e,void 0,e.platform),e.realPath!==void 0&&O.native(e.path)!==e.realPath)throw identityMismatch()}const va=Symbol(`nonrecursive removal kind`);function validateRemoveOptions(e){if(e.order!==void 0&&e.order!==`filesystem`&&e.order!==`sorted`)throw TypeError(`remove order must be filesystem or sorted`);for(let t of[`maxEntries`,`maxDepth`]){let n=e[t];if(n!==void 0&&n!==1/0&&(!Number.isSafeInteger(n)||n<0))throw RangeError(`${t} must be a non-negative safe integer`)}if(!e.recursive&&(e.maxEntries!==void 0||e.maxDepth!==void 0))throw TypeError(`remove budgets require recursive: true`);if(!e.recursive&&e.order!==void 0)throw TypeError(`remove order requires recursive: true`)}function assertNotAborted(e){try{e?.throwIfAborted()}catch(e){throw new Pt(e)}}function removalAncestorChanged(e){return new I(`path-mismatch`,`removal ancestor changed during operation`,U(e))}function sameCanonicalDirectory(e,t){return e===t||k(e,t)&&k(t,e)}function assertExactRemovalReceiptPrefixCurrent(e,t){try{W(e);for(let e of t)B(e.path,e)}catch(e){throw removalAncestorChanged(e)}}async function assertMissingRemovalPrefixCurrent(e,t){if(t.length===0){assertExactRemovalReceiptPrefixCurrent(e,t);return}let n=t[t.length-1];assertExactRemovalReceiptPrefixCurrent(e,t.slice(0,-1));let r;try{r=await F(n.path,{bigint:!0})}catch(e){throw removalAncestorChanged(e)}if(!H(r.stat,n)||!sameCanonicalDirectory(r.realPath,n.path))throw removalAncestorChanged()}async function captureNonrecursiveRemovalAdmission(e,t,n,r){let i=Z.dirname(t);if(!k(e.rootReal,i))throw new I(`path-mismatch`,`removal parent is outside the retained root`);let a=r?.complete(e.rootReal,t),o;try{o=a&&i!==e.rootReal?{dir:e.rootReal,realPath:e.rootReal,stat:a.rootStat}:await F(e.rootReal,{bigint:!0,initial:a?.rootStat})}catch(t){throw n.force&&E(t)&&await assertRootIdentityCurrent(e),vt(t)}if(!H(o.stat,e.rootIdentity))throw T();if(i===e.rootReal){let e=createRemovalDirectoryAssertion(o.dir,o.stat,o.realPath);return Object.freeze({parentIdentity:e,assertAfterMutation(){assertRemovalDirectoryCurrent(e)},assertCurrent(){try{assertRemovalDirectoryCurrent(e)}catch(e){throw removalAncestorChanged(e)}}})}let s=[],c=a?.directories,l=c?void 0:Z.relative(e.rootReal,i).split(Z.sep).filter(Boolean).slice(0,-1),u=c?Math.max(0,c.length-1):l.length,d=e.rootReal;for(let e=0;e<u;e+=1){let t=c?.[e],r=t?.path??(d=Z.join(d,l[e]));try{let e=B(r,void 0,t?.stat);s.push(createRemovalDirectoryAssertion(r,e))}catch(e){if(E(e)&&(await assertMissingRemovalPrefixCurrent(o,s),assertNotAborted(n.signal),n.force))return;throw vt(e)}}let f;try{f=await F(a?.parent?.path??i,{bigint:!0,initial:a?.parent?.stat})}catch(e){if(E(e)&&(await assertMissingRemovalPrefixCurrent(o,s),assertNotAborted(n.signal),n.force))return;throw vt(e)}if(!sameCanonicalDirectory(f.realPath,i))throw removalAncestorChanged();let p=a!==void 0&&f.realPath===i;if(a&&!p)try{o=await F(e.rootReal,{bigint:!0,initial:a.rootStat})}catch(t){throw n.force&&E(t)&&await assertRootIdentityCurrent(e),vt(t)}let m=createRemovalDirectoryAssertion(o.dir,o.stat,p?void 0:o.realPath),h=createRemovalDirectoryAssertion(f.dir,f.stat,f.realPath),assertPrefixCurrent=()=>{try{assertRemovalDirectoryCurrent(m);for(let e of s)assertRemovalDirectoryCurrent(e)}catch(e){throw removalAncestorChanged(e)}};return Object.freeze({parentIdentity:h,assertAfterMutation(){assertPrefixCurrent(),assertRemovalDirectoryCurrent(h)},assertCurrent(){assertPrefixCurrent();try{assertRemovalDirectoryCurrent(h)}catch(e){throw removalAncestorChanged(e)}}})}async function removeOne(e,t,n,r){let i=await captureNonrecursiveRemovalAdmission(e,t,n,r);if(i){try{await l()?.beforeRootFallbackMutation?.(`remove`,t),i.assertCurrent()}catch(e){throw vt(e)}try{let e=n.assertBeforeMutation?z(()=>Q.lstatSync(t,{bigint:!0})):void 0,r=(e??Q.lstatSync(t)).isDirectory();if(!r&&n[va]===`directory`)throw new I(`path-mismatch`,`store entry is no longer a directory`);L(t,n.mutationSymlinks!==void 0),assertNotAborted(n.signal),n.assertBeforeMutation?.(),e&&(assertNotAborted(n.signal),i.assertCurrent(),z(()=>Q.lstatSync(t,{bigint:!0}),e),L(t,n.mutationSymlinks!==void 0)),await(r?$.rmdir(t):$.unlink(t))}catch(e){if(!(n.force&&E(e)))throw Ne(e)}try{i.assertAfterMutation()}catch(e){throw vt(e)}assertNotAborted(n.signal)}}async function removePathInRootFallback(e,t,n,r){if(assertNotAborted(n.signal),!n.recursive){await removeOne(e,t,n,r);return}let i=n.maxEntries??1e5,a=n.maxDepth??64,details=(e,n)=>({operation:`remove`,phase:n,relativePath:Z.relative(t,e)}),o=0,s=await F(e.rootReal,{bigint:!0});if(!H(s.stat,e.rootIdentity))throw T();let c=[createRemovalDirectoryAssertion(s.dir,s.stat,s.realPath)],u=e.rootReal,d=Z.relative(e.rootReal,Z.dirname(t));for(let e of d.split(Z.sep).filter(Boolean)){u=Z.join(u,e);let t;try{t=await F(u,{bigint:!0})}catch(e){if(E(e)&&(assertCurrent(),assertNotAborted(n.signal),n.force))return;throw vt(e)}if(!k(t.realPath,u)||!k(u,t.realPath))throw new I(`path-mismatch`,`removal ancestor changed during operation`);c.push(createRemovalDirectoryAssertion(t.dir,t.stat,t.realPath))}function assertCurrent(){for(let e of c)try{assertRemovalDirectoryCurrent(e)}catch(e){throw new I(`path-mismatch`,`removal ancestor changed during operation`,{cause:e})}}let inspect=(e,t)=>{assertCurrent();try{return z(()=>Q.lstatSync(e,{bigint:!0}),t)}catch(r){if(n.force&&E(r))return;throw Ne(r,details(e,t?`remove`:`inspect`))}};async function visit(e,t,r=!1){if(assertNotAborted(n.signal),!r&&o>=i||t>a)throw new I(`too-large`,`recursive removal budget exceeded`,{details:details(e,`inspect`)});r||(o+=1),await assertMutationNotDenied(e,n.denyMutations,{protectAncestors:!0}),assertNotAborted(n.signal);let s=inspect(e);if(s){if(L(e,n.mutationSymlinks!==void 0,details(e,`inspect`)),s.isDirectory()){let r;try{r=await F(e,{bigint:!0})}catch(t){if(assertCurrent(),assertNotAborted(n.signal),n.force&&E(t))return;throw Ne(t,details(e,`inspect`))}if(!k(r.realPath,e)||!k(e,r.realPath)||!H(r.stat,s))throw new I(`path-mismatch`,`removal directory changed during operation`);c.push(createRemovalDirectoryAssertion(r.dir,r.stat,r.realPath));try{assertCurrent(),assertNotAborted(n.signal);let r=await $.opendir(e,{bufferSize:1}).catch(t=>{if(n.force&&E(t))assertNotAborted(n.signal);else throw Ne(t,details(e,`enumerate`))});if(r){let a=!1,s;try{let a=n.order===`sorted`?[]:void 0;if(a&&i===1/0){assertCurrent(),assertNotAborted(n.signal);let t=await $.readdir(e).catch(t=>{if(!(n.force&&E(t)))throw Ne(t,details(e,`enumerate`))});assertNotAborted(n.signal),t&&(assertCurrent(),a=t,o+=a.length)}else for(;;){assertCurrent(),assertNotAborted(n.signal);let s=await r.read().catch(t=>{if(!(n.force&&E(t)))throw Ne(t,details(e,`enumerate`))});if(s===void 0){assertNotAborted(n.signal),a&&(a.length=0);break}if(assertCurrent(),assertNotAborted(n.signal),!s)break;if(a){if(o>=i)throw new I(`too-large`,`recursive removal budget exceeded`,{details:details(Z.join(e,s.name),`enumerate`)});o+=1,a.push(s.name)}else await visit(Z.join(e,s.name),t+1)}if(a)for(let n of a.sort())await visit(Z.join(e,n),t+1,!0)}catch(e){throw a=!0,s=e instanceof Pt?e.rejection:e,e}finally{try{await r.close()}catch(t){let n=Ne(t,details(e,`enumerate`));throw a?K(n,s,`recursive removal and close both failed`):n}}}}finally{c.pop()}}if(await l()?.beforeRootFallbackMutation?.(`remove`,e),await assertMutationNotDenied(e,n.denyMutations,{protectAncestors:!0}),assertNotAborted(n.signal),inspect(e,s)){if(L(e,n.mutationSymlinks!==void 0,details(e,`remove`)),assertNotAborted(n.signal),n.assertBeforeMutation?.(),n.assertBeforeMutation){if(assertNotAborted(n.signal),!inspect(e,s))return;L(e,n.mutationSymlinks!==void 0,details(e,`remove`))}try{await(s.isDirectory()?$.rmdir(e):$.unlink(e))}catch(t){if(!(n.force&&E(t)))throw Ne(t,details(e,`remove`))}assertCurrent(),assertNotAborted(n.signal)}}}await assertRootIdentityCurrent(e),await visit(t,0)}function unavailable$1(){throw new I(`helper-unavailable`,`native confined removal is unavailable on this platform`)}function normalize(e,t){if(e instanceof I||e instanceof Pt||e instanceof Error&&e.name===`SuppressedError`)return e;let n=e?.code;return n===`path-mismatch`?new I(`path-mismatch`,`removal identity changed`,{cause:e,details:t}):[`ENOTSUP`,`ENOSYS`,`EOPNOTSUPP`].includes(n??``)?new I(`helper-unavailable`,`native confined removal is unavailable`,{cause:e,details:t}):Ne(e,t)}async function removeNativeLeaf(e,t,n,r,i,a){let assertNotAborted=()=>{try{r.signal?.throwIfAborted()}catch(e){throw new Pt(e)}};assertNotAborted();let o=l()?.beforeRootFallbackMutation;if(o)try{await o(`remove`,n)}catch(e){throw vt(e)}r.denyMutations&&await assertMutationNotDenied(n,r.denyMutations,{protectAncestors:!0});let s=Z.basename(n),observe=n=>{assertNotAborted(),a||i.assertCurrent(),a=!1;try{let i=e.rootRemovalStat(t.fd,s);if(n&&(i.dev!==n.dev||i.ino!==n.ino||i.directory!==n.directory))throw new I(`path-mismatch`,`removal entry changed`);if(i.symlink&&r.mutationSymlinks!==void 0)throw new I(`symlink`,`symlink not allowed`,{details:{operation:`remove`,phase:n?`remove`:`inspect`,relativePath:``}});return i}catch(e){if(r.force&&E(e))return;throw normalize(e,{operation:`remove`,phase:n?`remove`:`inspect`,relativePath:``})}},c=observe();if(c){if(!c.directory&&r[va]===`directory`)throw new I(`path-mismatch`,`store entry is no longer a directory`);if(!(r.assertBeforeMutation&&(r.assertBeforeMutation(),!observe(c)))){try{e.rootRemovalUnlink(t.fd,s,c.dev,c.ino,c.directory)}catch(e){if(!(r.force&&E(e)))throw normalize(e,{operation:`remove`,phase:`remove`,relativePath:``})}i.assertAfterMutation(),assertNotAborted()}}}async function removePathInRootNative(e,t,n,r){let i=P(`openBeneath`,`rootRemovalStat`,`rootRemovalUnlink`);(!i?.rootRemovalStat||!i.rootRemovalUnlink)&&unavailable$1();let a=i.rootRemovalStat.bind(i),o=i.rootRemovalUnlink.bind(i),s=i.openRootRemovalDirectory?.bind(i),c=await captureNonrecursiveRemovalAdmission(e,t,n,r);if(!c)return;if(n.recursive&&n.maxEntries===0)throw n.signal?.throwIfAborted(),c.assertCurrent(),new I(`too-large`,`recursive removal budget exceeded`,{details:{operation:`remove`,phase:`inspect`,relativePath:``}});let u;try{u=openExactNativeRootAdmissionSync(i,{rootPath:e.rootReal,rootIdentity:e.rootIdentity,operation:`remove`,reportCloseErrors:!0})}catch(e){throw vt(e)}let d,f,p,m=!1,h,g=!1;try{let r=Z.dirname(t);if(!k(e.rootReal,r))throw new I(`outside-workspace`,`removal parent is outside root`);try{d=r===e.rootReal?borrowNativeRootParent(u):await openNativeParentAdmission(i,u,Z.relative(e.rootReal,r).split(Z.sep).join(`/`),`native-directory`)}catch(t){if(assertRootIdentityCurrentSync(e),c.assertCurrent(),!(n.force&&E(t)))throw t}if(d){if(d.guard.stat.dev!==c.parentIdentity.dev||d.guard.stat.ino!==c.parentIdentity.ino)throw new I(`path-mismatch`,`removal parent identity changed`);if(n.recursive){c.assertCurrent();try{f=a(d.fd,Z.basename(t))}catch(e){if(c.assertCurrent(),!(n.force&&E(e)))throw e}if(f?.directory){s||unavailable$1(),m=!0;try{p=s(d.fd,Z.basename(t),f.dev,f.ino)}catch(e){c.assertCurrent();let t=e?.code;if([`ENOTSUP`,`ENOSYS`,`EOPNOTSUPP`].includes(t??``))unavailable$1();else if(!(n.force&&E(e)))throw normalize(e,{operation:`remove`,phase:`enumerate`,relativePath:``})}}}n.recursive?f&&await removeEntries(d):await removeNativeLeaf(i,d,t,n,c,r===e.rootReal&&!n.signal&&!n.denyMutations&&!n.assertBeforeMutation&&!l()?.beforeRootFallbackMutation)}}catch(e){g=!0,h=e instanceof Pt?e:normalize(e)}let _=[];try{p?.close()}catch(e){_.push(e)}try{d?.close()}catch(e){_.push(e)}try{await u.root.close()}catch(e){_.push(e)}if(_.length){let e=_.length===1?_[0]:AggregateError(_,`removal descriptors could not close`);throw g?K(e,h instanceof Pt?h.rejection:h,`removal and descriptor close failed`):e}if(g)throw h;async function removeEntries(e){let r=[],i=n.maxEntries??1e5,u=n.maxDepth??64,d=0,details=(e,n)=>({operation:`remove`,relativePath:Z.relative(t,e),phase:n});async function beforeMutation(e){try{await l()?.beforeRootFallbackMutation?.(`remove`,e)}catch(e){throw vt(e)}}function assertNotAborted(){try{n.signal?.throwIfAborted()}catch(e){throw new Pt(e)}}function assertTraversalCurrent(){for(let e of r)try{assertRemovalDirectoryCurrent(e)}catch(e){throw new I(`path-mismatch`,`removal ancestor changed`,{cause:e})}}function assertCurrent(){assertNotAborted(),c.assertCurrent(),assertTraversalCurrent()}function observe(e,t,r,i){assertCurrent();try{let o=a(e,t);if(i&&(o.dev!==i.dev||o.ino!==i.ino||o.directory!==i.directory))throw new I(`path-mismatch`,`removal entry changed`);if(o.symlink&&n.mutationSymlinks!==void 0)throw new I(`symlink`,`symlink not allowed`,{details:details(r,i?`remove`:`inspect`)});return o}catch(e){if(n.force&&E(e))return;throw normalize(e,details(r,i?`remove`:`inspect`))}}async function visit(e,t,a,l,h=!1){if(assertNotAborted(),n.recursive&&(!h&&d>=i||l>u))throw new I(`too-large`,`recursive removal budget exceeded`,{details:details(a,`inspect`)});h||d++,await assertMutationNotDenied(a,n.denyMutations,{protectAncestors:!0});let g=observe(e,t,a,l===0?f:void 0);if(g){if(!g.directory&&n[va]===`directory`)throw new I(`path-mismatch`,`store entry is no longer a directory`);if(g.directory&&n.recursive){let o;try{l===0&&m?(o=p,p=void 0):o=s(e,t,g.dev,g.ino)}catch(r){if(assertCurrent(),!(n.force&&E(r)))throw normalize(r,details(a,`enumerate`));if(!observe(e,t,a,g))return}if(o){let e;try{let e=Q.fstatSync(o.fd,{bigint:!0}),read=()=>{try{return o.read()}catch(e){throw normalize(e,details(a,`enumerate`))}};r.push(createRemovalDirectoryAssertion(a,e,a));try{if(assertCurrent(),n.order===`sorted`){let e=[];for(let t=read();t!==null;t=read()){if(await ri.yield(),assertCurrent(),d>=i)throw new I(`too-large`,`recursive removal budget exceeded`,{details:details(Z.join(a,t),`enumerate`)});d++,e.push(t)}for(let t of e.sort())await visit(o.fd,t,Z.join(a,t),l+1,!0)}else for(let e=read();e!==null;e=read())await ri.yield(),await visit(o.fd,e,Z.join(a,e),l+1)}finally{r.pop()}}catch(t){throw e={error:t instanceof Pt?t.rejection:t},t}finally{try{o.close()}catch(t){let n=normalize(t,details(a,`enumerate`));throw e?K(n,e.error,`removal and directory close failed`):n}}}}if(!(n.recursive&&(await beforeMutation(a),await assertMutationNotDenied(a,n.denyMutations,{protectAncestors:!0}),!observe(e,t,a,g)))&&!(n.assertBeforeMutation&&(n.assertBeforeMutation(),!observe(e,t,a,g)))){try{o(e,t,g.dev,g.ino,g.directory)}catch(e){if(!(n.force&&E(e)))throw normalize(e,details(a,`remove`))}c.assertCurrent(),assertTraversalCurrent(),assertNotAborted()}}}await visit(e.fd,Z.basename(t),t,0)}}async function verifyRootWritePublication(e){try{await e.verify(),e.retention?.retain(e.fd,e.parentGuard,e.nativeParent)}catch(t){if(e.retention&&e.nativeParent)try{e.retention.cleanup(e.fd,e.nativeParent,e.expectedIdentity)}catch(e){throw K(e,t,`sidecar retention and creator cleanup both failed`)}throw t}}async function verifyAtomicWriteResult(e){let t=!1,assertFile=t=>{if(t.isSymbolicLink())throw new I(`symlink`,`symlink not allowed`);if(!t.isFile())throw new I(`not-file`,`not a file`);if(!Be(t,e.expectedIdentity))throw new I(`path-mismatch`,`path changed during write`);if(t.nlink>1)throw R()},assertPath=e=>{assertFile(e),t||=process.platform===`win32`&&(e.dev===0n||e.ino===0n)},assertDescriptor=(t=e.fd)=>{let n=Q.fstatSync(t,{bigint:!0});if(e.expectedIdentity.dev!==n.dev||e.expectedIdentity.ino!==n.ino)throw new I(`path-mismatch`,`descriptor changed during write`);if(assertFile(n),process.platform!==`win32`&&e.expectedMode!==void 0){let t=Number(n.mode&4095n);if(t!==e.expectedMode)throw Error(`Private secret file ${e.targetPath} has insecure permissions ${t.toString(8)}.`)}return n};try{let n;try{for(;;){let r=n?.fd??e.fd,i=assertDescriptor(r);assertPath(Q.lstatSync(e.targetPath,{bigint:!0}));let{realPath:a,stat:o}=await resolveOpenedFileRealPathForFd(r,i,e.targetPath);if(assertPath(o),!M({rootPath:e.root.rootReal,candidatePath:a,rootIdentity:e.root.rootIdentity}))throw G();if(await A(e.parentGuard),await assertRootIdentityCurrent(e.root),assertPath(Q.lstatSync(e.targetPath,{bigint:!0})),assertDescriptor(r),n||!t)break;oe(e.targetPath),n=await $.open(e.targetPath,ke()).catch(e=>{throw S(e)?new I(`symlink`,`symlink open blocked`,{cause:e}):j(e,`EISDIR`)?new I(`not-file`,`not a file`):e})}}finally{n&&await n.close().catch(()=>void 0)}}catch(e){throw E(e)?Qe():e}}async function finishRootFallbackWrite(e){let t=e.handle,n=e.identity,r,i=e.options.renameIdentity===`verify-content-with-lock`,verify=async()=>{try{await verifyAtomicWriteResult({root:e.root,targetPath:e.targetPath,fd:t.fd,expectedIdentity:n,parentGuard:e.parentGuard})}catch(t){throw e.onVerificationFailure(t),t}};try{if(i){let i=Q.lstatSync(e.targetPath,{bigint:!0});if(i.isSymbolicLink()||!i.isFile())throw new I(`path-mismatch`,`fallback target changed during write`);if(process.platform===`win32`&&(i.dev===0n||i.ino===0n))await verify();else if(!H(i,n)){let i=await e.openForCompatibility();r=t=i.opened.handle,n=i.identity,await verify();let a=e.options.data,o=typeof a==`string`?Buffer.byteLength(a,e.options.encoding??`utf8`):a.byteLength,s=await we(t,o).catch(e=>{throw e instanceof I&&e.code===`too-large`?new I(`path-mismatch`,`fallback target changed during write`,{cause:e}):e});if(Ze(s)!==Ze(a,e.options.encoding))throw new I(`path-mismatch`,`fallback target changed during write`);await verify()}}try{(process.platform!==`win32`||(Q.fstatSync(t.fd).mode&128)!=(e.mode&128))&&Q.fchmodSync(t.fd,e.mode)}catch(r){throw await kt({pathname:e.targetPath,handle:t,identity:n,parentGuard:e.parentGuard}),r}e.options.durable!==!1&&await t.sync(),await verify(),e.options.durable!==!1&&(await syncDirectoryBestEffort(Z.dirname(e.targetPath)),i&&await verify())}finally{await r?.close().catch(()=>void 0)}}async function withRootFallbackCompatibilityLock(e,t){let n=createRootWriteLockBinding(e),r=e.assertBeforeMutation,i=r===void 0?n.assertCurrent:()=>{r.call(e),n.assertCurrent()};try{return await St(n.targetPath,async()=>await withPinnedWriteRenameIdentityLock({rootPath:e.rootPath,targetPath:n.targetPath,relativeTargetPath:n.relativeLockPath},async()=>await t({targetPath:n.targetPath,relativePath:n.relativePath,assertBeforeMutation:i})))}finally{n.dispose()}}function fallbackError(e,t){let n=e?.code,r=e instanceof Error?e.message:`native no-replace move fallback failed`;if(n===`EEXIST`)return new I(`already-exists`,`no-replace fallback destination exists`,{cause:e});if(n===`FS_SAFE_INTERNAL_MOVE_LINK_UNSUPPORTED`)return new I(`helper-unavailable`,r,{cause:e,details:{capability:`rename-noreplace`,fallback:`link-unlink`,fallbackCapability:`linkat`}});let i=(/* @__PURE__ */ new Map([[`FS_SAFE_INTERNAL_MOVE_LINK_CHANGED`,`not-attempted`],[`FS_SAFE_INTERNAL_MOVE_SOURCE_LINKED`,`still-linked`],[`FS_SAFE_INTERNAL_MOVE_UNLINK_UNVERIFIED`,`unverified`],[`FS_SAFE_INTERNAL_MOVE_PUBLISHED`,`removed`]])).get(n??``);return i?new I(n===`FS_SAFE_INTERNAL_MOVE_LINK_CHANGED`?`path-mismatch`:`helper-failed`,r,{cause:e,details:{operation:t,fallback:`link-unlink`,publication:`published`,sourceRemoval:i}}):e}function nativeMoveNoReplace(e,t,n,r,i=`move`){se(e,`renameNoReplace`);let[a,o,s,c]=t,l=cachedNoReplaceUnavailable(e,a,i);if(!l)try{e.renameNoReplace(...t);return}catch(t){if(l=noReplaceUnavailable(t,i,!0),!l)throw t;a===s&&o!==c&&rememberNoReplaceUnavailable(e,a,l)}if(!r||process.platform!==`linux`||!e.moveNoReplaceFallback||!n)throw l;try{return e.moveNoReplaceFallback(...t,n.dev,n.ino),n.isFile()?`link-unlink`:void 0}catch(e){throw fallbackError(e,i)}}function nativeParentRelativePath(e,t){let n=Z.relative(e,t);if(n===``||n===`.`)return``;if(n.split(Z.sep)[0]===`..`||Z.isAbsolute(n))throw G();return n.split(Z.sep).join(Z.posix.sep)}function admitMovePath(e,t,n){let r=M({rootPath:e.rootReal,candidatePath:Z.join(t.guard.realPath,n),rootIdentity:e.rootIdentity});if(!r)throw G();return r.path}function nativePrimitiveUnavailable(e){let t=e?.code;return t===`ENOSYS`||t===`ENOTSUP`||t===`EOPNOTSUPP`}function normalizeMoveError(e){if(e instanceof I)return e;let t=e?.code;return t===`path-mismatch`||t===`hardlink`?new I(t,`native move source changed`,U(e)):t===`ELOOP`?new I(`symlink`,`native move source is a symlink`,U(e)):E(e)?Qe(e instanceof Error?e:void 0):nativePrimitiveUnavailable(e)?new I(`helper-unavailable`,`native move is unavailable`,U(e)):e}function admitMoveSourceStat(e){if(e.isSymbolicLink())throw new I(`symlink`,`symlink not allowed`);if(e.isFile()&&e.nlink>1)throw R();return e}async function movePathNative(e,t,n,r=!1){if(!r)try{throw Q.lstatSync(n.targetPath),new I(`already-exists`,`destination exists`)}catch(e){if(e instanceof I||!E(e))throw e}let i=Oe(`openBeneath`,r?`renameReplaceWithIdentity`:`renameNoReplace`);if(typeof(r?i.renameReplaceWithIdentity:i.renameNoReplace)!=`function`)throw new I(`helper-unavailable`,`native move is unavailable`);let a=openExactNativeRootAdmissionSync(i,{rootPath:e.rootReal,rootIdentity:e.rootIdentity,operation:`native move`}),o,s,c=!1,u;try{let c=nativeParentRelativePath(e.rootReal,n.sourceParentPath);o=c===``?borrowNativeRootParent(a):await openNativeParentAdmission(i,a,c,`native-directory`);let u=nativeParentRelativePath(e.rootReal,n.targetParentPath);s=u===c?o:u===``?borrowNativeRootParent(a):await openNativeParentAdmission(i,a,u,`native-directory`);let d=s===o?[o]:[o,s],f=l()?.beforeRootFallbackMutation;f&&await f(`move`,n.targetPath);let p=admitMovePath(e,o,Z.basename(n.sourcePath)),m=admitMovePath(e,s,Z.basename(n.targetPath));t.denyMutations&&(await assertMutationNotDenied(p,t.denyMutations,{protectAncestors:!0}),await assertMutationNotDenied(m,t.denyMutations,{protectAncestors:!0}));let h=c===``?o:u===``?s:void 0;if(h){if(o!==s||c!==``||f||t.denyMutations!==void 0||t.assertBeforeMutation!==void 0)try{W(h.guard)}catch(e){throw T(e instanceof Error?e:void 0)}}else assertRootIdentityCurrentSync(e);for(let e of d)e!==h&&W(e.guard);let g=r||t.assertBeforeMutation||process.platform===`linux`&&!t.requireNative?z(()=>admitMoveSourceStat(Q.lstatSync(p,{bigint:!0})),n.expectedSourceIdentity):void 0;if(g||admitMoveSourceStat(Q.lstatSync(p)),L(m,t.mutationSymlinks!==void 0),t.assertBeforeMutation?.(),t.assertBeforeMutation||t.mutationSymlinks===`reject`){if(assertRootIdentityCurrentSync(e),t.mutationSymlinks===`reject`)for(let t of[n.sourcePath,n.targetPath])gt({absolutePath:t,rootPath:e.rootReal,rootCanonicalPath:e.rootReal,rootIdentity:e.rootIdentity,boundaryLabel:`root`,rejectSymlinks:!0,rejectFinalSymlink:!0});for(let e of d)W(e.guard)}if(r&&t.assertBeforeMutation){for(let[r,i,a,o]of[[n.sourceOriginalPath,p,n.sourceCanonicalPath,oa.strict],[n.targetOriginalPath,m,n.targetCanonicalPath,oa.unlinkTarget]])if(r!==void 0&&a!==void 0){for(let n of/* @__PURE__ */ new Set([Z.isAbsolute(r)?r:`${e.rootWithSep}${r}`,i]))if(gt({absolutePath:n,rootPath:e.rootReal,rootCanonicalPath:e.rootReal,rootIdentity:e.rootIdentity,boundaryLabel:`root`,policy:o,...ze(t.mutationSymlinks)}).canonicalPath!==a)throw new I(`path-mismatch`,`move route changed during authorization`)}}g!==void 0&&z(()=>admitMoveSourceStat(Q.lstatSync(p,{bigint:!0})),g);try{L(m,t.mutationSymlinks!==void 0),r?i.renameReplaceWithIdentity(o.fd,Z.basename(n.sourcePath),s.fd,Z.basename(n.targetPath),g.dev,g.ino):nativeMoveNoReplace(i,[o.fd,Z.basename(n.sourcePath),s.fd,Z.basename(n.targetPath)],g,!t.requireNative)}catch(e){throw Ue(e)||!r&&e?.code===`ENOTEMPTY`?new I(`already-exists`,`destination exists`,U(e)):normalizeMoveError(e)}try{for(let e of d)y(e.guard,`native`);r&&z(()=>Q.lstatSync(m,{bigint:!0}),g)}catch(e){throw Ae(e)}}catch(e){c=!0,u=normalizeMoveError(e)}let d=[],f=/* @__PURE__ */ new Set;for(let e of[s,o])if(e&&!f.has(e.fd)){f.add(e.fd);try{e.close()}catch(e){d.push(e)}}try{a.root.close()}catch(e){d.push(e)}if(d.length>0){let e=d.length===1?d[0]:AggregateError(d,`native move descriptor closes failed`);throw c?K(e,u,`native move and descriptor close failed`):e}if(c)throw u}async function resolvePinnedObservedPathInRoot(e,t,n){let r=await createRootObservationGuard(e),i=mt(l()===void 0),a=e.rootReal,o;try{let s=await expandRelativePathWithHome(t),c=process.platform===`win32`?s.replaceAll(`/`,Z.sep):s;o=await _e({absolutePath:Z.isAbsolute(c)?c:c===``?a:`${ensureTrailingSep(a)}${c}`,rootPath:a,rootCanonicalPath:a,rootIdentity:e.rootIdentity,boundaryLabel:`root`,policy:oa.strict},{kind:n,rootGuard:r,directoryObserver:i})}catch(t){throw t instanceof ee?t.parentReceipt&&(assertRootPathObservationReceiptCurrent(e,t.parentReceipt),t.traversalFailure&&!E(t.error))?t.error instanceof I&&t.error.code===`symlink`?t.error:new I(`path-alias`,`path alias escape blocked`,{cause:t.error}):E(t.error)?n===`stat`?Qe(t.error instanceof Error?t.error:void 0):new I(`not-found`,`directory not found`,U(t.error)):t.error:t instanceof I&&t.code===`symlink`?t:new I(`path-alias`,`path alias escape blocked`,{cause:t})}let s=o.resolved;if(o.receipt)return{resolved:s.canonicalPath,receipt:o.receipt};let c=Z.relative(s.rootCanonicalPath,s.canonicalPath);if(c===``||c===`.`)return{resolved:s.canonicalPath};if(c.split(Z.sep)[0]===`..`||Z.isAbsolute(c))throw G();let u=M({rootPath:s.rootCanonicalPath,candidatePath:s.canonicalPath,rootIdentity:e.rootIdentity});if(!u)throw G();return{resolved:u.path}}const ya=/* @__PURE__ */ new WeakMap,ba=/* @__PURE__ */ new WeakMap;function registerFileLockSyncRootAdapter(e,t,n){let r=t.rootIdentity;typeof r.dev==`bigint`&&typeof r.ino==`bigint`&&(ya.set(e,t),ba.set(e,n))}function snapshotPolicy(e){if(e===void 0)return;let t=e.paths,n=e.prefixes;return Object.freeze({paths:t===void 0?void 0:Object.freeze([...t]),prefixes:n===void 0?void 0:Object.freeze([...n])})}function captureFileLockSyncRootAuthority(e){let t=e,n=ya.get(t),r=ba.get(t);if(!n||!r)throw new I(`helper-unavailable`,`synchronous Root-backed file locks require a genuine fs-safe Root handle`);let i=n.rootIdentity;if(typeof i.dev!=`bigint`||typeof i.ino!=`bigint`)throw new I(`helper-unavailable`,`synchronous Root identity is unavailable`);let a=Object.freeze({rootDir:n.rootDir,rootGuard:n.rootGuard,rootIdentity:Object.freeze({dev:i.dev,ino:i.ino}),rootReal:n.rootReal,rootWithSep:n.rootWithSep}),o=r,s=o.assertBeforeMutation,c=snapshotPolicy(o.denyMutations),l=o.hardlinks,u=o.mutationSymlinks,d=o.symlinks;assertRootIdentityCurrentSync(a);let f=ze(u),p=Object.freeze({rejectSymlinks:f.rejectSymlinks,rejectFinalSymlink:f.rejectFinalSymlink,rejectUnresolvedSymlinks:!0}),m=Object.freeze({...nt(d),rejectUnresolvedSymlinks:!0});return Object.freeze({adapter:t,context:a,assertBeforeMutation:s,denyMutations:c,hardlinks:l,mutationPolicy:p,readPolicy:m,policiesMatch:p.rejectSymlinks===m.rejectSymlinks&&p.rejectFinalSymlink===m.rejectFinalSymlink})}function invokeFileLockSyncRootMutationAuthority(e){let t=e.assertBeforeMutation;return t?(q(t(),`assertBeforeMutation`),!0):!1}function absoluteRootPath(e,t){let n=t.split(Z.posix.sep),r=Z.join(e.context.rootReal,...n);return w(r,`filesystem`,`sidecar lock path uses a Windows filesystem namespace alias`),r}function assertFileLockSyncRootMutationAllowed(e,t,n=!1){assertMutationNotDenied(e,t,{protectAncestors:n},`sync-root-lock`)}function resolveAdmittedPath(e,t,n,r){let i=e.context,a;try{a=gt({absolutePath:t,rootPath:r,rootCanonicalPath:i.rootReal,rootIdentity:i.rootIdentity,boundaryLabel:`sidecar lock root`,...n})}catch(e){throw qe(e)?new I(`outside-workspace`,`sidecar lock path is outside lockRoot`,{cause:e}):e}let o=M({rootPath:i.rootReal,candidatePath:a.canonicalPath,rootIdentity:i.rootIdentity});if(!o||o.relativePath===``||sameAbsolutePath(o.path,i.rootReal))throw G();return{path:o.path,relativePath:o.relativePath.split(Z.sep).join(Z.posix.sep)}}function resolveBothPolicies(e,t,n){let{mutationPolicy:r,readPolicy:i,policiesMatch:a}=e,o=resolveAdmittedPath(e,t,r,n),s=a?o:resolveAdmittedPath(e,t,i,n);if(!sameAbsolutePath(o.path,s.path))throw new I(`path-mismatch`,`sidecar read and mutation paths resolve differently`);return assertFileLockSyncRootMutationAllowed(o.path,e.denyMutations),o}function admitRequestedRootPrefix(e,t){let n=e.context,r=process.platform===`win32`?/* @__PURE__ */ new Map:void 0,i=M({rootPath:n.rootDir,candidatePath:t,rootIdentity:n.rootIdentity,resolveCandidateRoot:n.rootDir!==n.rootReal,identityCache:r});if(i&&i.relativePath!==``)return{path:i.path,rootPath:n.rootDir};let a=n.rootDir===n.rootReal?void 0:M({rootPath:n.rootReal,candidatePath:t,rootIdentity:n.rootIdentity,identityCache:r});if(!a||a.relativePath===``)throw G();return{path:a.path,rootPath:n.rootReal}}function admitFileLockSyncRootPath(e,t){ht(t,`sidecar lock path contains a NUL byte`);let n=Ce(t);w(n,`filesystem`,`sidecar lock path uses a Windows filesystem namespace alias`),assertRootIdentityCurrentSync(e.context);let r=admitRequestedRootPrefix(e,n),i=resolveBothPolicies(e,r.path,r.rootPath);assertRootIdentityCurrentSync(e.context);let a=Object.freeze({authority:e,path:i.path,relativePath:i.relativePath});return assertMissingParentMutationsAllowed(a),a}function assertFileLockSyncRootResolvedPathCurrent(e){if(!sameAbsolutePath(resolveBothPolicies(e.authority,absoluteRootPath(e.authority,e.relativePath),e.authority.context.rootReal).path,e.path))throw new I(`path-mismatch`,`sidecar lock path changed during operation`)}function assertMissingParentMutationsAllowed(e){let t=e.authority,n=t.context,r=Z.posix.dirname(e.relativePath),i=r===`.`?``:r,a=n.rootReal,o=!1;for(let e of i.split(Z.posix.sep).filter(Boolean)){if(a=Z.join(a,e),!o)try{let e=Q.lstatSync(D(a),{bigint:!0});if(e.isSymbolicLink()||!e.isDirectory())throw Ve()}catch(e){if(!E(e))throw e;o=!0}o&&assertFileLockSyncRootMutationAllowed(a,t.denyMutations)}}function assertFileLockSyncRootPathsCurrent(e){let t=e[0]?.authority;for(let n of e)if(t&&n.authority!==t)throw new I(`path-mismatch`,`sidecar paths use different Root authority`);if(t&&invokeFileLockSyncRootMutationAuthority(t)){assertRootIdentityCurrentSync(t.context);for(let t of e)assertFileLockSyncRootResolvedPathCurrent(t),assertMissingParentMutationsAllowed(t);assertRootIdentityCurrentSync(t.context)}}function resolveTargetPathViaExistingAncestorSync(e){let t=Ce(e),n=process.platform===`win32`?O.native:O,r=t,i;for(;;){try{Q.lstatSync(D(r));try{i=n(D(r));break}catch(e){if(!E(e))throw e}}catch(e){if(!E(e))throw e}let e=Z.dirname(r);if(e===r){i=n(D(r));break}r=e}return w(i,`filesystem`,`file-lock target ancestor uses a Windows filesystem namespace alias`),Ce(r===t?i:Z.resolve(i,`.${Z.sep}${t.slice(r.length)}`))}function normalizeFileLockSyncTargetWithRoot(e,t){ht(t,`file-lock target contains a NUL byte`),w(t,`filesystem`,`file-lock target uses a Windows filesystem namespace alias`),assertRootIdentityCurrentSync(e.context);let n=process.platform===`win32`?resolveTargetPathViaExistingAncestorSync(t):Z.join(resolveTargetPathViaExistingAncestorSync(Z.dirname(t)),Z.basename(t));return w(n,`filesystem`,`file-lock target uses a Windows filesystem namespace alias`),assertRootIdentityCurrentSync(e.context),n}function readDefaults(e){return{hardlinks:e.hardlinks,maxBytes:Ye(e.maxBytes,{defaultValue:16777216}),symlinks:e.symlinks}}function mergeReadOptions(e,t){let n=readDefaults(e);return t.hardlinks!==void 0&&(n.hardlinks=t.hardlinks),n.maxBytes=Ye(t.maxBytes,{defaultValue:n.maxBytes}),t.symlinks!==void 0&&(n.symlinks=t.symlinks),n}var __addDisposableResource=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var dispose,r;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);dispose=t[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);dispose=t[Symbol.dispose],n&&(r=dispose)}if(typeof dispose!=`function`)throw TypeError(`Object not disposable.`);r&&(dispose=function(){try{r.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose,async:n})}else n&&e.stack.push({async:!0});return t},xa=(function(e){return function(t){function fail(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var n,r=0;function next(){for(;n=t.stack.pop();)try{if(!n.async&&r===1)return r=0,t.stack.push(n),Promise.resolve().then(next);if(n.dispose){var e=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(e).then(next,function(e){return fail(e),next()})}else r|=1}catch(e){fail(e)}if(r===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return next()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});function logWarn(e){process.env.FS_SAFE_DEBUG_WARNINGS===`1`&&console.warn(e)}const Sa=process.platform!==`win32`&&`O_NOFOLLOW`in ci,Ca=ci.O_WRONLY|(Sa?ci.O_NOFOLLOW:0)|f(),wa=ci.O_WRONLY|ci.O_CREAT|ci.O_EXCL|(Sa?ci.O_NOFOLLOW:0),Ta=ci.O_RDWR|ci.O_APPEND|(Sa?ci.O_NOFOLLOW:0)|f(),Ea=ci.O_RDWR|ci.O_APPEND|ci.O_CREAT|ci.O_EXCL|(Sa?ci.O_NOFOLLOW:0);function openResult(e){return{handle:e.handle,containment:`best-effort`,realPath:e.realPath,stat:e.stat,exactIdentity:e.exactIdentity,[Symbol.asyncDispose]:()=>e.handle.close().catch(()=>void 0)}}async function openVerifiedLocalFile(e,t){let n=l(),{handle:r,stat:i,identity:a,preOpenStat:o}=await openLocalFileDescriptor(e,t);try{let inspectPathIdentity=async t=>{try{return z(t,a)}catch(t){let n=E(t)?openedPathResolutionError(Qe()):t;throw i.nlink<=1&&(!o||o.nlink<=1n)&&await recordOpenedFileFailure(n,r,e,a),n}};await inspectPathIdentity(()=>inspectOpenedPathIdentitySync(e,t?.symlinks)),n?.afterOpenedPathIdentityCheck&&await n.afterOpenedPathIdentityCheck(e,r);let s=await resolveOpenedFileRealPathForFd(r.fd,a,e).catch(async t=>{throw i.nlink<=1&&(!o||o.nlink<=1n)&&await recordOpenedFileFailure(t,r,e,a),t}),{realPath:c}=s;w(c,`filesystem`,`resolved file path uses a Windows filesystem namespace alias`);let l=s.stat;return await inspectPathIdentity(()=>{let e=l??Q.statSync(c,{bigint:!0});if(l=void 0,t?.hardlinks===`reject`&&e.nlink>1n)throw R();return e}),{opened:openResult({handle:r,realPath:c,stat:i,exactIdentity:Xe(a)}),identity:a}}catch(e){throw await r.close().catch(()=>{}),e}}var RootHandle=class{context;rootDir;rootReal;rootWithSep;defaults;constructor(e,t={}){this.context=e,this.rootDir=e.rootDir,this.rootReal=e.rootReal,this.rootWithSep=e.rootWithSep,this.defaults=t,registerFileLockSyncRootAdapter(this,e,t),registerRootHandleContext(this,e)}mutationOptions(e){return{...e,assertBeforeMutation:Tt(this.defaults.assertBeforeMutation,e.assertBeforeMutation),mutationSymlinks:e.mutationSymlinks??this.defaults.mutationSymlinks,denyMutations:mergeDenyMutationPolicies(this.defaults.denyMutations,e.denyMutations)}}async resolve(e){return assertValidRootDestinationPath(e),(await resolvePathInRoot(this.context,e,{allowFinalSymlink:!0,resolveCanonical:!0})).resolved}async open(e,t={}){return await openFileInRoot(this.context,{...readDefaults(this.defaults),...t,relativePath:e})}async read(e,t={}){return await readFileInRoot(this.context,{relativePath:e,...mergeReadOptions(this.defaults,t)})}async readBytes(e,t={}){return(await this.read(e,t)).buffer}async readText(e,t={}){let{encoding:n=`utf8`,...r}=t;return(await this.read(e,r)).buffer.toString(n)}async readJson(e,t={}){return JSON.parse(await this.readText(e,t))}async readAbsolute(e,t={}){let n=this.context,r=mergeReadOptions(this.defaults,t);return await readFileInRoot(n,{relativePath:rootRelativeReadPath(n,e),...r})}reader(e={}){return async t=>(await this.readAbsolute(t,e)).buffer}async openWritable(e,t={}){assertValidRootDestinationPath(e);let n=t.writeMode??`replace`;return(await openWritableFileInRoot(this.context,{mkdir:this.defaults.mkdir,mode:this.defaults.mode,...this.mutationOptions(t),relativePath:e,expectedWritePath:void 0,append:n===`append`,truncateExisting:n===`replace`}).catch(Zt)).opened}async append(e,t,n={}){assertValidRootDestinationPath(e),await appendFileInRoot(this.context,{mkdir:this.defaults.mkdir,mode:this.defaults.mode,...this.mutationOptions(n),relativePath:e,data:t,durable:n.durable??this.defaults.durable??!0}).catch(Zt)}async remove(e,t={}){assertValidRootRelativePath(e),validateRemoveOptions(t),t.signal?.throwIfAborted(),await removePathInRoot(this.context,{...this.mutationOptions(t),relativePath:e}).catch(Zt)}async mkdir(e,t={}){assertValidRootDestinationPath(e),await mkdirPathInRoot(this.context,{...this.mutationOptions(t),relativePath:e,allowRoot:!1}).catch(Zt)}async ensureRoot(e={}){await mkdirPathInRoot(this.context,{...this.mutationOptions(e),relativePath:``,allowRoot:!0}).catch(Zt)}async write(e,t,n={}){assertValidRootDestinationPath(e),await writeFileInRoot(this.context,{mkdir:this.defaults.mkdir,mode:this.defaults.mode,renameIdentity:this.defaults.renameIdentity,...this.mutationOptions(n),atomic:void 0,private:void 0,strictFileSync:void 0,relativePath:e,data:t,durable:n.durable??this.defaults.durable??!0}).catch(Zt)}async create(e,t,n={}){assertValidRootDestinationPath(e);let r=n.durable??this.defaults.durable??!0;await writeFileInRoot(this.context,{mkdir:this.defaults.mkdir,mode:this.defaults.mode,...this.mutationOptions(an(t,n,this.defaults.maxBytes)),relativePath:e,data:t,durable:r!==!1,strictFileSync:r===`file`,overwrite:!1}).catch(Zt).catch(xt)}async writeJson(e,t,n={}){let{replacer:r,space:i,trailingNewline:a=!0,...o}=n,s=stringifyJsonDocument(t,r,i);await this.write(e,a?`${s}\n`:s,o)}async createJson(e,t,n={}){let{replacer:r,space:i,trailingNewline:a=!0,...o}=n,s=stringifyJsonDocument(t,r,i);await this.create(e,a?`${s}\n`:s,o)}async copyIn(e,t,n={}){n.signal?.throwIfAborted(),assertValidRootDestinationPath(e);let{maxBytes:r,...i}=this.mutationOptions(n),a=typeof t==`string`?t:{root:t.root,relativePath:t.relativePath};await copyFileInRoot(this.context,{maxBytes:Ye(r,{defaultValue:this.defaults.maxBytes}),mkdir:this.defaults.mkdir,...i,source:a,relativePath:e,mode:n.mode??this.defaults.mode,durable:n.durable??this.defaults.durable??!0,verifyPublished:n[sa],admitSource:n[ca]},openVerifiedLocalFile).catch(Zt)}async exists(e){try{return await this.stat(e),!0}catch(e){if(e instanceof I&&e.code===`not-found`)return!1;throw e}}async stat(e){return assertValidRootRelativePath(e),validatePinnedRelativePath(e),await statPathFallback(this.context,e)}async list(e,t={}){return assertValidRootRelativePath(e),validatePinnedRelativePath(e),await listPathFallback(this.context,e,t.withFileTypes===!0)}async move(e,t,n={}){assertValidRootRelativePath(e),assertValidRootDestinationPath(t),validatePinnedRelativePath(e),validatePinnedRelativePath(t);let r=this.mutationOptions(n),{assertBeforeMutation:i}=r,{denyMutations:a,mutationSymlinks:o}=snapshotPinnedMutationPolicy(r.denyMutations,r.mutationSymlinks)??{},s=n.overwrite??!1,c=st();for(let n of[e,t]){let{resolved:e}=await resolvePathInRoot(this.context,n,{aliasErrorCode:`path-alias`,allowFinalSymlink:!0});await assertMutationNotDenied(e,a,{protectAncestors:!0})}await movePathFallback(this.context,{requireNative:c,fromRelative:e,denyMutations:a,assertBeforeMutation:i,mutationSymlinks:o,overwrite:s,toRelative:t}).catch(Zt)}entries(e,t={}){return assertValidRootRelativePath(e),entriesInRoot(this.context,e,{...t,symlinks:t.symlinks??this.defaults.symlinks})}walk(e,t){return assertValidRootRelativePath(e),walkRoot({rootReal:this.context.rootReal,observeRoot:()=>createRootObservationGuard(this.context),stat:e=>this.stat(e),list:async(e,t,n)=>{if(validatePinnedRelativePath(e),n)return await openRootDirectoryListing(this.context,n.targetPath,t,n);let r=await resolvePinnedPathInRoot(this.context,{relativePath:e,allowRoot:!0});return await openRootDirectoryListing(this.context,r.resolved,t)}},e,t)}};async function root$1(e,t={}){return Ye(t.maxBytes),new RootHandle(await resolveRootContext(e),t)}async function openFileInRoot(e,t){let{resolved:n}=await resolvePathInRoot(e,t.relativePath,{allowFinalSymlink:!0,rejectUnsafeDeviceReads:!0,...nt(t.symlinks),resolveCanonical:!0}),r=l();r?.afterRootReadPathResolution&&await r.afterRootReadPathResolution(n);let{handle:i,stat:a,identity:o}=await openLocalFileDescriptor(n,{symlinks:t.symlinks});return openResult(await admitRootReadHandle({root:e,filePath:n,opened:{handle:i,stat:a,exactIdentity:Xe(o)},identity:o,hardlinks:t.hardlinks,symlinks:t.symlinks,beforeFinalFence:r?.beforeRootReadFinalFence,afterPathIdentityCheck:r?.afterRootReadFinalPathIdentityCheck}))}async function readFileInRoot(e,t){let n=await openFileInRoot(e,t);try{return await readOpenedFileSafely({opened:n,maxBytes:t.maxBytes})}finally{await n.handle.close().catch(()=>{})}}function emitWriteBoundaryWarning(e){logWarn(`security: fs-safe write boundary warning (${e})`)}async function openWritableFileInRoot(e,t,n){let r=st(),i=r?snapshotPinnedMutationPolicy(t.denyMutations,t.mutationSymlinks):void 0;i&&(t={...t,...i});let a=t.denyMutations===void 0&&t.mutationSymlinks===void 0?void 0:await resolveGuardedWriteTargetInRoot(e,{relativePath:t.relativePath,denyMutations:t.denyMutations,mutationSymlinks:t.mutationSymlinks}),o=r&&!a&&t.assertBeforeMutation===void 0&&n?.createIfMissing!==!1?probeNativeCreationPath(e,t.relativePath):void 0,{resolved:s}=o??a?.resolvedPath??await resolveGuardedWritePathInRoot(e,{relativePath:t.relativePath}),resolveCurrent=async()=>(await resolveGuardedWritePathInRoot(e,{relativePath:t.relativePath,...i})).resolved,c=r&&t.mkdir!==!1;if(c){if(!P(`openBeneath`,`mkdirChildBeneath`,`closeOwnedFd`))throw new I(`helper-unavailable`,`native confined creation is unavailable`);a&&await tryMkdirRootNative({originalPath:t.relativePath,root:e,directory:Z.dirname(s),target:s,mkdir:!0,policy:i,resolveCurrent,assertBeforeMutation:t.assertBeforeMutation})}let l=!c&&a?await prepareSharedRootWriteTarget(e,{relativePath:t.relativePath,guardedTarget:a,mkdir:t.mkdir,assertBeforeMutation:t.assertBeforeMutation}):void 0,u=l?.preparedParent,d=c?s:l?.targetPath??(t.mkdir===!1?s:await prepareRootWriteTarget(e,s,t.assertBeforeMutation)),f=d,p=!!o;if(!o)try{L(d,t.mutationSymlinks!==void 0);let n=t.mutationSymlinks===void 0?O.native(d):d,r=M({rootPath:e.rootReal,candidatePath:n,rootIdentity:e.rootIdentity});if(!r)throw G();d=r.path}catch(e){if(e instanceof I||!E(e))throw e;p=!0}assertRootFallbackWritePath(t.expectedWritePath,d);let m=t.mode??384,g,_=!1,v,y,b,x=t.append?Ta:Ca,C=t.append?Ea:wa;try{b=a?await prepareGuardedRootWritePathSelection(a,d,f,u):void 0;let createNative=()=>tryOpenCreateRootNative({originalPath:t.relativePath,root:e,directory:Z.dirname(d),target:d,mkdir:t.mkdir!==!1,policy:i,selectedParent:o?.parent,resolveCurrent,assertBeforeMutation:t.assertBeforeMutation!==void 0||b!==void 0?()=>{t.assertBeforeMutation?.(),b&&assertRootWritePathSelectionSync(e,b)}:void 0,flags:C,existingFlags:x,mode:m}),s;if(r&&p&&!a&&t.assertBeforeMutation===void 0&&n?.createIfMissing!==!1)try{s=await createNative()}catch(e){if(!j(e,`EEXIST`)||!isNativeCreateCollision(e))throw e}if(s)g=s.handle,v=s.cleanupCreated,y=s.releaseCreationParent,_=!0;else try{b&&assertRootWritePathSelectionSync(e,b),g=await $.open(d,x,m)}catch(o){if(await h(o,d,x))throw new I(`not-file`,`path is not a regular file under root`);if(!E(o))throw o;if(n?.createIfMissing===!1){c&&!a&&await tryMkdirRootNative({originalPath:t.relativePath,root:e,directory:Z.dirname(d),target:d,mkdir:!0,policy:i,resolveCurrent,assertBeforeMutation:t.assertBeforeMutation});let n=b?.parentGuard??await F(Z.dirname(d),{bigint:!0});if(assertRootIdentityCurrentSync(e),!M({rootPath:e.rootReal,candidatePath:n.realPath,rootIdentity:e.rootIdentity}))throw G();return W(n),{missing:!0,targetPath:d,parentGuard:n,writeSelection:b}}b&&await refreshRootWritePathSelection(b);let s=r?await createNative():void 0;s?g=s.handle:(t.assertBeforeMutation?.(),b&&assertRootWritePathSelectionSync(e,b),Sa||L(d,!0),g=await $.open(d,C,m)),v=s?.cleanupCreated,y=s?.releaseCreationParent,_=!0}}catch(e){throw E(e)?Qe():S(e)?new I(`symlink`,`symlink open blocked`,{cause:e}):j(e,`EISDIR`)?new I(`not-file`,`not a file`,{cause:e}):e}let ee=null,T=null;try{let n=z(()=>{let e=Q.fstatSync(g.fd,{bigint:!0});if(!e.isFile())throw new I(`not-file`,`path is not a regular file under root`);if(e.nlink>1n)throw R();return e}),r=He(n);_&&(T=n);let i=!1;try{z(()=>{let e=Q.lstatSync(d,{bigint:!0});if(i=!0,e.isSymbolicLink()||!e.isFile())throw new I(e.isSymbolicLink()?`symlink`:`not-file`,`path is not a regular file under root`);if(e.nlink>1n)throw R();return e},n)}catch(e){if(!E(e)||i)throw e instanceof I&&e.code===`path-mismatch`?new I(`path-mismatch`,`path changed during write`,{cause:e}):e}let a=(await resolveOpenedFileRealPathForFd(g.fd,n,d)).realPath;w(a,`filesystem`,`resolved file path uses a Windows filesystem namespace alias`);try{z(()=>{let e=Q.statSync(a,{bigint:!0});if(!e.isFile())throw new I(`not-file`,`path is not a regular file under root`);if(e.nlink>1n)throw R();return e},n)}catch(e){throw e instanceof I&&e.code===`path-mismatch`?new I(`path-mismatch`,`path mismatch`,{cause:e}):e}let o=M({rootPath:e.rootReal,candidatePath:a,rootIdentity:e.rootIdentity});if(!o)throw G();a=o.path,ee=a,assertRootFallbackWritePath(t.expectedWritePath,a);let s=b?createRootWriteSelectionForFd(b,g.fd):void 0;t.append!==!0&&t.truncateExisting!==!1&&!_&&(s&&await refreshRetainedRootWriteAdmission(e,s,g.fd),L(d,t.mutationSymlinks!==void 0),t.assertBeforeMutation?.(),s&&assertRootWriteSelectionSync(e,s,g.fd),await g.truncate(0)),s&&(await refreshRetainedRootWriteAdmission(e,s,g.fd),assertRootWriteSelectionSync(e,s,g.fd));let c={handle:g,containment:`best-effort`,createdForWrite:_,realPath:a,stat:r,exactIdentity:Xe(n),[Symbol.asyncDispose]:()=>g.close().catch(()=>void 0)};return t.keepCreationParent||y?.(),{opened:c,identity:n,writeSelection:s,cleanupCreated:v,releaseCreationParent:y}}catch(e){let t=_&&e instanceof I,n=ee??d;t&&v&&await v().catch(()=>{});try{y?.()}catch{}throw await g.close().catch(()=>{}),t&&T&&!v&&await yt(n,T).catch(()=>{}),e}}async function appendFileInRoot(e,t){let n={stack:[],error:void 0,hasError:!1};try{let{opened:r,identity:i,cleanupCreated:a,releaseCreationParent:o}=await openWritableFileInRoot(e,{relativePath:t.relativePath,mkdir:t.mkdir,mode:t.mode,denyMutations:t.denyMutations,assertBeforeMutation:t.assertBeforeMutation,mutationSymlinks:t.mutationSymlinks,truncateExisting:!1,append:!0,keepCreationParent:!0});__addDisposableResource(n,{[Symbol.dispose](){o?.()}},!1);let s=!1;__addDisposableResource(n,{async[Symbol.asyncDispose](){!s&&r.createdForWrite&&!a&&await yt(r.realPath,i)}},!0),__addDisposableResource(n,r.handle,!0),__addDisposableResource(n,{async[Symbol.asyncDispose](){!s&&r.createdForWrite&&await a?.()}},!0);try{let e=``;if(t.prependNewlineIfNeeded===!0&&!r.createdForWrite&&r.stat.size>0&&t.data.length>0&&(typeof t.data==`string`&&!t.data.startsWith(`
`)||Buffer.isBuffer(t.data)&&t.data[0]!==10)){let n=Buffer.from(`
`,typeof t.data==`string`?t.encoding:`utf8`),i=Buffer.alloc(n.length),{bytesRead:a}=await r.handle.read(i,0,i.length,Math.max(0,r.stat.size-i.length));a>0&&(a!==n.length||!i.equals(n))&&(e=`
`)}let n=typeof t.data==`string`?`${e}${t.data}`:e.length>0?Buffer.concat([Buffer.from(e,`utf8`),t.data]):t.data;await writeAllToFile(r.handle,n,{encoding:t.encoding,assertBeforeMutation:()=>{L(r.realPath,t.mutationSymlinks!==void 0),t.assertBeforeMutation?.(),s=!0}}),s=!0,t.durable!==!1&&await r.handle.sync(),t.durable!==!1&&r.createdForWrite&&await syncDirectoryBestEffort(Z.dirname(r.realPath))}catch(e){Zt(e)}}catch(e){n.error=e,n.hasError=!0}finally{let e=xa(n);e&&await e}}async function removePathInRoot(e,t){validatePinnedRelativePath(t.relativePath);let n=st();n&&(t={...t,...snapshotPinnedMutationPolicy(t.denyMutations,t.mutationSymlinks)});let r=t.recursive?void 0:new RemovalPathReceipts,i=await resolvePinnedPathInRoot(e,{relativePath:t.relativePath,denyMutations:t.denyMutations,mutationSymlinks:t.mutationSymlinks,remove:!0,removalReceipts:r});try{n?await removePathInRootNative(e,i.resolved,t,r):await removePathInRootFallback(e,i.resolved,t,r)}catch(e){throw t.recursive?e:Ae(e)}}async function mkdirPathInRoot(e,t){let n=st(),r=resolveCreationPermissions(t,!0).private;validatePinnedRelativePath(t.relativePath);let i=t.denyMutations===void 0&&t.mutationSymlinks===void 0?void 0:snapshotPinnedMutationPolicy(t.denyMutations,t.mutationSymlinks);if(n&&!r&&!i&&!t.assertBeforeMutation){if(t.allowRoot&&t.relativePath===``){ensureNativeRootCurrent(e);return}if(tryMkdirNativeDirectChild(e,t.relativePath)||tryMkdirNativeParents(e,t.relativePath))return}let a={relativePath:t.relativePath,allowRoot:t.allowRoot,...i},o=i?async()=>await resolvePinnedPathInRoot(e,a):void 0,s=await resolvePinnedPathInRoot(e,a);if(n&&await tryMkdirRootNative({originalPath:t.relativePath,root:e,directory:s.resolved,target:s.resolved,mkdir:!0,private:r,policy:i,resolveCurrent:async()=>(await resolvePinnedPathInRoot(e,a)).resolved,assertBeforeMutation:t.assertBeforeMutation}))return;let c=i&&s.relativePosix!==``?await preparePinnedWriteMutationAdmission({rootReal:s.rootReal,rootIdentity:e.rootIdentity,resolvedTargetPath:s.resolved,originalPath:t.relativePath,defaultRelativeParentPath:Z.posix.dirname(s.relativePosix)===`.`?``:Z.posix.dirname(s.relativePosix),policy:i,resolveCurrent:o}):void 0;c?.mutationAdmission&&await l()?.beforePinnedWriteParentAdmission?.(s.resolved);try{if(!r&&c?.mutationAdmission&&t.assertBeforeMutation===void 0&&await tryMkdirAtExactParent(e,s.resolved,c.mutationAdmission))return;await mkdirPathFallback(e,s,t.assertBeforeMutation,i?.mutationSymlinks!==void 0,c?.mutationAdmission,r)}catch(e){throw Ae(e)}}async function writeFileInRoot(e,t){if(t.private!==void 0){let e=resolveCreationPermissions(t,!1);t={...t,private:e.private,mode:e.mode}}let n=rn(t);await St(rootWriteQueueKey(e,t.relativePath),async()=>{if(!t.private&&n.kind===`buffer`&&!n.stageBeforePublish&&process.platform===`win32`&&(t.renameIdentity===`verify-content-with-lock`||!getPinnedWriteNativeBinding({input:n}))){await writeFileFallback(e,{...t,data:n.data});return}let r=await resolvePinnedWriteTargetInRoot(e,t.relativePath,t.mode,t.denyMutations,t.overwrite,t.mutationSymlinks);await St(r.targetPath,async()=>{await commitPinnedWriteInRoot(e,r,t,n)})})}async function commitPinnedWriteInRoot(e,t,n,r){let i=!1;try{if(n.private&&assertPrivateFileCreationAvailable(),n.private&&n.mkdir!==!1&&await prepareRootWriteTarget(e,t.targetPath,n.assertBeforeMutation,t.mutationAdmission,!0)!==t.targetPath)throw new I(`path-mismatch`,`private creation parent changed during admission`);await runPinnedWriteWithRenamePolicy({rootPath:t.rootReal,relativeParentPath:t.relativeParentPath,basename:t.basename,targetPath:t.targetPath,renameIdentity:n.renameIdentity,mkdir:!n.private&&n.mkdir!==!1,private:n.private,mode:n.mode??t.mode,sync:n.durable!==!1,strictFileSync:n.strictFileSync,overwrite:n.overwrite,rejectFinalSymlink:n.mutationSymlinks!==void 0,input:r,maxBytes:r.kind===`buffer`?void 0:n.maxBytes,rootIdentity:e.rootIdentity,mutationAdmission:t.mutationAdmission,assertBeforeMutation:n.assertBeforeMutation,verifyPublished:async(r,a,o,s)=>{i=!0;try{await verifyRootWritePublication({fd:r,expectedIdentity:a,parentGuard:o,nativeParent:s,retention:n[Mt],verify:()=>verifyAtomicWriteResult({root:e,targetPath:t.targetPath,fd:r,expectedIdentity:a,parentGuard:o})})}catch(e){throw emitWriteBoundaryWarning(`post-write verification failed: ${String(e)}`),e}}})}catch(e){if(i)throw e;let t=e?.code;throw t===`file_lock_stale`||t===`file_lock_timeout`?e:n.overwrite===!1&&Ue(e)?new I(`already-exists`,`file already exists`,U(e)):pt(e)}}async function resolvePinnedPathInRoot(e,t){let n=await resolvePinnedRootPathInRoot(e,{relativePath:t.relativePath,policy:t.remove?oa.unlinkTarget:oa.strict,mutationSymlinks:t.mutationSymlinks,removalReceipts:t.removalReceipts}),r=Z.relative(n.rootReal,n.canonicalPath);if((r===``||r===`.`)&&t.allowRoot===!0)return await assertMutationNotDenied(n.canonicalPath,t.denyMutations),{rootReal:n.rootReal,resolved:n.canonicalPath,relativePosix:``};let i=r.split(Z.sep)[0];if(r===``||r===`.`||i===`..`||Z.isAbsolute(r))throw G();let a=r.split(Z.sep).join(Z.posix.sep),o=M({rootPath:n.rootReal,candidatePath:n.canonicalPath,rootIdentity:e.rootIdentity});if(!o)throw G();return n.canonicalPath=o.path,await assertMutationNotDenied(n.canonicalPath,t.denyMutations,{protectAncestors:t.remove===!0}),{rootReal:n.rootReal,resolved:n.canonicalPath,relativePosix:a}}async function resolvePinnedRootPathInRoot(e,t){await assertRootIdentityCurrent(e,t.removalReceipts?.observeRoot);let n=e.rootReal,r;try{let i=await expandRelativePathWithHome(t.relativePath),a={absolutePath:Z.isAbsolute(i)?i:`${ensureTrailingSep(n)}${i}`,rootPath:n,rootCanonicalPath:n,rootIdentity:e.rootIdentity,boundaryLabel:`root`,policy:t.policy,...ze(t.mutationSymlinks)};r=await(t.removalReceipts?Me(a,t.removalReceipts):_t(a))}catch(e){throw ve(e,t.relativePath)||(e instanceof I&&e.code===`symlink`?e:new I(`path-alias`,`path alias escape blocked`,{cause:e}))}return{rootReal:r.rootCanonicalPath,canonicalPath:r.canonicalPath}}async function statPathFallback(e,t){let n=l()?.beforeRootStatInitialObservation?await resolvePinnedPathInRoot(e,{relativePath:t,allowRoot:!0}):await resolvePinnedObservedPathInRoot(e,t,`stat`);return await statResolvedPathInRoot(e,n.resolved,n.receipt)}async function listPathFallback(e,t,n){let r=await resolvePinnedObservedPathInRoot(e,t,`directory`);return await listDirectoryPath(e,r.resolved,n,r.receipt)}async function movePathFallback(e,t){let n=t.overwrite&&t.assertBeforeMutation?await Promise.all([t.fromRelative,t.toRelative].map(expandRelativePathWithHome)):void 0,r=await resolvePathInRoot(e,t.fromRelative,{aliasErrorCode:`path-alias`,allowFinalSymlink:!0,...ze(t.mutationSymlinks)});await assertMutationNotDenied(r.resolved,t.denyMutations,{protectAncestors:!0});let i=await resolvePinnedRootPathInRoot(e,{relativePath:t.fromRelative,policy:oa.strict,mutationSymlinks:t.mutationSymlinks}),a,o=await resolveGuardedWritePathInRoot(e,{relativePath:t.toRelative,denyMutations:t.denyMutations,mutationSymlinks:t.mutationSymlinks,allowFinalSymlink:!0,protectDeniedAncestors:!0,shouldAssertNoPathAlias:async n=>{if(a=await resolvePinnedRootPathInRoot(e,{relativePath:t.toRelative,policy:oa.unlinkTarget}),!t.overwrite)return!0;let r;try{r=Q.lstatSync(n.resolved)}catch{}return!(process.platform!==`win32`&&t.overwrite&&r?.isSymbolicLink()===!0)}}),s;try{t.overwrite&&t.assertBeforeMutation?s=z(()=>admitMoveSourceStat(Q.lstatSync(r.resolved,{bigint:!0}))):admitMoveSourceStat(Q.lstatSync(r.resolved))}catch(e){throw E(e)?Qe(e instanceof Error?e:void 0):e}if(!a)throw new I(`path-mismatch`,`destination admission was not completed`);let c=t.overwrite&&t.requireNative?P()?.renameReplaceWithIdentity:void 0;if(t.overwrite&&!c&&t.requireNative)throw new I(`helper-unavailable`,`native overwrite move is unavailable`);if(!t.overwrite||c){await movePathNative(e,t,{sourcePath:r.resolved,sourceParentPath:Z.dirname(i.canonicalPath),targetPath:o.resolved,targetParentPath:Z.dirname(a.canonicalPath),sourceOriginalPath:n?.[0],targetOriginalPath:n?.[1],sourceCanonicalPath:i.canonicalPath,targetCanonicalPath:a.canonicalPath,expectedSourceIdentity:s},t.overwrite);return}let u={bigint:s!==void 0},d=await F(Z.dirname(r.resolved),u),f=Z.dirname(o.resolved)===d.dir?d:await tt(o.rootReal,Z.dirname(o.resolved),u),p=l()?.beforeRootFallbackMutation;p&&await p(`move`,o.resolved),await A(d),f!==d&&await A(f);try{if(L(r.resolved,t.mutationSymlinks!==void 0),L(o.resolved,t.mutationSymlinks!==void 0),t.assertBeforeMutation?.(),s){assertRootIdentityCurrentSync(e),W(d),f!==d&&W(f);for(let[s,c,l,u]of[[n[0],r.resolved,i.canonicalPath,oa.strict],[n[1],o.resolved,a.canonicalPath,oa.unlinkTarget]])for(let n of/* @__PURE__ */ new Set([Z.isAbsolute(s)?s:`${e.rootWithSep}${s}`,c]))try{if(gt({absolutePath:n,rootPath:e.rootReal,rootCanonicalPath:e.rootReal,rootIdentity:e.rootIdentity,boundaryLabel:`root`,policy:u,...ze(t.mutationSymlinks)}).canonicalPath!==l)throw new I(`path-mismatch`,`move route changed during authorization`)}catch(e){throw Ae(e)}z(()=>admitMoveSourceStat(Q.lstatSync(r.resolved,{bigint:!0})),s)}await $.rename(r.resolved,o.resolved)}catch(e){throw E(e)?Qe(e instanceof Error?e:void 0):j(e,`EEXIST`)?new I(`already-exists`,`destination exists`,U(e)):e}try{await A(d),f!==d&&await A(f)}catch(e){throw Ae(e)}}async function writeFileFallback(e,t){if(t.renameIdentity!==`verify-content-with-lock`)return await writeFileFallbackUnlocked(e,t);let n=snapshotPinnedMutationPolicy(t.denyMutations,t.mutationSymlinks);n&&(t={...t,...n});let{rootReal:r,resolved:i}=await resolveGuardedWritePathInRoot(e,{relativePath:t.relativePath,denyMutations:t.denyMutations,mutationSymlinks:t.mutationSymlinks});await withRootFallbackCompatibilityLock({rootPath:r,rootIdentity:e.rootIdentity,targetPath:i,assertBeforeMutation:t.assertBeforeMutation},async({targetPath:n,...r})=>await writeFileFallbackUnlocked(e,{...t,...r},n))}async function writeFileFallbackUnlocked(e,t,n){if(t.overwrite===!1){await writeMissingFileFallback(e,t,n);return}let r={relativePath:t.relativePath,mkdir:t.mkdir,denyMutations:t.denyMutations,assertBeforeMutation:t.assertBeforeMutation,mutationSymlinks:t.mutationSymlinks,truncateExisting:!1,expectedWritePath:n},i=await openWritableFileInRoot(e,r,{createIfMissing:!1}),a=`missing`in i?void 0:i,o=a?.opened,s=a?.writeSelection,c=`missing`in i?i.writeSelection:void 0,l=t.denyMutations!==void 0||t.mutationSymlinks!==void 0,u=`missing`in i?i.targetPath:s?.selectedPath??i.opened.realPath,d=t.mode??(o?o.stat.mode&511:void 0);if(l&&!s&&!c)throw await o?.handle.close().catch(()=>void 0),new I(`path-mismatch`,`write admission state was not retained`);let f=`missing`in i?i.parentGuard:s?.parentGuard??await F(Z.dirname(u),{bigint:!0}).catch(async e=>{throw await o?.handle.close().catch(()=>void 0),e}),p=null,m=null,h,g,_;try{p=buildAtomicWriteTempPath(u),s?await refreshRetainedRootWriteAdmission(e,s,o?.handle.fd):c&&await refreshRootWritePathSelection(c),t.assertBeforeMutation?.(),s?assertRootWriteSelectionSync(e,s,o?.handle.fd):c&&assertRootWritePathSelectionSync(e,c),assertRootIdentityCurrentSync(e),W(f),re(p),h=await $.open(p,wa,384),g=Q.fstatSync(h.fd,{bigint:!0}),d??=Number(g.mode&511n),m=sn(p,{identity:g,singleLinkFile:!0}),await writeAllToFile(h,t.data,{encoding:t.encoding,assertBeforeMutation:t.assertBeforeMutation}),t.durable!==!1&&await h.sync();let n=p,i=h,l=g;await Gt([f],async()=>{await verifyAtomicWriteResult({root:e,targetPath:n,fd:i.fd,expectedIdentity:l,parentGuard:f}),assertRootIdentityCurrentSync(e),W(f);let d=inspectFallbackReplacementDestination(u);if(d&&(!a||!Be(d,a.identity))){let t=await openWritableFileInRoot(e,{...r,mkdir:!1,expectedWritePath:u},{createIfMissing:!1});_=`missing`in t?void 0:t.opened.handle,d=`missing`in t?void 0:t.identity,await _?.close()}await o?.handle.close(),s?await refreshRetainedRootWriteAdmission(e,s):c&&await refreshRootWritePathSelection(c),L(u,t.mutationSymlinks!==void 0),t.assertBeforeMutation?.(),s?assertRootWriteSelectionSync(e,s):c&&assertRootWritePathSelectionSync(e,c),assertRootIdentityCurrentSync(e),W(f);let m=inspectFallbackReplacementDestination(u);if(d?!m||!Be(m,d):m)throw new I(`path-mismatch`,`write destination changed before publication`);await $.rename(n,u),p=null}),m(),m=null,await finishRootFallbackWrite({root:e,targetPath:u,handle:h,identity:g,parentGuard:f,mode:d,options:t,openForCompatibility:()=>openVerifiedLocalFile(u,{hardlinks:`reject`,readWrite:!0}),onVerificationFailure:e=>emitWriteBoundaryWarning(`post-write verification failed: ${String(e)}`)})}finally{await o?.handle.close().catch(()=>void 0),await _?.close().catch(()=>void 0),p&&h&&await kt({pathname:p,handle:h,identity:g,parentGuard:f}),await h?.close().catch(()=>void 0),m?.()}}function inspectFallbackReplacementDestination(e){let t;try{t=z(()=>Q.lstatSync(e,{bigint:!0}))}catch(e){if(E(e))return;throw e}if(t.isSymbolicLink()||!t.isFile())throw new I(`path-mismatch`,`write destination changed before publication`);if(t.nlink>1n)throw R();return t}async function writeMissingFileFallback(e,t,n){let r=t.denyMutations===void 0&&t.mutationSymlinks===void 0?void 0:await resolveGuardedWriteTargetInRoot(e,{relativePath:t.relativePath,denyMutations:t.denyMutations,mutationSymlinks:t.mutationSymlinks}),{resolved:i}=r?.resolvedPath??await resolveGuardedWritePathInRoot(e,{relativePath:t.relativePath}),a=r?await prepareSharedRootWriteTarget(e,{relativePath:t.relativePath,guardedTarget:r,mkdir:t.mkdir,assertBeforeMutation:t.assertBeforeMutation}):void 0,o=a?.mutationAdmission,s=a?.preparedParent,c=a?.targetPath??(t.mkdir===!1?i:await prepareRootWriteTarget(e,i,t.assertBeforeMutation));assertRootFallbackWritePath(n,c);let l=(r?await prepareGuardedRootWritePathSelection(r,c,c,s):void 0)?.parentGuard??await F(Z.dirname(c),{bigint:!0}),u=!1,d=!1,f,p,m=!1;try{let{handle:n,writtenStat:r}=await Gt([l],async()=>{L(c,t.mutationSymlinks!==void 0),t.assertBeforeMutation?.(),o&&W(l),re(c);let e=await $.open(c,wa,t.mode??384).catch(e=>recordExclusiveCreateFailure(e,c));p=e,u=!0;let n=Q.fstatSync(e.fd,{bigint:!0});return f=n,await writeAllToFile(e,t.data,{encoding:t.encoding,assertBeforeMutation:()=>{L(c,t.mutationSymlinks!==void 0),t.assertBeforeMutation?.(),o&&W(l)}}),t.durable!==!1&&await e.sync(),{handle:e,writtenStat:n}},{onPostGuardFailure:()=>{u=!1}});p=n,u=!1,m=!0,await verifyAtomicWriteResult({root:e,targetPath:c,expectedIdentity:r,fd:n.fd,parentGuard:l}),t.durable!==!1&&await syncDirectoryBestEffort(Z.dirname(c)),d=!0}catch(e){throw m?e:j(e,`EEXIST`)?new I(`already-exists`,`file already exists`,U(e)):e}finally{u&&p&&await kt({pathname:c,handle:p,identity:f,parentGuard:l}),d?await p?.close():await p?.close().catch(()=>void 0)}}function safeParseWithSchema(e,t){let n=e.safeParse(t);return n.success?n.data:null}function safeParseJsonWithSchema(e,t){try{return safeParseWithSchema(e,JSON.parse(t))}catch{return null}}function readLockFileOwnerPayload(e){return e?{pid:typeof e.pid==`number`&&Number.isInteger(e.pid)&&e.pid>0?e.pid:void 0,createdAt:typeof e.createdAt==`string`?e.createdAt:void 0,starttime:typeof e.starttime==`number`&&Number.isInteger(e.starttime)&&e.starttime>=0?e.starttime:void 0}:null}function inspectStaleLockOwner(e){let t=readLockFileOwnerPayload(e.payload);if(!t?.pid)return null;if((e.isPidDefinitelyDead??jr)(t.pid))return{reason:`owner-process-exited`,pid:t.pid,recordedStarttime:t.starttime??null,observedStarttime:null};let n=t.starttime===void 0?null:(e.getProcessStartTime??Nr)(t.pid),r={pid:t.pid,recordedStarttime:t.starttime??null,observedStarttime:n},i=process.platform===`darwin`&&t.starttime!==void 0&&t.starttime>1e10?Math.floor(t.starttime/1e6):t.starttime;return n!==null&&n!==i?{reason:`owner-starttime-changed`,...r}:null}function isLockOwnerDefinitelyStale(e){return inspectStaleLockOwner(e)!==null}const Da=J().min(1).max(4096),Oa={pid:Ar().int().positive(),startIdentity:Da.max(128)},ka=Y({...Oa,startIdentitySource:X(`argv-sha256`).nullable().optional()}).refine(({startIdentity:e,startIdentitySource:t})=>t===`argv-sha256`?/^win32-argv-sha256:[a-f0-9]{64}$/.test(e):!e.startsWith(`win32-argv-sha256:`)),Aa=Dr([Y({platform:kr([`linux`,`darwin`]),identity:J().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i)}),Y({platform:X(`win32`),identity:J().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z$/)}),Y({platform:X(`freebsd`),identity:J().regex(/^[a-f0-9]{32}$/)})]),ja=Y({kind:X(`native`),unit:Da,scope:Da,placement:Tr(`kind`,[Y({kind:X(`pending`)}),Y({kind:X(`attached`),invocation:J().regex(/^[a-f0-9]{32}$/i)})])}),Ma=X(`original-cancellation-v1`),Na=Y({kind:X(`update`),mutationProtocol:Ma}).extend({mutationProtocol:Ma.optional(),custody:kr([`reserved`,`bound`]).optional()}),Pa=Tr(`kind`,[Na,Y({kind:X(`triage`),phase:kr([`reserved`,`running`,`closing`,`closed`,`uncertain`]),lifetime:Tr(`kind`,[Y({kind:X(`foreground`),boot:Aa}),ja])}).refine(e=>e.phase!==`running`||e.lifetime.kind!==`native`||e.lifetime.placement.kind===`attached`)]),Fa=Da.refine(Z.isAbsolute,`Native source path must be absolute`),Ia=J().regex(/^[a-f0-9]{64}$/),La=Y({runId:Da,transactionId:Da,claimId:Da,revision:Ar().int().nonnegative(),recordSha256:Ia,serviceKey:Fa,configPaths:Or(Fa).min(1).max(512),lifetimeId:Da}),Ra=Y({id:J().uuid(),phase:kr([`reserved`,`admitted`]),source:La}),za={executor:ka,helper:ka,action:Pa},Ba=Y({version:X(2),executor:ka,helper:ka,action:Na}),Va=Y({key:Da,owner:Da,payload:J().min(1),updatedAt:Ar().int().nonnegative()}),Ha=Y({version:X(4),executor:ka,helper:ka,action:Na,cancellation:Va}).refine(e=>{let t=safeParseJsonWithSchema(Ba,e.cancellation.payload);return t!==null&&JSON.stringify(t.helper)===JSON.stringify(e.helper)&&JSON.stringify(t.executor)===JSON.stringify(e.executor)&&JSON.stringify(t.action)===JSON.stringify(e.action)&&(JSON.stringify(e.helper)===JSON.stringify(e.executor)||t.action.mutationProtocol===`original-cancellation-v1`)}),Ua=Y({version:X(2),...za,mutationOriginal:Va.optional()}).refine(e=>{if(!e.mutationOriginal)return!0;let t=safeParseJsonWithSchema(Ba,e.mutationOriginal.payload);return t!==null&&!e.mutationOriginal.key.includes(`/.openclaw-update-child-`)&&t.action.mutationProtocol===`original-cancellation-v1`});Tr(`version`,[Ha,Ua,Y({version:X(3),...za,action:Y({kind:X(`update`)}),nativeBorrower:Ra})]),Y({version:X(1),...Oa});function createManagedHandoffBootIdentityReader(e){return function(){let t,n=process.platform===`android`?`linux`:process.platform;if(n===`linux`)t=Q.readFileSync(`/proc/sys/kernel/random/boot_id`,`utf8`).trim();else if([`freebsd`,`darwin`,`win32`].includes(process.platform)){let n=process.platform===`freebsd`,r=process.platform===`win32`,i=Si(r?`powershell.exe`:n?`/sbin/sysctl`:`/usr/sbin/sysctl`,r?[`-NoProfile`,`-NonInteractive`,`-Command`,`(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o')`]:n?[`-b`,`kern.boot_id`]:[`-n`,`kern.bootsessionuuid`],{env:e,...n?{maxBuffer:16}:{encoding:`utf8`,windowsHide:!0},timeout:r?5e3:1e3,killSignal:`SIGKILL`,stdio:[`ignore`,`pipe`,`ignore`]});!i.error&&i.status===0&&(t=n?Buffer.isBuffer(i.stdout)&&i.stdout.length===16?i.stdout.toString(`hex`):void 0:i.stdout.toString().trim())}let r={platform:n,identity:n===`win32`?t:t?.toLowerCase()},i=Aa.safeParse(r);if(!i.success)throw Error(`OS boot identity unavailable; run openclaw triage manually`);return i.data}}const[Wa,Ga,Ka]=Aa.options,qa=J().min(1),Ja=J().regex(/^[a-f0-9]{64}$/u),Ya=Tr(`platform`,[Wa.extend({host:qa,platform:X(`linux`),pidNsInode:J().min(1)}),Wa.extend({host:qa,platform:X(`darwin`)}),Ga.extend({host:qa,identity:Ga.shape.identity.optional()}),Ka.extend({host:qa})]);let Xa;function readGatewayLockProcessNamespace(){if(Xa?.platform===process.platform&&(Xa.value!==null||process.platform!==`linux`&&process.platform!==`android`))return Xa.value;try{let e=process.platform===`win32`?{platform:`win32`}:createManagedHandoffBootIdentityReader(process.env)(),t=Ya.parse({host:pi.hostname(),...e,...e.platform===`linux`?{pidNsInode:Q.readlinkSync(`/proc/self/ns/pid`).match(/^pid:\[(\d+)\]$/u)?.[1]}:{}});return Xa={platform:process.platform,value:t},t}catch{return Xa={platform:process.platform,value:null},null}}function describeGatewayLockHolder(e,t,n){let r=Ya.safeParse(e.processNamespace).data,i=e.heartbeatAt;if(t)try{i=Q.statSync(t).mtimeMs}catch{}let a=i===void 0?void 0:Date.now()-i,o=`${r?.host??e.host??`unknown host`}${r?.platform===`linux`?`/pid-ns ${r.pidNsInode}`:``}`,s=n===`live`?`The holder ${e.pid} is alive on this host, stop it first`:n===`unknown`?"Stop the holder before retrying; if it has already stopped, run `openclaw gateway recover-lock` to inspect and explicitly recover the unchanged owner":"Run this command inside the Gateway container or with a shared PID namespace; if the holder has stopped, run `openclaw gateway recover-lock` to inspect and explicitly recover the unchanged owner";return`holder ${e.pid??`unknown`} at ${o}, last renewed ${a===void 0?`at an unknown time`:`${Math.max(0,Math.floor(a/1e3))} s ago`}. ${s}.`}var GatewayLockNamespaceError=class extends Error{constructor(e,t){super(`cannot verify Gateway ownership from this process; heartbeat age does not prove that the holder stopped. ${describeGatewayLockHolder(e,t)}`),this.name=`GatewayLockNamespaceError`}};function classifyGatewayLockProcessNamespace(e,t){if(process.platform===`win32`&&e&&e.processNamespace===void 0&&t){try{if(Date.now()-Q.statSync(t).mtimeMs>9e4&&isLockOwnerDefinitelyStale({payload:{pid:e.pid,starttime:e.startTime}}))return`dead`}catch{}return`unknown`}return classifyGatewayOwnerProcessNamespace(e?.processNamespace,{machineIdentity:e?.machineIdentity})}function classifyGatewayOwnerProcessNamespace(e,t={}){let n=Ya.safeParse(e).data;if(!n||t.ownerHost!==void 0&&t.ownerHost!==n.host)return`unknown`;let r=readGatewayLockProcessNamespace();if(!r||n.platform!==r.platform)return`unknown`;if(n.platform===`darwin`&&t.machineIdentity!==void 0){let e=Ja.safeParse(t.machineIdentity).data,i=Pn();if(e&&i){if(e!==i)return`unknown`;if(n.identity!==r.identity)return`dead`}}let i=n.platform===`darwin`&&r.platform===`darwin`&&n.identity===r.identity;return n.host!==r.host&&!i?`unknown`:n.platform===`win32`?`same`:n.identity===r.identity?n.platform!==`linux`||r.platform===`linux`&&n.pidNsInode===r.pidNsInode?`same`:`unknown`:`dead`}const Za=Er({pid:Ar(),ownerId:J().min(1).optional(),stateOwnerKind:X(`schema`).optional(),cronOwnerProjection:X(`dynamic-default-v1`).optional(),createdAt:J(),startupPhase:X(`starting`).optional(),configPath:J(),port:Ar().int().min(1).max(65535).optional(),role:kr([`gateway`,`agent-embedded`,`skill-workshop-apply`,`sqlite-maintenance`]).optional(),stateDir:J().optional(),startTime:Ar().optional(),parentPid:Ar().int().positive().optional(),parentStartTime:Ar().optional(),processNamespace:Ya.nullable().optional(),machineIdentity:Ja.nullable().optional()});function parseGatewayLockPayload(e){return safeParseJsonWithSchema(Za,e)}function sha256Hex(e){return ai(`sha256`,e,`hex`)}function sha256HexPrefixCore(e,t){return sha256Hex(e).slice(0,t)}const Qa=/* @__PURE__ */ new Set([`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`]);function hasRestrictivePermissions(e){try{return!(ui(e).mode&63)}catch{return!1}}function filesystemRejectsChmod(e){let t;try{let n=ui(e).isDirectory()?e:Z.dirname(e);t=Z.join(n,`.openclaw-chmod-probe-${oi()}`),fi(t,``,{flag:`wx`,mode:384})}catch{return!1}try{return si(t,384),!1}catch(e){return ne(e)&&e.code===`EPERM`}finally{try{di(t)}catch{}}}function canIgnorePrivateChmodError(e,t,n){return t&&Qa.has(t)?!0:t!==`EROFS`&&t!==`EPERM`?!1:n||t===`EPERM`&&filesystemRejectsChmod(e)}function applyPrivateModeSync(e,t){if((ui(e).mode&4095)===t)return{applied:!0};try{return si(e,t),{applied:!0}}catch(t){if(!canIgnorePrivateChmodError(e,ne(t)?t.code:void 0,hasRestrictivePermissions(e)))throw t;return{applied:!1,error:t}}}function ensureOwnerDirectory(e,t){let n=Q.mkdirSync(e,{recursive:!0,mode:448});if(n&&t){let r=Z.toNamespacedPath(n),i=[];for(let t=e;;){let{dev:e,ino:n}=Q.lstatSync(t,{bigint:!0});if(i.push({path:t,dev:e,ino:n}),Z.toNamespacedPath(t)===r)break;let a=Z.dirname(t);if(a===t)throw Error(`Created state ownership directory is outside its expected ancestry`);t=a}for(let e of i){let n=t.findIndex(t=>t.path===e.path);n<0?t.push(e):t[n]=e}}let r=Q.lstatSync(e),i=process.getuid?.();if(!r.isDirectory()||i!==void 0&&r.uid!==i)throw Error(`State ownership directory must be a user-owned real directory`);if(process.platform!==`win32`&&(r.mode&4095)!=448&&(applyPrivateModeSync(e,448),Q.lstatSync(e).mode&63))throw Error(`State ownership directory permissions are not private`)}function removeCreatedProjectionDirectories(e){let n=e[0];for(;n;){try{let e=Q.lstatSync(n.path,{bigint:!0});e.isDirectory()&&e.dev===n.dev&&e.ino===n.ino&&Q.rmdirSync(n.path)}catch(e){let n=t(e);if(n!==`ENOENT`&&n!==`ENOTEMPTY`&&n!==`EEXIST`)throw e}e.shift(),n=e[0]}}function resolveStateOwnerIdentity(e){let t=i(e);return stateOwnerIdentity(t,i(stateOwnerDirectory(t)))}async function resolveStateOwnerIdentityAsync(e){let t=await s(e);return stateOwnerIdentity(t,await s(stateOwnerDirectory(t)))}function stateOwnerIdentity(e,t){return{canonicalPath:e,ownerPath:Z.join(t,`state.${sha256HexPrefixCore(e,16)}.lock`),key:process.platform===`win32`?Ke(e):e}}function stateOwnerDirectory(t){let n=process.getuid?.();return process.platform===`win32`?Z.join(pi.homedir(),`AppData`,`Local`,`OpenClaw`,`locks`,n===void 0?`openclaw-state-owners`:`openclaw-state-owners-${n}`):e(yr(t))}function isGatewayStateOwnerLockSnapshotCurrent(e,t,n,r){return t.isFile()&&e.nlink!==0n&&e.dev===t.dev&&e.ino===t.ino&&r===n}function captureRootSyncAcquireOptions(e){let t=e.lockPath,n=e.staleMs,r=e.timeoutMs,i=e.retry,a=e.staleRecovery,o=e.reentrantOwner,s=e.payload,c=e.shouldReclaim,l=e.shouldRemoveStaleLock,u=e.parsePayload,d=e.onCompromised,f=e.compromiseCheckIntervalMs,p=i===void 0?void 0:Object.freeze({retries:i.retries,factor:i.factor,minTimeout:i.minTimeout,maxTimeout:i.maxTimeout,randomize:i.randomize}),m=en(),h=m.retry,g=p??Object.freeze({retries:h?.retries,factor:h?.factor,minTimeout:h?.minTimeout,maxTimeout:h?.maxTimeout,randomize:h?.randomize}),_=r??m.timeoutMs,v=n??m.staleMs??3e4,y=a??m.staleRecovery;return Bt(g),Xt(_),Vt(v),tn(f),Object.freeze({compromiseCheckIntervalMs:f,lockPath:t,onCompromised:d,optionsReceiver:e,parsePayload:u,payload:s,reentrantOwner:o,retry:g,shouldReclaim:c,shouldRemoveStaleLock:l,staleMs:v,staleRecovery:y,timeoutMs:_})}const $a=Symbol.for(`fsSafe.syncSidecarLocks`),eo=Symbol.for(`fsSafe.syncSidecarLockAdmissions`),to=Symbol.for(`fsSafe.syncSidecarLockCleanupRegistered`),no=Symbol.for(`fsSafe.syncSidecarLockCleanupHandler`),ro=Symbol.for(`fsSafe.syncSidecarLockCleanupRegistration`),io=Symbol.for(`fsSafe.syncRootSidecarLocks.v1`);function foreignSyncHeldLock(e,t){return globalThis[e===`raw`?io:$a]?.get(t)}function getSyncHeldLocks(){let e=globalThis;return e[$a]||(e[$a]=/* @__PURE__ */ new Map),e[$a]}function getSyncLockAdmissions(){let e=globalThis;return e[eo]||(e[eo]=/* @__PURE__ */ new Map),e[eo]}function syncReclaimGuardExists(e){try{return Q.lstatSync(e,{throwIfNoEntry:!1})!==void 0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function ensureSyncLockExitCleanupRegistered(e,t,n){Wt({event:`exit`,registered:to,registering:ro,handler:no,reentryError:()=>qt(t,n)},e,!0)}var SyncLockAcquisition=class{lockPath;normalizedTargetPath;retry;timeoutMs;#e=getSyncLockAdmissions();#t={};#n=!1;#r=performance.now();#i=0;#a=0;constructor(e,t,n,r){this.lockPath=e,this.normalizedTargetPath=t,this.retry=n,this.timeoutMs=r}get owns(){return this.#n}hasToken(){return this.#e.get(this.normalizedTargetPath)===this.#t}assert(){if(!this.hasToken())throw qt(this.lockPath,this.normalizedTargetPath)}reserve(){if(!this.#n){if(this.#e.has(this.normalizedTargetPath))throw qt(this.lockPath,this.normalizedTargetPath);this.#e.set(this.normalizedTargetPath,this.#t),this.#n=!0}}release(){this.#n&&this.hasToken()&&this.#e.delete(this.normalizedTargetPath),this.#n=!1}run(e){this.assert();try{return e()}finally{this.assert()}}waitForRetry(){this.release();let e=$t(this.retry,this.timeoutMs,performance.now()-this.#r,this.#i);if(e===void 0)throw qt(this.lockPath,this.normalizedTargetPath);le(e),this.#i+=1}retryDenial(e){if(!Yt(e,this.lockPath)||++this.#a>8)return!1;try{this.waitForRetry()}catch(t){throw t?.code===`file_lock_timeout`?e:t}return!0}monitor(e,t,n,r,i,a){if(!n||(r??0)<=0)return;let{lockPath:o,normalizedTargetPath:s}=this,c=setInterval(()=>{let r;try{r=t.verifyStillHeld()}catch{r=!1}!r&&e.timer&&(clearInterval(e.timer),e.timer=void 0,Reflect.apply(n,i,[{lockPath:o,normalizedTargetPath:s}]))},r);a?.(c),e.timer=c,c.unref()}};function observeDirectory(e,t){let n=B(e,void 0,t),r=O.native(D(e));if(w(r,`filesystem`,`sidecar lock parent uses a Windows filesystem namespace alias`),!sameAbsolutePath(r,e))throw new I(`path-mismatch`,`sidecar lock parent changed during operation`);return Object.freeze({identity:Object.freeze({dev:n.dev,ino:n.ino}),path:e,realPath:r})}function assertDirectoryCurrent(e,t){B(e.path,e.identity,t);let n=O.native(D(e.path));if(w(n,`filesystem`,`sidecar lock parent uses a Windows filesystem namespace alias`),n!==e.realPath)throw new I(`path-mismatch`,`sidecar lock parent changed during operation`)}function assertRetainedParentCurrent(e,t){let n=e.authority.context,r=t.path===n.rootReal&&t.identity.dev===n.rootIdentity.dev&&t.identity.ino===n.rootIdentity.ino,i;assertRootIdentityCurrentSync(n,r?e=>{i=e}:void 0),assertDirectoryCurrent(t,i),assertRootIdentityCurrentSync(n)}function exactFileIdentity(e){return Object.freeze({dev:e.dev,ino:e.ino})}function assertRegularFile(e,t){if(e.isSymbolicLink()||!e.isFile())throw new I(`not-file`,`sidecar lock is not a regular file`);if(t!==`allow`&&e.nlink>1n)throw R()}function sameExactIdentity(e,t){return e.dev===t.dev&&e.ino===t.ino}function assertFreshPathCurrent(e){assertFileLockSyncRootResolvedPathCurrent(e),assertRootIdentityCurrentSync(e.authority.context)}function missingAfterCurrentRead(e,t){return t?assertRetainedParentCurrent(e,t.parent):assertFreshPathCurrent(e),null}function readFileLockSyncRootSnapshot(e,t={}){let n=t.expectedReceipt;n?assertRetainedParentCurrent(e,n.parent):assertFreshPathCurrent(e);let r;try{r=z(()=>Q.lstatSync(D(e.path),{bigint:!0}),n?.identity)}catch(t){if(E(t)||n&&t instanceof I&&t.code===`path-mismatch`)return missingAfterCurrentRead(e,n);throw t}assertRegularFile(r,e.authority.hardlinks);let i=n?.parent??observeDirectory(Z.dirname(e.path)),a,o,s=!1;try{try{a=Q.openSync(D(e.path),ke())}catch(r){if(E(r))return missingAfterCurrentRead(e,n);throw t.onOpenFailure?.(r),r}let o;try{o=z(()=>Q.fstatSync(a,{bigint:!0}),exactFileIdentity(r))}catch(t){if(t instanceof I&&t.code===`path-mismatch`)return n?assertRetainedParentCurrent(e,i):(assertDirectoryCurrent(i),assertFreshPathCurrent(e)),null;throw t}assertRegularFile(o,e.authority.hardlinks);let s=Ee(a,1048576).toString(`utf8`),c;try{c=z(()=>Q.lstatSync(D(e.path),{bigint:!0}),exactFileIdentity(o))}catch(t){if(E(t)||t instanceof I&&t.code===`path-mismatch`)return n?assertRetainedParentCurrent(e,i):(assertDirectoryCurrent(i),assertFreshPathCurrent(e)),null;throw t}assertRegularFile(c,e.authority.hardlinks);let l=Q.fstatSync(a,{bigint:!0});n?assertRetainedParentCurrent(e,i):(assertDirectoryCurrent(i),assertFreshPathCurrent(e));let u={raw:s,payload:null,stat:l};return Object.freeze({receipt:Object.freeze({identity:exactFileIdentity(o),parent:i}),snapshot:u})}catch(e){throw s=!0,o=e,e}finally{if(a!==void 0)try{Q.closeSync(a)}catch(e){throw s?K(e,o,`sidecar snapshot admission and descriptor close both failed`):e}}}function fileLockSyncRootSnapshotStillCurrent(e,t){let n=readFileLockSyncRootSnapshot(e,{expectedReceipt:t.receipt});return!!n&&sameExactIdentity(n.receipt.identity,t.receipt.identity)&&Rt(n.snapshot,t.snapshot)}function fileReceiptCurrentAfterParentCheck(e,t){let n;try{n=z(()=>Q.lstatSync(D(e.path),{bigint:!0}),t.identity)}catch(e){if(E(e)||e instanceof I&&e.code===`path-mismatch`)return!1;throw e}return assertRegularFile(n,e.authority.hardlinks),assertRetainedParentCurrent(e,t.parent),!0}function fileLockSyncRootReceiptStillCurrent(e,t){return assertRetainedParentCurrent(e,t.parent),fileReceiptCurrentAfterParentCheck(e,t)}function ensureParent(e){let t=e.authority,n=t.context;assertFileLockSyncRootResolvedPathCurrent(e);let r=Z.dirname(e.path),i=M({rootPath:n.rootReal,candidatePath:r,rootIdentity:n.rootIdentity});if(!i)throw G();let a=i.relativePath,o=n.rootReal,s=observeDirectory(o);for(let r of a.split(Z.sep).filter(Boolean)){let i=Z.join(o,r);assertRootIdentityCurrentSync(n),assertDirectoryCurrent(s);let a=!1,c;try{if(c=Q.lstatSync(D(i),{bigint:!0}),c.isSymbolicLink()||!c.isDirectory())throw Ve()}catch(e){if(!E(e))throw e;a=!0}if(a){assertFileLockSyncRootMutationAllowed(i,t.denyMutations);let r=invokeFileLockSyncRootMutationAuthority(t);r&&assertFileLockSyncRootResolvedPathCurrent(e),assertDirectoryCurrent(s),assertRootIdentityCurrentSync(n),r&&assertFileLockSyncRootMutationAllowed(i,t.denyMutations);try{Q.mkdirSync(D(i))}catch(e){if(e.code!==`EEXIST`)throw e}}let l=observeDirectory(i,c);assertDirectoryCurrent(s),o=l.realPath,s=l}return assertRootIdentityCurrentSync(n),assertDirectoryCurrent(s),s}function createFileLockSyncRootFile(e,t){let n=ensureParent(e);invokeFileLockSyncRootMutationAuthority(e.authority)&&(assertFileLockSyncRootResolvedPathCurrent(e),assertRetainedParentCurrent(e,n));let r=process.platform!==`win32`&&typeof Q.constants.O_NOFOLLOW==`number`?Q.constants.O_NOFOLLOW:0,i,a;try{t.assertBeforeOpen();try{re(D(e.path))}catch(e){throw e.code===`EEXIST`&&t.onOpenFailure(e),e}try{i=Q.openSync(D(e.path),Q.constants.O_WRONLY|Q.constants.O_CREAT|Q.constants.O_EXCL|r,384)}catch(e){throw t.onOpenFailure(e),e}let o=z(()=>Q.fstatSync(i,{bigint:!0}));if(assertRegularFile(o,e.authority.hardlinks),a=Object.freeze({identity:exactFileIdentity(o),parent:n}),!fileReceiptCurrentAfterParentCheck(e,a))throw new I(`path-mismatch`,`created sidecar lock changed before admission`);return{fd:i,receipt:a}}catch(t){if(i===void 0)throw t;let n=i;i=void 0;try{if(Q.closeSync(n),a&&!removeFileLockSyncRootFile(e,a))throw new I(`path-mismatch`,`created sidecar lock changed before cleanup`)}catch(e){throw K(t,e,`file lock create admission and cleanup both failed`)}throw t}}function refreshFileLockSyncRootFileReceipt(e,t){if(!fileReceiptCurrentAfterParentCheck(e,t))throw new I(`path-mismatch`,`created sidecar lock changed before admission`);return t}function removeFileLockSyncRootFile(e,t,n,r){assertFileLockSyncRootMutationAllowed(e.path,e.authority.denyMutations);let matches=()=>{if(!n)return fileLockSyncRootReceiptStillCurrent(e,t);let r=readFileLockSyncRootSnapshot(e,{expectedReceipt:t});return!!r&&sameExactIdentity(r.receipt.identity,t.identity)&&Rt(r.snapshot,n)};if(!matches()||invokeFileLockSyncRootMutationAuthority(e.authority)&&!matches()||r?.()===!1)return!1;assertFileLockSyncRootMutationAllowed(e.path,e.authority.denyMutations),Q.unlinkSync(D(e.path)),assertRetainedParentCurrent(e,t.parent);let i;try{i=z(()=>Q.lstatSync(D(e.path),{bigint:!0}))}catch(e){if(E(e))return!0;throw e}if(assertRegularFile(i,e.authority.hardlinks),assertRetainedParentCurrent(e,t.parent),!sameExactIdentity(exactFileIdentity(i),t.identity))return!0;if(n){let r=readFileLockSyncRootSnapshot(e);if(assertRetainedParentCurrent(e,t.parent),r){if(!sameExactIdentity(r.receipt.identity,t.identity)||!Rt(r.snapshot,n))return!0}else{let n;try{n=z(()=>Q.lstatSync(D(e.path),{bigint:!0}))}catch(n){if(E(n))return assertRetainedParentCurrent(e,t.parent),!0;throw n}if(assertRegularFile(n,e.authority.hardlinks),assertRetainedParentCurrent(e,t.parent),!sameExactIdentity(exactFileIdentity(n),t.identity))return!0}}throw new I(`path-mismatch`,`sidecar lock was replaced during removal`)}function fileLockSyncRootGuardExists(e){assertRootIdentityCurrentSync(e.authority.context);let t;try{t=Q.lstatSync(D(e.path),{bigint:!0})}catch(t){if(E(t))return assertFileLockSyncRootResolvedPathCurrent(e),assertRootIdentityCurrentSync(e.authority.context),!1;throw t}if(t.isSymbolicLink()||!t.isDirectory()&&!t.isFile())throw Ve();t.isFile()&&assertRegularFile(t,e.authority.hardlinks);let n=observeDirectory(Z.dirname(e.path));return t.isFile()?assertRegularFile(z(()=>Q.lstatSync(D(e.path),{bigint:!0}),exactFileIdentity(t)),e.authority.hardlinks):B(e.path,exactFileIdentity(t)),assertDirectoryCurrent(n),assertFileLockSyncRootResolvedPathCurrent(e),assertRootIdentityCurrentSync(e.authority.context),!0}function createFileLockSyncRootDirectory(e){let t=ensureParent(e);invokeFileLockSyncRootMutationAuthority(e.authority)&&(assertFileLockSyncRootResolvedPathCurrent(e),assertRetainedParentCurrent(e,t));try{Q.mkdirSync(D(e.path))}catch(e){if(e.code===`EEXIST`)return null;throw e}let n=B(e.path),r=Object.freeze({identity:exactFileIdentity(n),parent:t});return assertRetainedParentCurrent(e,t),B(e.path,r.identity),r}function removeFileLockSyncRootDirectory(e,t){return!fileLockSyncRootDirectoryReceiptStillCurrent(e,t)||(assertFileLockSyncRootMutationAllowed(e.path,e.authority.denyMutations,!0),invokeFileLockSyncRootMutationAuthority(e.authority)&&!fileLockSyncRootDirectoryReceiptStillCurrent(e,t))?!1:(assertFileLockSyncRootMutationAllowed(e.path,e.authority.denyMutations,!0),Q.rmdirSync(D(e.path)),assertRetainedParentCurrent(e,t.parent),!0)}function fileLockSyncRootDirectoryReceiptStillCurrent(e,t){assertRetainedParentCurrent(e,t.parent);try{B(e.path,t.identity)}catch(e){if(E(e)||e instanceof I&&e.code===`path-mismatch`)return!1;throw e}return assertRetainedParentCurrent(e,t.parent),!0}const ao=Symbol.for(`fsSafe.syncRootSidecarLockCleanupRegistering.v1`),oo=Symbol.for(`fsSafe.syncRootSidecarLockCleanupRegistered.v1`),so=Symbol.for(`fsSafe.syncRootSidecarLockCleanupRegistrationFailed.v1`),co=Symbol.for(`fsSafe.syncRootSidecarLockCleanupHandler.v1`);function unavailable(e){return new I(`helper-unavailable`,e)}function exactListenerCount(e){return process.listeners(`exit`).filter(t=>t===e).length}function ensureFileLockSyncRootExitCleanupRegistered(e){let t=globalThis;if(t[oo]){if(typeof t[co]==`function`)return;throw t[so]=!0,unavailable(`Root sidecar exit cleanup registration state is inconsistent`)}if(t[so])throw unavailable(`Root sidecar exit cleanup registration previously failed`);if(t[ao])throw unavailable(`Root sidecar exit cleanup registration is already in progress`);if(t[co]!==void 0)throw t[so]=!0,unavailable(`Root sidecar exit cleanup handler exists without registration`);t[ao]=!0;let n,r=!1,i=!1;try{if(n=exactListenerCount(e),n!==0)throw i=!0,unavailable(`Root sidecar exit cleanup listener exists without registration`);if(r=!0,process.on(`exit`,e),exactListenerCount(e)!==n+1)throw unavailable(`Root sidecar exit cleanup listener was not registered exactly once`);t[co]=e,t[oo]=!0,t[so]=!1,t[ao]=!1}catch(a){let o=!1,s;if(r&&n!==void 0)try{let t=exactListenerCount(e);for(;t>n;){process.removeListener(`exit`,e);let n=exactListenerCount(e);if(n>=t)throw unavailable(`Root sidecar exit cleanup listener rollback made no progress`);t=n}if(t!==n)throw unavailable(`Root sidecar exit cleanup listener rollback was ambiguous`)}catch(e){o=!0,s=e}throw t[co]=void 0,t[oo]=!1,t[ao]=!1,i?(t[so]=!0,a):o?(t[so]=!0,K(a,s,`Root sidecar exit cleanup registration and rollback both failed`)):(t[so]=!1,a)}}const lo=Symbol.for(`fsSafe.syncRootSidecarLocks.v1`),uo=Symbol.for(`fsSafe.syncRootSidecarLockCleanupActive.v1`),fo=/* @__PURE__ */ new WeakMap;function readRootSyncHeldReleaseState(e){return e.releaseState}function readRootSidecarSnapshotSync(e,t,n,r){let i=readFileLockSyncRootSnapshot(e,{expectedReceipt:r,onOpenFailure:n});if(!i)return null;let a;try{a=Jt(i.snapshot.raw,t)}catch(n){if(t)try{if(!fileLockSyncRootSnapshotStillCurrent(e,i))throw new I(`path-mismatch`,`sidecar changed during payload parsing`)}catch(e){throw K(n,e,`sidecar parser and post-callback admission both failed`)}throw n}return t&&!fileLockSyncRootSnapshotStillCurrent(e,i)?null:{receipt:i.receipt,snapshot:{...i.snapshot,payload:a}}}function getRootSyncHeldLocks(){let e=globalThis;return e[lo]||(e[lo]=/* @__PURE__ */ new Map),e[lo]}function reactivateExactHeldLock(e,t,n){return e.get(t.normalizedTargetPath)!==t||t.releaseState===`released`?!1:(n&&(t.refCount+=1),t.releaseState=`active`,t.revision+=1,!0)}function finishDeferredExitReleases(e){let t=e.deferredExitReleases;if(t){for(let e of t)e.released=!0;t.clear(),e.deferredExitReleases=void 0}}function restoreDeferredExitReleases(e){let t=e.deferredExitReleases;if(!t)return 0;let n=t.size;return t.clear(),e.deferredExitReleases=void 0,n}function restoreExactHeldLockAfterExitCleanup(e,t){e.get(t.normalizedTargetPath)===t&&t.releaseState!==`released`&&(t.refCount+=restoreDeferredExitReleases(t),t.refCount<=0?(t.releaseState=`released`,t.revision+=1,e.delete(t.normalizedTargetPath)):(t.releaseState=`active`,t.revision+=1))}function releaseAllRootSyncHeldLocks(){let e=globalThis;if(!e[uo]){e[uo]=!0;try{let e=globalThis[lo];if(!e)return;getSyncLockAdmissions().clear();for(let[t,n]of e){if(e.get(t)!==n||n.releaseState!==`active`)continue;n.releaseState=`exit-cleaning`,n.revision+=1;let r=n.revision,i=n.timer,a=n.fd;n.timer=void 0,n.fd=void 0,i&&clearInterval(i);try{a!==void 0&&Q.closeSync(a)}catch{}let entryIsContinuous=()=>e.get(t)===n&&n.releaseState===`exit-cleaning`&&n.revision===r,beginFreshCleanupAttempt=()=>{n.releaseState=`exit-cleaning`,n.revision+=1,r=n.revision};if(!entryIsContinuous()){if(e.get(t)===n&&readRootSyncHeldReleaseState(n)!==`released`&&n.refCount===0)beginFreshCleanupAttempt();else{restoreExactHeldLockAfterExitCleanup(e,n);continue}}let o=!1;for(let r=0;r<2;r+=1){let i=!1,a=!1,s=!1;try{s=removeFileLockSyncRootFile(n.rootPath,n.rootReceipt,n.snapshot,()=>{let e=entryIsContinuous();return e||(i=!0),e})}catch{a=!0}if(!a&&s&&!i&&entryIsContinuous()){o=!0;break}let c=entryIsContinuous();if(e.get(t)===n&&readRootSyncHeldReleaseState(n)!==`released`&&(i||!c)&&n.refCount===0&&r+1<2)beginFreshCleanupAttempt();else{if(c&&n.refCount>0){o=!0;break}restoreExactHeldLockAfterExitCleanup(e,n);break}}o&&(finishDeferredExitReleases(n),n.releaseState=`released`,n.revision+=1,e.get(t)===n&&e.delete(t))}}finally{e[uo]=!1}}}function ensureRootSyncExitCleanupRegistered(){ensureFileLockSyncRootExitCleanupRegistered(releaseAllRootSyncHeldLocks)}function verifyRootSyncHeldLock(e){let t=e.rootPath,n=e.parsePayload,r=e.rootReceipt,i=n?readRootSidecarSnapshotSync(t,n,void 0,r):readFileLockSyncRootSnapshot(t,{expectedReceipt:r});return i?i.receipt.identity.dev===e.rootReceipt.identity.dev&&i.receipt.identity.ino===e.rootReceipt.identity.ino&&Rt(i.snapshot,e.snapshot):!1}function releaseRootSyncHeldLock(e,t){let n=getRootSyncHeldLocks();if(n.get(e.normalizedTargetPath)!==e||e.releaseState===`released`)return!0;if(e.releaseState!==`active`){if(e.deferredExitReleases?.has(t)||e.refCount<=0)return!1;if(!fileLockSyncRootReceiptStillCurrent(e.rootPath,e.rootReceipt))throw new I(`path-mismatch`,`held sidecar lock changed before release`);return--e.refCount,e.revision+=1,e.releaseState!==`exit-cleaning`||e.refCount>0||((e.deferredExitReleases??=/* @__PURE__ */ new Set).add(t),!1)}if(e.refCount>1){if(!fileLockSyncRootReceiptStillCurrent(e.rootPath,e.rootReceipt))throw new I(`path-mismatch`,`held sidecar lock changed before release`);return--e.refCount,e.revision+=1,!0}if(e.refCount!==1)return!1;e.refCount=0,e.releaseState=`releasing`,e.revision+=1;let r=e.revision,entryIsContinuous=()=>n.get(e.normalizedTargetPath)===e&&e.releaseState===`releasing`&&e.revision===r&&e.refCount===0,beginFreshReleaseAttempt=()=>{e.releaseState=`releasing`,e.revision+=1,r=e.revision},i=e.fd;e.fd=void 0;try{i!==void 0&&Q.closeSync(i)}catch(t){throw reactivateExactHeldLock(n,e,!0),t}if(!entryIsContinuous()){if(n.get(e.normalizedTargetPath)!==e||readRootSyncHeldReleaseState(e)===`released`)return!0;if(e.refCount>0)return reactivateExactHeldLock(n,e,!1),!0;beginFreshReleaseAttempt()}for(let t=0;t<2;t+=1){let r=!1,i;try{i=removeFileLockSyncRootFile(e.rootPath,e.rootReceipt,e.snapshot,()=>{let e=entryIsContinuous();return e||(r=!0),e})}catch(t){throw reactivateExactHeldLock(n,e,!0),t}if(!r&&entryIsContinuous()){if(!i)throw reactivateExactHeldLock(n,e,!0),new I(`path-mismatch`,`owned sidecar lock changed before release`);let t=e.timer;return e.timer=void 0,e.releaseState=`released`,e.revision+=1,n.get(e.normalizedTargetPath)===e&&n.delete(e.normalizedTargetPath),t&&clearInterval(t),!0}if(n.get(e.normalizedTargetPath)!==e||readRootSyncHeldReleaseState(e)===`released`)return!0;if(e.refCount>0)return reactivateExactHeldLock(n,e,!1),!0;if(e.refCount===0&&t+1<2)beginFreshReleaseAttempt();else throw reactivateExactHeldLock(n,e,!0),new I(`path-mismatch`,`held sidecar release continuity changed repeatedly`)}throw new I(`path-mismatch`,`held sidecar release could not complete`)}function createRootSyncHeldLockHandle(e){let t={held:e,released:!1},n=!1,release=()=>{if(!(t.released||n)){n=!0;try{releaseRootSyncHeldLock(e,t)&&(t.released=!0)}finally{n=!1}}},r={lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,verifyStillHeld:()=>verifyRootSyncHeldLock(e),release,[Symbol.dispose]:release};return fo.set(r,t),r}var FileLockSyncRootArbitrationCollision=class extends I{constructor(){super(`path-mismatch`,`file lock arbitration changed during local creation`)}};function cleanupCreatedRootSyncLock(e,t,n,r){let i=!1,a;try{r&&clearInterval(r)}catch(e){i=!0,a=e}try{if(Q.closeSync(t),!removeFileLockSyncRootFile(e,n))throw new I(`path-mismatch`,`created sidecar lock changed before cleanup`)}catch(e){throw i?K(a,e,`unpublished lock timer and file cleanup both failed`):e}if(i)throw a}function acquireFileLockSyncWithRoot(e,t,n){let r=captureFileLockSyncRootAuthority(n),i=captureRootSyncAcquireOptions(t);ensureRootSyncExitCleanupRegistered(),w(e),i.lockPath!==void 0&&w(i.lockPath);let a=normalizeFileLockSyncTargetWithRoot(r,Z.resolve(e)),o=admitFileLockSyncRootPath(r,Z.resolve(i.lockPath??`${a}.lock`)),s=admitFileLockSyncRootPath(r,`${o.path}.reclaim`),c=Object.freeze([o,s]),l=o.path,u=getRootSyncHeldLocks(),currentTargetHolder=()=>u.get(a)??foreignSyncHeldLock(`root`,a),tryReuseCurrentHeld=()=>{let e=u.get(a);if(e&&!foreignSyncHeldLock(`root`,a)&&i.reentrantOwner!==void 0&&e.reentrantOwner!==void 0&&i.reentrantOwner===e.reentrantOwner&&r.adapter===e.rootAuthority.adapter&&o.relativePath===e.rootPath.relativePath&&Z.relative(o.path,e.rootPath.path)===``&&e.releaseState!==`released`){if(!verifyRootSyncHeldLock(e))throw new I(`path-mismatch`,`held sidecar lock changed before reentrant reuse`);if(u.get(a)!==e||e.releaseState===`released`||foreignSyncHeldLock(`root`,a))throw new I(`path-mismatch`,`held sidecar lock changed during reentrant reuse`);return e.refCount+=1,e.revision+=1,createRootSyncHeldLockHandle(e)}};if(u.has(a)&&!foreignSyncHeldLock(`root`,a)){assertFileLockSyncRootPathsCurrent(c);let e=tryReuseCurrentHeld();if(e)return e}let d=new SyncLockAcquisition(l,a,i.retry,i.timeoutMs),f,p=!1,reuseCurrentHeld=()=>f?void 0:tryReuseCurrentHeld(),releaseReclaimGuard=()=>{let e=f;if(e){if(p=!0,!removeFileLockSyncRootDirectory(s,e))throw new I(`path-mismatch`,`owned sidecar reclaim guard changed before release`);f=void 0,p=!1}},assertOwnedReclaimGuardCurrent=()=>{let e=f;if(!e||!fileLockSyncRootDirectoryReceiptStillCurrent(s,e))throw new I(`path-mismatch`,`owned sidecar reclaim guard changed during acquisition`)};try{for(;;){if(d.reserve(),d.assert(),assertFileLockSyncRootPathsCurrent(c),d.assert(),f&&assertOwnedReclaimGuardCurrent(),!f&&fileLockSyncRootGuardExists(s)){d.waitForRetry();continue}if(currentTargetHolder()!==void 0){let e=reuseCurrentHeld();if(e)return e}let e=Reflect.apply(i.payload,i.optionsReceiver,[]);d.assert();let{raw:t,ownershipToken:n}=on(e);if(d.assert(),f&&assertOwnedReclaimGuardCurrent(),currentTargetHolder()!==void 0){let e=reuseCurrentHeld();if(e)return e;d.waitForRetry();continue}let m,h,g,_;try{let s=createFileLockSyncRootFile(o,{assertBeforeOpen:()=>{if(d.assert(),f&&assertOwnedReclaimGuardCurrent(),currentTargetHolder()!==void 0)throw new FileLockSyncRootArbitrationCollision},onOpenFailure:e=>{_={error:e}}});m=s.fd,h=s.receipt,Q.writeFileSync(m,t,`utf8`),Q.fsyncSync(m);let c={raw:t,payload:e,ownershipToken:n};f&&releaseReclaimGuard(),h=refreshFileLockSyncRootFileReceipt(o,h);let p={fd:m,lockPath:l,normalizedTargetPath:a,parsePayload:i.parsePayload,refCount:1,reentrantOwner:i.reentrantOwner,releaseState:`active`,revision:0,rootAuthority:r,rootPath:o,rootReceipt:h,snapshot:c},v=createRootSyncHeldLockHandle(p);if(d.monitor(p,v,i.onCompromised,i.compromiseCheckIntervalMs,i.optionsReceiver,e=>{g=e}),currentTargetHolder()!==void 0)throw new FileLockSyncRootArbitrationCollision;return d.assert(),u.set(a,p),m=void 0,g=void 0,v}catch(e){if(m!==void 0&&h){let t=m,n=h,r=g;m=void 0,h=void 0,g=void 0;try{cleanupCreatedRootSyncLock(o,t,n,r)}catch(t){throw K(e,t,`file lock acquisition and Root cleanup both failed`)}}if(e instanceof FileLockSyncRootArbitrationCollision){let e=reuseCurrentHeld();if(e)return e;d.waitForRetry();continue}let t=_!==void 0&&_.error===e;if(t&&d.retryDenial(e))continue;if(!t||e.code!==`EEXIST`)throw e;if(f){releaseReclaimGuard();let e=reuseCurrentHeld();if(e)return e;d.waitForRetry();continue}if(currentTargetHolder()!==void 0){let e=reuseCurrentHeld();if(e)return e;d.waitForRetry();continue}let n=!1,r;try{r=readRootSidecarSnapshotSync(o,i.parsePayload,e=>{n=Yt(e,l)})}catch(e){if(n&&d.retryDenial(e))continue;throw e}if(currentTargetHolder()!==void 0){let e=reuseCurrentHeld();if(e)return e;d.waitForRetry();continue}if(d.assert(),!r){d.waitForRetry();continue}let c=r.snapshot,u=Date.now(),v;if(i.shouldReclaim){if(v=Reflect.apply(i.shouldReclaim,i.optionsReceiver,[{lockPath:l,normalizedTargetPath:a,payload:c.payload,staleMs:i.staleMs,nowMs:u,heldByThisProcess:!1}]),q(v,`shouldReclaim`),d.assert(),!fileLockSyncRootSnapshotStillCurrent(o,r))throw new I(`path-mismatch`,`sidecar changed during reclaim policy callback`)}else v=Lt(c,i.staleMs,u);if(v){if(i.staleRecovery===`remove-if-unchanged`&&c.raw!==void 0&&i.shouldRemoveStaleLock){let e=createFileLockSyncRootDirectory(s);if(!e){d.waitForRetry();continue}f=e,p=!1;let t=Reflect.apply(i.shouldRemoveStaleLock,i.optionsReceiver,[{lockPath:l,normalizedTargetPath:a,raw:c.raw,payload:c.payload}]);if(q(t,`shouldRemoveStaleLock`),d.assert(),assertOwnedReclaimGuardCurrent(),t){if(!removeFileLockSyncRootFile(o,r.receipt,c,()=>{if(d.assert(),assertOwnedReclaimGuardCurrent(),currentTargetHolder()!==void 0)throw new FileLockSyncRootArbitrationCollision}))throw new I(`path-mismatch`,`stale sidecar changed before removal`);continue}if(!fileLockSyncRootSnapshotStillCurrent(o,r))throw new I(`path-mismatch`,`sidecar changed during stale-removal policy callback`);releaseReclaimGuard()}throw zt(l,a)}d.waitForRetry()}}}catch(e){if(f&&!p)try{releaseReclaimGuard()}catch(t){throw K(e,t,`file lock acquisition and reclaim cleanup both failed`)}throw e}finally{d.release()}}function handleSyncStaleAdmission(e,t){let n={},assertUnheld=()=>{if(e.assert(),t.currentHeld())throw n},retryHolderChange=t=>t===n&&(e.waitForRetry(),!0),r,i=!1;try{r=Ht(e.lockPath,{rejectNonFile:!0,onOpenFailure:()=>{i=!0,assertUnheld()}}),assertUnheld()}catch(t){if(retryHolderChange(t))return;try{assertUnheld()}catch(e){if(retryHolderChange(e))return;throw e}if(i&&e.retryDenial(t))return;throw t}let a=t.staleOptions;try{a.shouldReclaimObserved||(assertUnheld(),a.shouldReclaim=t.options.shouldReclaim,a.shouldReclaimObserved=!0,assertUnheld()),a.shouldRemoveObserved||(assertUnheld(),a.shouldRemove=t.options.shouldRemoveStaleLock,a.shouldRemoveObserved=!0,assertUnheld())}catch(e){if(retryHolderChange(e))return;try{assertUnheld()}catch(e){if(retryHolderChange(e))return;throw e}throw e}let o=t.parsePayload&&(e=>{assertUnheld();try{return Reflect.apply(t.parsePayload,void 0,[e])}finally{assertUnheld()}}),s;try{s=Ut(r,o),assertUnheld()}catch(e){if(retryHolderChange(e))return;throw e}if(!s){e.waitForRetry();return}let c=Date.now(),l;try{assertUnheld();try{l=a.shouldReclaim?Reflect.apply(a.shouldReclaim,t.options,[{lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,payload:s.payload,staleMs:t.staleMs,nowMs:c,heldByThisProcess:!1}]):Lt(s,t.staleMs,c),q(l,`shouldReclaim`)}finally{assertUnheld()}}catch(e){if(retryHolderChange(e))return;throw e}if(!l)e.waitForRetry();else{if(t.staleRecovery===`remove-if-unchanged`&&s.raw!==void 0&&a.shouldRemove!==void 0){let r;try{assertUnheld();try{r=Reflect.apply(a.shouldRemove,t.options,[{lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,raw:s.raw,payload:s.payload}]),q(r,`shouldRemoveStaleLock`)}finally{assertUnheld()}}catch(e){if(retryHolderChange(e))return;throw e}if(!r)throw zt(e.lockPath,e.normalizedTargetPath);try{Q.mkdirSync(t.reclaimGuardPath)}catch(t){try{assertUnheld()}catch(e){if(retryHolderChange(e))return;throw e}if(t.code===`EEXIST`){e.waitForRetry();return}throw t}let i=!1;try{if(assertUnheld(),nn(e.lockPath,s,assertUnheld))return}catch(e){if(e===n)i=!0;else throw e}finally{try{Q.rmdirSync(t.reclaimGuardPath)}catch{}}if(i){e.waitForRetry();return}}throw zt(e.lockPath,e.normalizedTargetPath)}}function releaseAllSyncHeldLocks(){let e=getSyncHeldLocks();for(let[t,n]of e){n.timer&&=(clearInterval(n.timer),void 0);try{n.fd!==void 0&&Q.closeSync(n.fd)}catch{}try{nn(n.lockPath,n.snapshot)}catch{}e.delete(t)}getSyncLockAdmissions().clear()}function verifySyncHeldLock(e){let t=e.lockPath,n=e.parsePayload,r=n?It(t,n):Ht(t);return!!r&&Rt(r,e.snapshot)}function releaseSyncHeldLock(e){let t=getSyncHeldLocks();if(t.get(e.normalizedTargetPath)!==e)return!1;if(e.refCount>1)return--e.refCount,!1;if(e.timer&&=(clearInterval(e.timer),void 0),e.fd!==void 0){let t=e.fd;e.fd=void 0,Q.closeSync(t)}return nn(e.lockPath,e.snapshot),t.delete(e.normalizedTargetPath),!0}function createSyncHeldLockHandle(e){let t=!1,release=()=>{t||=(releaseSyncHeldLock(e),!0)};return{lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,verifyStillHeld:()=>verifySyncHeldLock(e),release,[Symbol.dispose]:release}}function canonicalLockParentSync(e){return process.platform===`win32`?O.native(e):O(e)}function normalizeTargetPath(e){let t=Z.resolve(e);w(t);let n=Z.dirname(t),r=!1;try{r=Q.statSync(n).isDirectory()}catch{}r||Q.mkdirSync(ge(n),{recursive:!0});let i;try{i=canonicalLockParentSync(Z.dirname(t))}catch{return t}w(i);let a=Z.join(i,Z.basename(t));return w(a),a}function acquireFileLockSync(e,t){let n=t.lockRoot;if(n)return acquireFileLockSyncWithRoot(e,t,n);let r=en(),i=t.retry??r.retry??{},a=t.timeoutMs??r.timeoutMs;Bt(i),Xt(a);let o=t.staleMs??r.staleMs??3e4;Vt(o);let s=t.compromiseCheckIntervalMs;tn(s);let c=t.lockPath;w(e),c!==void 0&&w(c);let l=normalizeTargetPath(e),u=Z.resolve(c??`${l}.lock`);w(u);let d=t.reentrantOwner,f=getSyncHeldLocks(),currentTargetHolder=()=>f.get(l)??foreignSyncHeldLock(`raw`,l),p=f.get(l);if(p&&!foreignSyncHeldLock(`raw`,l)&&d!==void 0&&p.reentrantOwner!==void 0&&d===p.reentrantOwner)return p.refCount+=1,createSyncHeldLockHandle(p);let m=new SyncLockAcquisition(u,l,i,a),h,g,_=!1,v,y=!1,b,x=!1,S={},C=`${u}.reclaim`;try{for(;;){if(!m.owns){let e=f.get(l);if(e&&!foreignSyncHeldLock(`raw`,l)&&d!==void 0&&e.reentrantOwner!==void 0&&d===e.reentrantOwner)return e.refCount+=1,createSyncHeldLockHandle(e);m.reserve()}let e=currentTargetHolder(),holderWasReplaced=()=>{let t=currentTargetHolder();return t!==void 0&&t!==e};if(!x&&(b=m.run(()=>t.staleRecovery??r.staleRecovery),x=!0,holderWasReplaced())){m.waitForRetry();continue}let n=syncReclaimGuardExists(C);if(!m.hasToken())throw qt(u,l);if(holderWasReplaced()||n){m.waitForRetry();continue}let i,a,c;if(h||=m.run(()=>t.payload),holderWasReplaced()){m.waitForRetry();continue}let p=m.run(()=>Reflect.apply(h,t,[]));if(holderWasReplaced()){m.waitForRetry();continue}let{raw:w,ownershipToken:ee}=m.run(()=>on(p));if(holderWasReplaced()||currentTargetHolder()!==void 0||!_&&(g=m.run(()=>t.onCompromised),_=!0,currentTargetHolder()!==void 0)||!y&&(v=m.run(()=>t.parsePayload),y=!0,currentTargetHolder()!==void 0)){m.waitForRetry();continue}let T=!1,E=!1;try{let e=process.platform!==`win32`&&typeof Q.constants.O_NOFOLLOW==`number`?Q.constants.O_NOFOLLOW:0;try{re(u)}catch(e){throw E=e.code===`EEXIST`,e}try{i=Q.openSync(u,Q.constants.O_WRONLY|Q.constants.O_CREAT|Q.constants.O_EXCL|e,384)}catch(e){throw T=Yt(e,u),E=e.code===`EEXIST`,e}Q.writeFileSync(i,w,`utf8`),Q.fsyncSync(i),c={raw:w,payload:p,stat:Q.fstatSync(i,{bigint:!0}),ownershipToken:ee},a={fd:i,lockPath:u,normalizedTargetPath:l,parsePayload:v,refCount:1,reentrantOwner:d,snapshot:c};let n=a;if(ensureSyncLockExitCleanupRegistered(releaseAllSyncHeldLocks,u,l),!m.hasToken()||currentTargetHolder()!==void 0)throw qt(u,l);let r=createSyncHeldLockHandle(n);if(m.monitor(n,r,g,s,t),!m.hasToken()||currentTargetHolder()!==void 0)throw qt(u,l);return f.set(l,n),m.release(),i=void 0,r}catch(e){if(a?.timer&&(clearInterval(a.timer),a.timer=void 0),a&&f.get(l)===a&&f.delete(l),i!==void 0){let t=c??{payload:null};if(!t.stat)try{t.stat=Q.fstatSync(i,{bigint:!0})}catch{}let n=i;i=void 0,a&&(a.fd=void 0);try{Q.closeSync(n),t.stat&&nn(u,t)}catch(t){throw K(e,t,`file lock acquisition and cleanup both failed`)}}if(T){if(!m.hasToken())throw qt(u,l);if(currentTargetHolder()!==void 0){m.waitForRetry();continue}if(m.retryDenial(e))continue;throw e}if(!E)throw e;if(!m.hasToken())throw qt(u,l);if(currentTargetHolder()!==void 0){m.waitForRetry();continue}handleSyncStaleAdmission(m,{currentHeld:currentTargetHolder,options:t,parsePayload:v,reclaimGuardPath:C,staleMs:o,staleOptions:S,staleRecovery:b});continue}}}finally{m.release()}}const po=Date.now.bind(Date);function captureLock(e){let t=Q.readFileSync(e.lockPath,`utf8`);if(!e.verifyStillHeld())throw Error(`OpenClaw state ownership is no longer current`);return t}function startGatewayStateOwnerHeartbeat(e,t){let n={};for(let t of e)n[t.lockPath]=captureLock(t);let r=Object.keys(n)[0];if(!r)throw Error(`Gateway state ownership requires a held lock`);let i=Q.statSync(r,{bigint:!0}),{moduleUrl:o,runtimeGeneration:s}=lr(cr(`gatewayStateOwnerHeartbeat`));return _(()=>{let c=new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));Atomics.store(c,0,BigInt(po()));let{port1:l,port2:d}=new hi,f=zr(o,{workerData:{clock:`epoch`,locks:n,intervalMs:15e3,failureMs:6e4,lastBeat:c.buffer,events:d},transferList:[d],execArgv:Kr(o)}),p=v();f.on(`message`,e=>{e===`closed`&&p.resolve()}),f.unref();let m=0,h=/* @__PURE__ */ new Map,rejectPending=e=>{for(let t of h.values())t.reject(e);h.clear(),l.unref()};l.on(`message`,e=>{if(Vr(`lifecycle`,`from_worker`),e===`parent-lost`)Hr();else if(e&&typeof e==`object`&&e.type===`lost`)t(/* @__PURE__ */ Error(`${e.error}; restart the Gateway.`),e.lockPath);else if(e&&typeof e==`object`&&e.type===`verified`){let t=h.get(e.id);h.delete(e.id),h.size===0&&l.unref(),e.error?t?.reject(Error(e.error)):t?.resolve(e.current)}}),l.unref(),f.on(`error`,e=>{let n=/* @__PURE__ */ Error(`${u(e)}; restart Gateway.`);rejectPending(n),t(n)}),f.once(`exit`,()=>{p.resolve(),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership verification worker stopped`))});let g,remainingUntilInspection=()=>{let e=Atomics.load(c,0),t=po()-Number(e);return t<0?0:6e4-t},inspect=()=>{let e=remainingUntilInspection();if(e<=0)throw Error(`Gateway state ownership renewal is overdue at ${r}; retry after storage recovers.`);return e},renewAsync=async()=>{let t=po(),a=new Date(t);for(let t of e)try{let o=n[t.lockPath];if(o===void 0)throw Error(`owner acquisition bytes were not registered`);let s=await Q.promises.open(t.lockPath,`r+`);try{let n=await s.stat({bigint:!0}),c=await Q.promises.lstat(t.lockPath,{bigint:!0}),l=Buffer.alloc(Buffer.byteLength(o)+1),{bytesRead:u}=await s.read(l,0,l.length,0),d=await Q.promises.lstat(t.lockPath,{bigint:!0});if(g||!e.has(t))continue;if(!isGatewayStateOwnerLockSnapshotCurrent(n,c,o,l.subarray(0,u).toString(`utf8`))||!d.isFile()||d.dev!==n.dev||d.ino!==n.ino||t.lockPath===r&&(n.dev!==i.dev||n.ino!==i.ino)){if(t.lockPath!==r)continue;throw Error(`owner lock was removed or replaced`)}await s.utimes(a,a)}finally{await s.close()}}catch(e){if(t.lockPath!==r&&j(e,`ENOENT`))continue;throw e}!g&&e.size>0&&Atomics.store(c,0,BigInt(t))},_,y,watch=()=>{let e=remainingUntilInspection();e>0?(_=setTimeout(watch,e),_.unref()):y??=renewAsync().then(()=>{y=void 0,g||watch()},e=>{y=void 0,g||t(/* @__PURE__ */ Error(`Gateway state ownership is no longer current at ${r}: ${u(e)}; restart the Gateway.`))})};watch();let stop=()=>(g||=(clearTimeout(_),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership is no longer current`)),l.close(),f.ref(),f.postMessage(`stop`,[]),(async()=>(await Gr(p.promise,1e3)||process.emitWarning(`Gateway state-owner heartbeat did not close within ${Wr}ms; forcing termination. Lock file descriptors may remain open until process exit.`,{code:`GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT`}),f.terminate()))()),Promise.all([g,y]).then(()=>void 0));s?.retain(f,async()=>async()=>{await stop()});let assertActive=()=>{if(g||f.threadId===-1)throw Error(`Gateway state ownership verification worker stopped`)},b=new Set(Object.keys(n));return{worker:f,paths:b,register(e){let t=captureLock(e);n[e.lockPath]=t,f.postMessage([e.lockPath,t],[]),b.add(e.lockPath)},inspect,assertActive,verify(e){assertActive();let t=++m;return new Promise((n,r)=>{h.set(t,{resolve:n,reject:r}),l.ref();try{f.postMessage({type:`verify`,id:t,paths:e},[])}catch(e){h.delete(t),h.size===0&&l.unref(),r(a(e,`Gateway state ownership verification failed`))}})},stop}})}function hasPhysicalOwnership(e){try{return verifyOwnerLock(e,e.locks.values().next().value)}catch(t){if(e.lost.signal.aborted)return!1;throw t}}function verifyOwnerLock(e,t){if(e.lost.signal.throwIfAborted(),e.heartbeat?.inspect(),!t)return!1;let n=e.getProjection?.();n&&e.heartbeat&&!e.heartbeat.paths.has(n.lockPath)&&e.heartbeat.register(n);let r=e.payload.role??`gateway`;return e.kind===`process`&&e.accepting&&(r===`gateway`||r===`agent-embedded`)&&e.heartbeat?(e.heartbeat.assertActive(),!0):t.verifyStillHeld()?!0:(loseOwner(e,/* @__PURE__ */ Error(`${t.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`)),!1)}const mo=g(`gateway/state`);function loseOwner(e,t){e.lost.signal.aborted||(e.accepting=!1,ho.clear(),e.heartbeat?.stop(),mo.error(t.message),e.lost.abort(t))}function observeOwnerLoss(e,t,n){let r=[...e.locks,e.getProjection?.()];(!n||r.some(e=>e?.lockPath===n))&&loseOwner(e,t)}const ho=r(Symbol.for(`openclaw.gatewayStateReadOwnerPaths`),()=>/* @__PURE__ */ new Map),go=r(Symbol.for(`openclaw.gatewayStateOwners`),()=>/* @__PURE__ */ new Map),_o=/* @__PURE__ */ new Set([`--port`,`--bind`,`--token`,`--token-file`,`--auth`,`--password`,`--password-file`,`--tailscale`,`--ws-log`,`--raw-stream-path`]),vo=/* @__PURE__ */ new Set([`--tailscale-reset-on-exit`,`--allow-unconfigured`,`--dev`,`--ambient-channels`,`--dev-ambient-channels`,`--reset`,`--update-canary`,`--force`,`--verbose`,`--cli-backend-logs`,`--claude-cli-logs`,`--compact`,`--raw-stream`]);function isForegroundGatewayRunArgv(e){let t=qr(e,{commandPath:[`gateway`],booleanFlags:[...vo,`--task-supervisor`],valueFlags:[..._o,`--task-supervisor-child`],mode:`command-path`});return t?t.length===0||t.length===1&&t[0]===`run`:!1}const yo=new yi;function comparableStateOwnerStaleReason(e,t){return t===`dead`?`owner-process-exited`:t===`same`?inspectStaleLockOwner({payload:{pid:e.pid,starttime:e.startTime}})?.reason:void 0}function isGatewayStateOwnerDefinitelyStale(e,t){let n=o(e)?e:null;if(!n)return!1;let r=classifyGatewayLockProcessNamespace(n,t);if(r===`unknown`)throw new GatewayLockNamespaceError(n,t);return comparableStateOwnerStaleReason(n,r)!==void 0}function assertPersistedStateDatabaseAccessAllowed(e){let{databasePath:n,ownerPath:r,assertMaintenance:i}=e,a=`OpenClaw state ownership at ${n} could not be verified from ${r}; restart the Gateway.`,o;try{o=Q.readFileSync(r,`utf8`)}catch(e){if(t(e)===`ENOENT`)return;throw new Br(a,{cause:e})}let s=yo.getStore();if(s?.deadOwner?.path===r&&s.deadOwner.raw===o)return;let c=parseGatewayLockPayload(o);if(!c)throw new Rr(n,a);if(!Number.isSafeInteger(c.pid)||c.pid<=0)throw new Br(a);let l=classifyGatewayLockProcessNamespace(c,r),u=comparableStateOwnerStaleReason(c,l);if(u){s&&u===`owner-process-exited`&&(s.deadOwner={path:r,raw:o});return}if(l===`same`&&c.pid===process.pid&&!gi)return;if(l===`same`&&!Mr(c.pid))throw new Rr(n,a);let d=c.role??`gateway`;if(d===`gateway`||d===`agent-embedded`)return;if(l===`same`&&c.pid===process.pid){i();return}let f=`OpenClaw state at ${n} is undergoing offline maintenance by ${d} process ${c.pid} (ownerKind=${c.stateOwnerKind??`process`}); retry when it finishes. For update progress, run \`openclaw update status --json\`.`;throw c.stateOwnerKind===`schema`&&c.role===`sqlite-maintenance`?new Rr(n,f):new Ir(n,f)}function defaultPayload(e){let t=yr(e),n=Nr(process.pid),r=Ur(),i=r===void 0?null:Nr(r);return{pid:process.pid,ownerId:oi(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),stateDir:t,configPath:Z.join(t,`openclaw.json`),role:`sqlite-maintenance`,processNamespace:readGatewayLockProcessNamespace(),machineIdentity:process.platform===`darwin`?Pn():void 0,...r===void 0?{}:{parentPid:r},...i===null?{}:{parentStartTime:i},...n===null?{}:{startTime:n}}}function assertGatewayRestorationPriority(e,n,r){if(r.role===`gateway`)return;let i;try{i=Q.readFileSync(n,`utf8`)}catch(e){if(t(e)===`ENOENT`)return;throw e}let a=parseGatewayLockPayload(i);if(!(isGatewayStateOwnerDefinitelyStale(a,n)||a?.pid===r.pid)&&!(r.pid===process.pid&&isForegroundGatewayRunArgv(process.argv)&&Jr(process.argv,{command:`gateway`}).kind===`openclaw`))throw new Rr(e,`Gateway restoration has priority for OpenClaw state at ${e}; retry when it finishes.`)}function acquireGatewayStateOwnerFile(e,n,r,i=0,a){let o=performance.now()+i,s=`${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;assertGatewayRestorationPriority(e,s,r),ensureOwnerDirectory(Z.dirname(n),a);let c={holder:null},stale=({payload:e})=>(c.holder=Za.safeParse(e).data??null,isGatewayStateOwnerDefinitelyStale(c.holder,n));if(i>0)try{let t=c.holder=parseGatewayLockPayload(Q.readFileSync(n,`utf8`));if(t&&!isGatewayStateOwnerDefinitelyStale(t,n)&&(t.pid===process.pid||(t.role??`gateway`)===`gateway`&&Mr(t.pid)))throw new Fr(e)}catch(e){if(t(e)!==`ENOENT`)throw e}for(let l=!1;;)try{return acquireFileLockSync(n,{lockPath:n,retry:i>0?{factor:1.25,minTimeout:10,maxTimeout:25,randomize:!1}:{retries:0},timeoutMs:Math.max(0,Math.ceil(o-performance.now())),staleMs:1/0,staleRecovery:`remove-if-unchanged`,reentrantOwner:r.ownerId,payload:()=>(assertGatewayRestorationPriority(e,s,r),r),shouldReclaim:stale,shouldRemoveStaleLock:stale})}catch(r){let i=t(r);if(i===`ENOENT`&&!l){l=!0,ensureOwnerDirectory(Z.dirname(n),a);continue}if(i===`file_lock_timeout`||i===`file_lock_stale`){let{holder:t}=c,i=describeGatewayLockHolder(t??{},n,t&&Mr(t.pid)?`live`:`unknown`);throw new Fr(e,r,i,t?{pid:t.pid,role:t.role}:void 0)}throw r}}const bo=r(Symbol.for(`openclaw.stateDatabaseSchemaOwners`),()=>new yi);function getStateDatabaseSchemaLease(e){let t=bo.getStore()?.get(resolveStateOwnerIdentity(e).key);if(t&&!t.active)throw Error(`State schema maintenance scope is no longer current`);return t?.lease.assertCurrent(),t?.lease}function withStateDatabaseColdAdmission(e,t){let n=$n(e.busyTimeoutMs,`busyTimeoutMs`),r=performance.now()+n,a=i(e.databasePath),remainingBusyTimeoutMs=()=>Math.max(0,Math.ceil(r-performance.now())),o=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));for(;;)try{return assertStateDatabaseAccessAllowed(e.databasePath),t(remainingBusyTimeoutMs)}catch(t){if(!(t instanceof Rr)||i(t.databasePath)!==a||e.canRetry?.()===!1)throw t;let n=r-performance.now();if(n<=0)throw t;Atomics.wait(o,0,0,Math.min(10,n))}}function resolveGatewayStateOwnerPath(e){return resolveStateOwnerIdentity(e).ownerPath}function leaseForFile(e,t,n,r){let i=!1,holdsPhysicalLease=()=>verifyOwnerLock(n,t)&&(!r||r.verifyStillHeld());function run(e){a.assertCurrent(),ho.clear();let t=new Map(bo.getStore()),r={lease:a,active:!0};t.set(n.key,r);let leave=()=>{r.active=!1,ho.clear()};try{let n=bo.run(t,e);return Wn(n)?Promise.resolve(n).finally(leave):(leave(),n)}catch(e){throw leave(),e}}let a={path:e,assertCurrent(){if(i||!holdsPhysicalLease())throw Error(`OpenClaw state ownership is no longer current`)},assertDatabaseAccess(e){if(i||go.get(n.key)!==n||resolveStateOwnerIdentity(e).key!==n.key||!holdsPhysicalLease())throw Error(`OpenClaw state maintenance does not own this database`)},run,release(){ho.clear(),i||(r?.release(),t.release(),i=!0,n.locks.delete(t),r&&n.locks.delete(r),n.locks.size===0&&go.get(n.key)===n&&(n.heartbeat?.stop(),n.accepting=!1,go.delete(n.key))),n.locks.size===0&&removeCreatedProjectionDirectories(n.projectionDirectories)}};return a}function acquireStateDatabaseSchemaLease(e,t={}){ho.clear();let n=resolveStateOwnerIdentity(e),r=go.get(n.key),a=r?.path??n.ownerPath;if(r&&(!r.accepting||!hasPhysicalOwnership(r)))throw new Fr(e,r.lost.signal.reason);r&&assertStateDatabaseAccessAllowed(e);let o=r?.payload??{...defaultPayload(e),stateOwnerKind:`schema`},s,c=[];try{s=acquireGatewayStateOwnerFile(e,a,o,r?0:t.busyTimeoutMs??5e3,c)}catch(t){if(t instanceof Fr)try{assertStateDatabaseAccessAllowed(e)}catch(e){if(e instanceof Rr)throw e}throw t}let l=r?.projectionPath??Z.join(p(yr(i(e))),`gateway.state.lock`),u;try{u=r?.getProjection?.()?.retain()??acquireGatewayStateOwnerFile(e,l,{...o,role:o.role===`gateway`?`gateway`:`agent-embedded`},0,c)}catch(e){return Ln({release(){s.release(),removeCreatedProjectionDirectories(c)}},`state schema projection admission`,()=>{throw e})}r?(r.locks.add(s),r.locks.add(u),r.projectionDirectories.push(...c)):(r={key:n.key,path:a,kind:`schema`,payload:o,projectionPath:l,locks:/* @__PURE__ */ new Set([s,u]),projectionDirectories:c,lost:new AbortController,accepting:!0},go.set(r.key,r));let d=leaseForFile(a,s,r,u);try{let e=r.heartbeat??=startGatewayStateOwnerHeartbeat(r.locks,(e,t)=>observeOwnerLoss(r,e,t));return d.assertCurrent(),e.register(u),d}catch(e){return Ln(d,`state schema ownership verification`,()=>{throw e})}}function prepareStateDatabaseReadAccess(e){return captureAdmittedGatewayStateOwner(e,!1)}async function captureAdmittedGatewayStateOwner(e,t){e.assertCurrent();let n=e.identity.canonicalPath,r=process.platform===`win32`?Ke(n):n,i=go.get(r);if(!i||i.kind!==`process`)return;let a={canonicalPath:n,key:r,ownerPath:i.path},assertRegistered=()=>{if(e.assertCurrent(),i.lost.signal.throwIfAborted(),go.get(r)!==i)throw Pr()},assertCurrent=()=>{if(assertRegistered(),!i.accepting)throw Pr();assertStateDatabaseAccessAtOwnerPath(n,a,void 0)},o=createStateDatabaseAccess(a,i),assertReadAllowed=e=>{assertRegistered(),o.assertReadAllowed(e)},c=Z.resolve(e.databasePath),l=t?assertCurrent:assertRegistered;if(l(),t||ho.get(c)!==i){let t=await s(c);if(l(),(process.platform===`win32`?Ke(t):t)!==r)throw new Fr(e.databasePath)}return t||(assertReadAllowed(),ho.get(Z.resolve(n))===i&&ho.set(c,i)),{ownerId:i.payload.ownerId,role:i.payload.role??`gateway`,signal:i.lost.signal,assertCurrent,assertReadAllowed,prepareAccess:o.prepareAccess}}function assertStateDatabaseReadAllowed(e,t){assertStateDatabaseReadAtOwnerPath(e,t)}function assertStateDatabaseReadAtOwnerPath(e,t,n){if(go.size===0){assertStateDatabaseAccessAtOwnerPath(e,n??resolveStateOwnerIdentity(e),t);return}let r=Z.resolve(e);if(ho.get(r)?.accepting)return;let i=n??resolveStateOwnerIdentity(e),a=go.get(i.key),o=a?.payload.role??`gateway`;if(!a||a.kind!==`process`||!a.accepting||o!==`gateway`&&o!==`agent-embedded`)assertStateDatabaseAccessAtOwnerPath(e,i,t);else{if(!hasPhysicalOwnership(a))throw a.lost.signal.throwIfAborted(),Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);ho.set(r,a)}}function assertStateDatabaseAccessAllowed(e,t){assertStateDatabaseAccessAtOwnerPath(e,resolveStateOwnerIdentity(e),t)}async function captureStateDatabaseAccess(e){return createStateDatabaseAccess(await resolveStateOwnerIdentityAsync(e))}function createStateDatabaseAccess(e,t){let{canonicalPath:n}=e,r=go.get(e.key);return{canonicalPath:n,processOwner:r?.kind===`process`?{role:r.payload.role??`gateway`,signal:r.lost.signal,assertCurrent(){if(r.lost.signal.throwIfAborted(),!r.accepting||go.get(e.key)!==r)throw Pr()}}:void 0,prepareAccess:async r=>{let i=t??go.get(e.key),a=i?.payload.role??`gateway`;if(!i||i.kind!==`process`||!i.accepting||a!==`gateway`&&a!==`agent-embedded`)return assertStateDatabaseAccessAtOwnerPath(n,e,r),(t=r)=>{if(i&&go.get(e.key)!==i)throw Pr();assertStateDatabaseReadAtOwnerPath(n,t,e)};let o=i.heartbeat,s=i.locks.values().next().value,c=i.getProjection?.();if(!o||!s)throw Pr();let assertCurrent=(t=r)=>{if(i.lost.signal.throwIfAborted(),o.assertActive(),go.get(e.key)!==i||i.heartbeat!==o)throw Pr();if(!i.accepting)assertStateDatabaseAccessAtOwnerPath(n,e,t);else if(!i.locks.has(s)||i.getProjection?.()!==c)throw Pr()};assertCurrent();let l=[s.lockPath];c&&l.push(c.lockPath);let u=await o.verify(l).catch(e=>{throw i.lost.signal.throwIfAborted(),e});if(assertCurrent(),!u){let e=/* @__PURE__ */ Error(`${s.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`);throw loseOwner(i,e),e}return ho.set(Z.resolve(n),i),assertCurrent},assertReadAllowed(t){assertStateDatabaseReadAtOwnerPath(n,t,e)}}}function assertStateDatabaseAccessAtOwnerPath(e,t,n){let assertMaintenance=()=>{let t=n?n.schemaLease:getStateDatabaseSchemaLease(e);if(t){t.assertDatabaseAccess(e);return}let r=n?n.maintenanceScope:ur();if(!r)throw new Lr(e);r.assertDatabaseAccess(e)},r=go.get(t.key);if(r){if(!hasPhysicalOwnership(r))throw r.lost.signal.throwIfAborted(),Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);let t=r.payload.role??`gateway`;(!r.accepting||t!==`gateway`&&t!==`agent-embedded`)&&assertMaintenance()}else assertPersistedStateDatabaseAccessAllowed({databasePath:e,ownerPath:t.ownerPath,assertMaintenance})}async function backupNodeSqliteDatabase(e,t,n){let r=setInterval(()=>{},100);try{let r=await Un().backup(e,qn(t),{progress:n});return n?.({totalPages:r,remainingPages:0}),r}finally{clearInterval(r)}}async function root(e,t){return await root$1(e,t)}async function copySqliteFile(e,t,n,r){let i=await root(Z.dirname(e)),a=await root(Z.dirname(t)),o,copy=s=>a.copyIn(Z.basename(t),{relativePath:Z.basename(e),root:{stat:e=>i.stat(e),open:async(t,r)=>{let a=await i.open(t,r);try{if(!Be(n,await a.handle.stat({bigint:!0})))throw Error(`SQLite copy source changed: ${e}`);return a}catch(e){throw await a.handle.close(),e}}}},{clone:s,...r?{maxBytes:Number(n.size)}:{},sourceHardlinks:`allow`,overwrite:!1,mode:384,durable:!0,onDestinationPublished:e=>{o=e}});if(r)try{await copy(`always`)}catch(e){if(o||!(e instanceof I)||!(e.code===`unsupported-platform`||e.code===`helper-unavailable`&&e.message===`native file cloning is unavailable`))throw e;await r(Number(n.size)),await copy(`never`)}else await copy(`auto`);if(!o)throw Error(`SQLite copy was not published: ${t}`);return o}function createPrivateWindowsDirectory(e){let t=!1;try{createDirectorySync(Z.resolve(e),{private:!0,assertBeforeMutation(){t=!0}})}catch(e){throw!t||e instanceof I&&e.code===`already-exists`?ar(e):e}}function resolvePrivateSqliteSnapshotStagingRoot(e=process.env){try{return resolveSnapshotStagingRoot(e)}catch(e){throw e instanceof Error&&vr(e)?new Sr(`SQLite snapshot staging root is unavailable: ${e.message}; free disk space/quota`,{cause:e}):e}}function resolveSnapshotStagingRoot(e){let t=e.OPENCLAW_UPDATE_IN_PROGRESS===`1`?e.TMPDIR?.trim():void 0;if(t&&Z.isAbsolute(t))return c({preferredDir:Z.join(t,`openclaw`),tmpdir:()=>t});let n=process.platform===`win32`?e.LOCALAPPDATA?.trim():void 0,r=process.platform===`win32`?`AppData/Local`:`.cache`,i=process.platform===`darwin`?`Library/Caches`:r,a=[e.XDG_CACHE_HOME?.trim(),n].find(e=>e&&Z.isAbsolute(e))??Z.join(m(e),i);return c({preferredDir:Z.join(a,`openclaw`),tmpdir:()=>a})}function createPrivateSqliteTempDirectorySync(e,t){if(process.platform!==`win32`)try{return Q.mkdtempSync(Z.join(e,t))}catch(e){throw ar(e)}let n=Z.join(e,`${t}${oi()}`);return createPrivateWindowsDirectory(n),n}var SqliteSchemaMismatchError=class extends Error{constructor(...e){super(...e),this.name=`SqliteSchemaMismatchError`}};const xo={"missing-table":`missing table`,"missing-column":`column definitions differ for`,"unexpected-column":`column definitions differ for`,"column-definition-drift":`column definitions differ for`,"table-constraint-drift":`table constraints differ for`,"table-definition-drift":`table definition differs for`,"missing-or-drifted-index":`missing or drifted index`,"unexpected-unique-index":`unexpected unique index`,"missing-or-drifted-trigger":`missing or drifted trigger`,"missing-or-drifted-view":`missing or drifted view`,"unexpected-trigger":`unexpected trigger`,"virtual-table-definition-drift":`virtual table definition differs for`,"table-options-drift":`table options differ for`};function isColumnIssue(e){return e===`column-definition-drift`||e===`missing-column`||e===`unexpected-column`}function defaultIssueMessage(e,t){let n=isColumnIssue(e)?t.split(`.`,1)[0]:t;return`${xo[e]} ${n}`}function createSqliteSchemaIssue(e,t,n){return{code:e,objectName:t,message:n??defaultIssueMessage(e,t)}}function legacySqliteSchemaIssueMessages(e){let t=new Set(e.filter(e=>isColumnIssue(e.code)).map(e=>e.objectName.split(`.`,1)[0]));return[...new Set(e.filter(e=>e.code!==`table-constraint-drift`||!t.has(e.objectName)).map(e=>e.message))]}function throwSqliteSchemaMismatches(e,t){let n=t.slice(0,8);throw t.length>n.length&&n.push(`${t.length-n.length} additional mismatch(es)`),new SqliteSchemaMismatchError(`SQLite schema is incomplete or noncanonical for ${e}: ${n.join(`; `)}; run openclaw doctor --fix to repair it.`)}const So=/* @__PURE__ */ new WeakMap;function readCanonicalTableDefinition(e,t){if(!/^CREATE TABLE\b/iu.test(e)||Xr(e,/\bAS\b/giu))return;let n=Gn(e,t);return[...n.columns.values()].every(e=>{let t=Zr(e,0);return t?.keyword!==`CONSTRAINT`&&/^[a-z_][a-z0-9_]*$/u.test(t?.raw??``)})?n:void 0}function tableHasColumn(e,t,n){return readTableColumns(e,t).has(n)}function readTableColumns(e,t){if(Vn(e))return new Set(Jn(e)?.catalog.flatMap(e=>e.table===t&&e.kind===`column`&&e.value&&typeof e.value==`object`&&`name`in e.value&&typeof e.value.name==`string`?[e.value.name]:[])??[]);let n=Yn(e),r=n?.tableSql.get(t);if(n&&!r&&![...n.tables,...n.views].some(e=>e.toLowerCase()===t.toLowerCase()))return/* @__PURE__ */ new Set;if(n&&r){let e=So.get(n),i=e?.get(t);if(i)return i;let a=readCanonicalTableDefinition(r,t);if(a){let r=new Set(a.columns.keys());return e||(e=/* @__PURE__ */ new Map,So.set(n,e)),e.set(t,r),r}}let i=e.prepare(`PRAGMA table_info(${t})`).all();return new Set(i.flatMap(e=>typeof e.name==`string`?[e.name]:[]))}function classifySqliteTableReadError(e,t,n,r){if(Vn(e)||Rn(r)!==1)return r;try{let i=readTableColumns(e,t);if(i.size>0&&n.some(e=>!i.has(e)))return new SqliteSchemaMismatchError(`SQLite table ${t} is missing required columns; run openclaw doctor --fix to repair it.`,{cause:r})}catch{}return r}function tablePrimaryKeyColumns(e,t){if(Vn(e)){let n=Jn(e)?.catalog.find(e=>e.table===t&&e.kind===`primaryKey`)?.value;return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}let n=Yn(e)?.tableSql.get(t),r=n&&readCanonicalTableDefinition(n,t);if(r){let e=r.constraints.find(e=>{let t=Zr(e,0);return t&&ti(e,t)===`PRIMARY`});if(!e)return[...r.columns].flatMap(([e,t])=>Xr(t,/\bPRIMARY\s+KEY\b/giu)?[e]:[]);let t=Qr(e,`(`),n=Yr(e.slice(t+1,ei(e,t))).map(e=>$r(Zr(e,0)?.raw??``));if(n.every(e=>r.columns.has(e)))return[...new Set(n)]}return e.prepare(`PRAGMA table_info(${t})`).all().filter(e=>Number(e.pk??0)>0&&typeof e.name==`string`).toSorted((e,t)=>Number(e.pk??0)-Number(t.pk??0)).map(e=>e.name)}function tableExists(e,t){if(Vn(e))return Jn(e)?.catalog.some(e=>e.table===t&&e.kind===`table`)??!1;let n=Yn(e);return n?n.tables.has(t):Kn(e,`SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?`,[t],e=>e.get(t))?.ok===1}function ensureColumn(e,t,n){let r=n.trim().split(/\s+/,1)[0];return!r||!tableExists(e,t)||tableHasColumn(e,t,r)?!1:(e.exec(`ALTER TABLE ${t} ADD COLUMN ${n};`),!0)}const Co={name:`agent.schema-metadata`,lifetime:`process`,schemaDependent:!0,read(e){if(!(typeof e!=`object`||!e||!(`agentId`in e)||e.agentId!==null&&typeof e.agentId!=`string`||!(`role`in e)||e.role!==null&&typeof e.role!=`string`||!(`schemaVersion`in e)||e.schemaVersion!==null&&typeof e.schemaVersion!=`number`))return{agentId:e.agentId,role:e.role,schemaVersion:e.schemaVersion}}};function schemaMetadataKey(e){return{name:`agent.schema-metadata:${e}`,read:Co.read}}function publishAgentSchemaMetadata(e,t){tr(e,Co,t);let n=Yn(e);n&&tr(e,schemaMetadataKey(n.admissionId),t)}function readExistingAgentSchemaMeta(e){let t=Yn(e),r=t&&In(e,schemaMetadataKey(t.admissionId));if(r)return r;let i=!t||In(e,Xn)?.admissionId===t.admissionId?In(e,Co):void 0;if(i)return t&&tr(e,schemaMetadataKey(t.admissionId),i),i;if(!tableExists(e,`schema_meta`))return null;let a;try{a=e.prepare(`SELECT role, schema_version, agent_id FROM schema_meta WHERE meta_key = 'primary'`).get()}catch(t){throw classifySqliteTableReadError(e,`schema_meta`,[`meta_key`,`role`,`schema_version`,`agent_id`],t)}if(!a)return null;let o={agentId:n(a.agent_id),role:typeof a.role==`string`?a.role:null,schemaVersion:typeof a.schema_version==`number`?a.schema_version:null},s=t&&Yn(e)===t;return Vn(e)||s&&In(e,Xn)?.admissionId===t.admissionId?publishAgentSchemaMetadata(e,o):s&&tr(e,schemaMetadataKey(t.admissionId),o),o}function sqliteSnapshotSourceFileSize(e){try{let t=Q.statSync(e);return t.isFile()?t.size:0}catch(e){if(j(e,`ENOENT`))return 0;throw e}}function waitForSnapshotRetrySync(e){if(e+1>=10)return;let t=Math.min(80,10*2**e);t>0&&Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function finiteNonNegativeNumber(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function findExistingDiskSpacePath(e){let t=Z.resolve(e);for(;;)try{return Q.statSync(t).isDirectory()?t:Z.dirname(t)}catch{let e=Z.dirname(t);if(e===t)return null;t=e}}function tryReadDiskSpace(e){let t=findExistingDiskSpacePath(e);if(!t)return null;try{let n=Q.statfsSync(t),r=finiteNonNegativeNumber(n.bsize),i=finiteNonNegativeNumber(n.bavail);if(r===null||i===null)return null;let a=finiteNonNegativeNumber(n.blocks);return{targetPath:e,checkedPath:t,availableBytes:r*i,totalBytes:a===null?null:r*a}}catch{return null}}const wo=536870912;function sqliteSnapshotStagingParent(e){let t=Z.basename(e)===`openclaw`?Z.dirname(e):e;return rr(Z.basename(t))?t:void 0}function warnSqliteSnapshotReclamation(e,n){try{d({subsystem:`infra/sqlite-snapshot`}).warn({errorCode:t(n)},e)}catch{}}function acquireSqliteSnapshotReadToken(e){return Cr(e,`read`)}function reconcileSqliteSnapshotRetirement(e){if(!Q.lstatSync(e,{throwIfNoEntry:!1}))return;let t=sr(e,{cutoff:1/0});try{dr(t)}finally{t.release()}}function*reclaimAbandonedSqliteSnapshots(e,t=warnSqliteSnapshotReclamation){if(!sqliteSnapshotStagingParent(e))try{let n=0;for(let r of Q.readdirSync(e,{withFileTypes:!0})){if(n>=wo){t(`Stopped SQLite snapshot reclamation: byte budget exhausted for this pass.`);break}let i=or.test(r.name);if(!r.isDirectory()||!rr(r.name))continue;let a=Z.join(e,r.name),o;try{o=sr(a,{cutoff:Date.now()-(i?wr:9e5)});let{bytes:r}=o;if(n>0&&r>wo-n)throw Error(`Snapshot reclamation byte budget exhausted for this pass`);n+=r,dr(o);let s=Z.join(e,`${i?`openclaw-sqlite-readonly-${process.pid}-`:nr}${oi()}`);if(Q.renameSync(a,s),!br(s))throw Error(`Snapshot removal failed; check private cache permissions`);t(`Reclaimed ${r} bytes of interrupted SQLite snapshot data.`)}catch(e){t(`Skipped SQLite snapshot reclamation: ${ni(e)}`,e)}finally{try{o?.release()}catch(e){t(`SQLite snapshot token close failed; retaining native cleanup custody.`,e)}}yield}}catch(e){t(`SQLite snapshot reclamation failed; check private cache permissions.`,e)}}function sqliteSnapshotStagingError(e,t,n=!1,r){Fn(t,`snapshot`);let i=n,a=!1,o=!1,s;for(let n=0,r=t;n<8&&r instanceof Error;n+=1){o||=r instanceof AggregateError||r instanceof Hn;let{errcode:t,path:n}=r;a||=vr(r),(a||typeof t==`number`&&[13,778,1034,1290].includes(t)||`${n??``}${Z.sep}`.startsWith(`${e}${Z.sep}`))&&(i=!0,typeof t==`number`&&(s=t)),r=r.cause}if(!i)return t;let c=a?`free disk space/quota`:`check filesystem health and write permissions`,l=``;if(a&&r)try{let t=sqliteSnapshotSourceFileSize(r)+sqliteSnapshotSourceFileSize(`${r}-wal`)+sqliteSnapshotSourceFileSize(`${r}-journal`),n=tryReadDiskSpace(e)?.availableBytes,i=Q.existsSync(`${r}-wal`)&&Q.existsSync(`${r}-shm`);l=`; estimated ${t} bytes needed; ${n===void 0?`available bytes unknown`:`${n} bytes available`}; source ${i?`has live WAL sidecars`:`has no live WAL sidecars`}`}catch{}let u=process.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`?`TMPDIR`:`XDG_CACHE_HOME`,d=`${t instanceof Error?t.message:String(t)}${s===void 0?``:` (SQLite errcode=${s})`}; snapshot staging root ${n?e:Z.dirname(e)}${l}: ${c} or set ${u} to a writable filesystem`,f=a&&!o&&Qn(t)!==`source`?new Sr(d,{cause:t}):Error(d,{cause:t});return ir(t)?ar(f):f}async function createSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1,n,r=!1){n?.throwIfAborted();try{return await allocateSqliteSnapshotStagingDirectory(e,t,n,r)}catch(e){throw e instanceof Hn||r&&e instanceof AggregateError||(n?.throwIfAborted(),Fn(e,`snapshot`)),e}}async function allocateSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1,n,r=!1){if(n?.throwIfAborted(),r){let r=new AbortController;return hr((async()=>{let{allocateWorkerOwnedSqliteSnapshotDirectory:i}=await import(`./sqlite-readonly-sqlite-snapshot-staging-allocation-Cr130_yR.mjs`);n?.throwIfAborted(),r.signal.throwIfAborted();let a=await i(e,t,n?AbortSignal.any([n,r.signal]):r.signal);if(mr(a.directory),n?.aborted||r.signal.aborted){if(!await _r(a.directory))throw new Hn(`SQLite snapshot cleanup failed: ${a.directory}`);n?.throwIfAborted(),r.signal.throwIfAborted()}return a.directory})(),()=>r.abort(/* @__PURE__ */ Error(`SQLite snapshot allocation stopped`)))}return createSqliteSnapshotStagingDirectorySync(e,t)}function createSqliteSnapshotStagingDirectorySync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1){let n=createSqliteSnapshotStagingTokenSync(e,t);return mr(n.directory,n.release),n.directory}function createSqliteSnapshotStagingTokenSync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1){let n;try{try{n=createPrivateSqliteTempDirectorySync(e,t?`openclaw-sqlite-readonly-${process.pid}-`:nr)}catch(t){throw sqliteSnapshotStagingError(e,t,!0)}return{directory:n,release:Cr(n,`create`)}}catch(e){throw n&&br(n),e}}function readUint32(e,t,n){return n===`LE`?e.readUInt32LE(t):e.readUInt32BE(t)}function sqliteWalChecksum(e,t,n=[0,0]){let[r,i]=n;for(let n=0;n<e.length;n+=8)r=r+readUint32(e,n,t)+i>>>0,i=i+readUint32(e,n+4,t)+r>>>0;return[r,i]}const To=1048576;function readWalGeneration(e){let t=Buffer.alloc(32);if(Mn(e,t,0)!==t.length)return;let n=t.readUInt32BE(0);if(n!==931071618&&n!==931071619)return;let r=n===931071618?`LE`:`BE`,i=t.readUInt32BE(8),[a,o]=sqliteWalChecksum(t.subarray(0,24),r);if(!(i<512||i>65536||i&i-1||t.readUInt32BE(24)!==a||t.readUInt32BE(28)!==o))return{header:t,byteOrder:r,frameBytes:24+i}}function copyCommittedWalFrames(e,t,n,r){let{header:i,byteOrder:a,frameBytes:o}=n;if(readWalGeneration(e)?.header.equals(i)!==!0)return!1;let s=i.subarray(16,24),c=[i.readUInt32BE(24),i.readUInt32BE(28)];writeFully(t,i,0);let l=32,u=Math.max(1,Math.floor(To/o)),d=Buffer.allocUnsafe(u*o);for(let n=32;n<r;){let i=d.subarray(0,Math.min(d.length,r-n)),u=Mn(e,i,n),f=0,p=!0;for(let e=0;e+o<=u;e+=o){let t=i.subarray(e,e+o);if(t.readUInt32BE(0)===0||!t.subarray(8,16).equals(s)){p=!1;break}let r=sqliteWalChecksum(t.subarray(24),a,sqliteWalChecksum(t.subarray(0,8),a,c));if(t.readUInt32BE(16)!==r[0]||t.readUInt32BE(20)!==r[1]){p=!1;break}c=r,f=e+o,t.readUInt32BE(4)!==0&&(l=n+f)}if(f>0&&writeFully(t,i.subarray(0,f),n),!p||f<i.length)break;n+=f}return Q.ftruncateSync(t,l),Q.fsyncSync(t),l}function writeFully(e,t,n){for(let r=0;r<t.length;){let i=Q.writeSync(e,t,r,t.length-r,n+r);if(i<=0)throw Error(`SQLite WAL snapshot write made no progress`);r+=i}}function matchesCapturedWalPrefix(e,t,n){let r=Q.openSync(t,`r`);try{let t=Q.fstatSync(r);if(!t.isFile()||t.size!==n)return!1;let i=Buffer.allocUnsafe(Math.min(To,n)),a=Buffer.allocUnsafe(i.length);for(let t=0;t<n;t+=i.length){let o=Math.min(i.length,n-t),s=i.subarray(0,o),c=a.subarray(0,o);if(Mn(e,s,t)!==o||Mn(r,c,t)!==o||!s.equals(c))return!1}return!0}finally{Q.closeSync(r)}}function prepareSqliteWalPrefixCopy(e,t,n){let r=readWalGeneration(e);if(r)return()=>{let i=Q.fstatSync(e).size;if(!Number.isSafeInteger(i)||i<32)return!1;let a=Q.openSync(t,`wx`,384),o;try{o=copyCommittedWalFrames(e,a,r,i)}finally{Q.closeSync(a)}return o!==!1&&n()&&matchesCapturedWalPrefix(e,t,o)&&readWalGeneration(e)?.header.equals(r.header)===!0}}const Eo=/* @__PURE__ */ new Set;function withSqliteSourceReadDatabase(e,t,n,r={}){assertStateDatabaseAccessAllowed(e);let i=Bn(t,()=>er(r.readOnlyShm?Zn(e):e,{readOnly:!0,timeout:r.timeout}));try{return assertStateDatabaseAccessAllowed(e),n(i)}finally{try{i.close()}finally{i.isOpen&&Eo.add(i)}}}const Do=Buffer.from([217,213,5,249,32,161,99,215]);var SqliteSourceChangedError=class extends Error{constructor(e,t){super(t?.attempts?`SQLite source did not stabilize (reason=${e}, attempts=${t.attempts}) after ${t.attempts} read-only inspection attempts. Wait a moment for write activity to settle, then retry the inspection`:`SQLite source changed during read-only inspection (reason=${e})`,t),this.reason=e}};function statIfPresent(e){try{return Q.statSync(e,{bigint:!0})}catch(e){if(e.code===`ENOENT`)return;throw e}}function readSourceSidecars(e){return{journal:!!statIfPresent(`${e}-journal`),shm:!!statIfPresent(`${e}-shm`),wal:!!statIfPresent(`${e}-wal`)}}function openPinnedFile(e,t){let n;try{n=Q.openSync(e,`r`)}catch(e){throw e.code===`ENOENT`?new SqliteSourceChangedError(`source-disappeared`):e}try{let r=Q.fstatSync(n,{bigint:!0});t&&zn(r,t);let i=statIfPresent(e);if(!r.isFile()||!i?.isFile()||!Be(r,i))throw new SqliteSourceChangedError(`source-identity-changed`);return{descriptor:n,identity:r,pathname:e}}catch(e){throw Q.closeSync(n),e}}function readSourceJournalMode(e,t){let n=openPinnedFile(e,t);try{let e=Buffer.alloc(20),t=Q.readSync(n.descriptor,e,0,e.length,0);return assertPinnedIdentityUnchanged(n),t===0?`empty`:t!==e.length||e.subarray(0,16).toString(`utf8`)!==`SQLite format 3\0`?`unknown`:e[18]===2||e[19]===2?`wal`:`rollback`}finally{Q.closeSync(n.descriptor)}}function assertPinnedIdentityUnchanged(e){let t=Q.fstatSync(e.descriptor,{bigint:!0}),n=statIfPresent(e.pathname);if(!t.isFile()||!n?.isFile()||!Be(e.identity,t)||!Be(e.identity,n))throw new SqliteSourceChangedError(`source-identity-changed`)}function copySourceFile(e,n,r){let i=openPinnedFile(e,r);try{let r;try{r=Q.realpathSync.native(e)}catch(e){throw t(e)===`ENOENT`?new SqliteSourceChangedError(`source-disappeared`,{cause:e}):e}let a=copyRootFileSync({source:{rootPath:Z.dirname(r),absolutePath:r},destination:{rootPath:Z.dirname(n),absolutePath:n},expectedSourceIdentity:i.identity,sourceHardlinks:`allow`,clone:`auto`,mode:384});try{Q.fsyncSync(a.fd),assertPinnedIdentityUnchanged(i)}finally{a.close()}}finally{Q.closeSync(i.descriptor)}}function sourceMatchesCopy(e,t,n){let r=openPinnedFile(e,n);try{let e=Q.openSync(t,`r`);try{if(!Q.fstatSync(e).isFile())return!1;let t=sameFileContentsSync(r.descriptor,e);return assertPinnedIdentityUnchanged(r),t}finally{Q.closeSync(e)}}finally{Q.closeSync(r.descriptor)}}function assertExpectedSidecars(e,t){let n=readSourceSidecars(e);if(n.journal!==t.journal||n.wal!==t.wal)throw new SqliteSourceChangedError(`journal-state-changed`)}function isSqliteReadOnlyError(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e+=1){let e=t;if(typeof e.errcode==`number`&&(e.errcode&255)==8)return!0;t=e.cause}return!1}function rollbackJournalReferencesSuperJournal(e){let t=Q.openSync(e,`r`);try{let e=Q.fstatSync(t).size;if(e<16)return!1;let n=Buffer.allocUnsafe(16);if(Q.readSync(t,n,0,n.length,e-n.length)!==n.length)return!1;let r=n.readUInt32BE(0);return r>0&&r<=e-20&&n.subarray(8).equals(Do)}finally{Q.closeSync(t)}}function syncPrivateSnapshot(e){let t=Q.openSync(e,`r+`);try{Q.fsyncSync(t)}finally{Q.closeSync(t)}}function recoverPrivateJournalCopy(e){if(rollbackJournalReferencesSuperJournal(`${e}-journal`))throw Error(`SQLite hot rollback journal references a super-journal and cannot be recovered privately: ${e}`);let t=er(e);try{t.exec(`PRAGMA busy_timeout = 30000; PRAGMA trusted_schema = OFF;`),t.prepare(`PRAGMA schema_version;`).get()}finally{t.close()}Q.rmSync(`${e}-journal`,{force:!0}),syncPrivateSnapshot(e)}function*createStableReadOnlyCopyInTempDirectory(e,t,n,r=n?Z.dirname(n):resolvePrivateSqliteSnapshotStagingRoot(),i,a){let o=n;try{o??=createSqliteSnapshotStagingDirectorySync(r);let n=Z.join(o,`database.sqlite.partial`),s=Z.join(o,`first`);if(process.platform!==`win32`&&Q.chmodSync(o,448),readSourceJournalMode(e,i)!==t)throw new SqliteSourceChangedError(`journal-mode-changed`);let c=readSourceSidecars(e),l=!1;if(t===`wal`&&c.wal&&!c.journal){let t=openPinnedFile(`${e}-wal`);try{let r=prepareSqliteWalPrefixCopy(t.descriptor,`${n}-wal`,()=>sourceMatchesCopy(e,n,i));r&&(yield{sourcePath:e,targetPath:n,expectedSourceIdentity:i});let a=r?.();if(assertPinnedIdentityUnchanged(t),a===!1)throw new SqliteSourceChangedError(`wal-copy-unstable`);l=a===!0}finally{Q.closeSync(t.descriptor)}}let u=[...c.journal?[`-journal`]:[],...c.wal?[`-wal`]:[]];if(l)assertExpectedSidecars(e,c);else if(u.length>0){for(let t of u)yield{sourcePath:`${e}${t}`,targetPath:`${n}${t}`};if(yield{sourcePath:e,targetPath:n,expectedSourceIdentity:i},!sourceMatchesCopy(e,n,i))throw new SqliteSourceChangedError(`main-changed-during-copy`);for(let t of u)if(!sourceMatchesCopy(`${e}${t}`,`${n}${t}`))throw new SqliteSourceChangedError(t===`-wal`?`wal-changed-during-copy`:`rollback-journal-changed-during-copy`);assertExpectedSidecars(e,c)}else{yield{sourcePath:e,targetPath:s,expectedSourceIdentity:i},assertExpectedSidecars(e,c);let t=a!==void 0||sourceMatchesCopy(e,s,i);if(assertExpectedSidecars(e,c),!t)throw new SqliteSourceChangedError(`main-changed-during-copy`);Q.rmSync(n,{force:!0}),Q.renameSync(s,n)}if(readSourceJournalMode(e,i)!==t)throw new SqliteSourceChangedError(`journal-mode-changed`);if(a&&(c.journal||c.wal&&Q.statSync(`${n}-wal`).size!==0))throw new SqliteSourceChangedError(`recovery-data-appeared`);return c.journal&&recoverPrivateJournalCopy(n),gr(o,a)}catch(t){let r=o?sqliteSnapshotStagingError(o,t,!1,e):t;if(o&&n===void 0){let e=[r];if(!br(o,t=>e.push(t)))throw pr(e,`SQLite snapshot preparation`)}throw r}}function copyPreparedLocationSync(e){let t=e.next();for(;!t.done;){try{let{sourcePath:e,targetPath:n,expectedSourceIdentity:r}=t.value;copySourceFile(e,n,r)}catch(n){t=e.throw(n);continue}t=e.next()}return t.value}async function copyPreparedLocation(e){let t=e.next();for(;!t.done;){try{let{sourcePath:e,targetPath:n,expectedSourceIdentity:r}=t.value,i=openPinnedFile(e,r);try{await copySqliteFile(e,n,i.identity)}finally{try{assertPinnedIdentityUnchanged(i)}finally{Q.closeSync(i.descriptor)}}}catch(n){t=e.throw(n);continue}t=e.next()}return t.value}async function createStableReadOnlyCopy(e,t,n,r){let i=typeof n==`object`?n.directory:await createSqliteSnapshotStagingDirectory(n,!1,r);try{return await copyPreparedLocation(createStableReadOnlyCopyInTempDirectory(e,t,i))}catch(e){return fr(i,e,`SQLite snapshot preparation`,typeof n==`object`)}}async function createOnlineReadOnlyBackup(e,t,n,r){let i=typeof t==`object`?t.directory:await createSqliteSnapshotStagingDirectory(t,!1,n),a=Z.join(i,`database.sqlite.partial`);try{process.platform!==`win32`&&Q.chmodSync(i,448);let t=Bn(`source`,()=>er(e,{readOnly:!0}));try{t.exec(`PRAGMA busy_timeout = 30000; PRAGMA trusted_schema = OFF; BEGIN;`),t.prepare(`PRAGMA schema_version;`).get(),await hr(backupNodeSqliteDatabase(t,a,r)),t.exec(`ROLLBACK;`)}finally{t.isOpen&&t.close()}let n=er(a);try{n.exec(`PRAGMA journal_mode = DELETE;`)}finally{n.close()}return syncPrivateSnapshot(a),gr(i)}catch(n){let r=sqliteSnapshotStagingError(i,n,!1,e);return fr(i,r,`SQLite online backup`,typeof t==`object`)}}async function prepareReadOnlySourceInProcess(e,t,n,r){n?.throwIfAborted();let i=Q.realpathSync.native(e);for(let e=0;;e+=1){n?.throwIfAborted();try{let e=readSourceJournalMode(i),a=readSourceSidecars(i);if(e===`empty`||e===`wal`&&(!a.wal||!a.shm))return await createStableReadOnlyCopy(i,e,t,n);try{return await createOnlineReadOnlyBackup(i,t,n,r)}catch(e){if(n?.throwIfAborted(),e instanceof AggregateError||!isSqliteReadOnlyError(e)||readSourceJournalMode(i)!==`rollback`||!readSourceSidecars(i).journal)throw e;return await createStableReadOnlyCopy(i,`rollback`,t,n)}}catch(t){if(!(t instanceof SqliteSourceChangedError)||e+1>=10)throw t}}}function*prepareArtifactPreservingCopy(e,t,n,r){let i=Q.realpathSync.native(e);for(let e=0;;e+=1)try{return yield*createStableReadOnlyCopyInTempDirectory(i,readSourceJournalMode(i,n),typeof t==`object`?t.directory:void 0,typeof t==`string`?t:void 0,n,r)}catch(n){if(typeof t==`object`&&xr(t.directory,n),!(n instanceof SqliteSourceChangedError))throw n;if(e+1>=10)throw new SqliteSourceChangedError(n.reason,{cause:n,attempts:10});waitForSnapshotRetrySync(e)}}function prepareSqliteReadOnlyLocationSyncInProcess(e,t,n,r){return copyPreparedLocationSync(prepareArtifactPreservingCopy(e,t,n,r))}const Oo=/* @__PURE__ */ new Set([`wal-copy-unstable`,`main-changed-during-copy`,`wal-changed-during-copy`]);async function prepareSqliteReadOnlyCopyInProcess(e,t,n){try{return await copyPreparedLocation(prepareArtifactPreservingCopy(e,t,n))}catch(r){if(!(r instanceof SqliteSourceChangedError)||!Oo.has(r.reason))throw r;let i=Q.realpathSync.native(e),a=openPinnedFile(i,n);try{let e=readSourceSidecars(i);if(readSourceJournalMode(i,n)!==`wal`||!e.wal||!e.shm||e.journal)throw r;let o=await createOnlineReadOnlyBackup(i,t);try{assertPinnedIdentityUnchanged(a)}catch(e){throw o.cleanup(),e}return o}finally{Q.closeSync(a.descriptor)}}}function prepareSqliteReadOnlyLocationInProcess(e,t,n,r){return n?.throwIfAborted(),prepareReadOnlySourceInProcess(e,t,n,r)}async function prepareSqliteReadOnlyLocationFromOwnedDatabase(e,t,n,r){let assertReady=()=>{if(n?.throwIfAborted(),t(),!e.isOpen||e.isTransaction)throw Error(`SQLite inspection requires an open owner outside a transaction`)};assertReady();let i=await createSqliteSnapshotStagingDirectory(void 0,!1,n,r===`async`);try{assertReady();let r=Z.join(i,`database.sqlite.partial`);return await hr(backupNodeSqliteDatabase(e,r)),n?.throwIfAborted(),t(),gr(i)}catch(e){let t=[e];throw!await _r(i,e=>t.push(e))&&r===`async`?pr(t,`Owned SQLite snapshot preparation`):e}}export{throwSqliteSchemaMismatches as A,withStateDatabaseColdAdmission as B,readTableColumns as C,SqliteSchemaMismatchError as D,tablePrimaryKeyColumns as E,assertStateDatabaseReadAllowed as F,Ja as G,sha256Hex as H,captureStateDatabaseAccess as I,syncDirectorySync as J,classifyGatewayOwnerProcessNamespace as K,getStateDatabaseSchemaLease as L,resolvePrivateSqliteSnapshotStagingRoot as M,acquireStateDatabaseSchemaLease as N,createSqliteSchemaIssue as O,assertStateDatabaseAccessAllowed as P,prepareStateDatabaseReadAccess as R,ensureColumn as S,tableHasColumn as T,GatewayLockNamespaceError as U,applyPrivateModeSync as V,Ya as W,createFileSync as X,createDirectorySync as Y,reconcileSqliteSnapshotRetirement as _,prepareSqliteReadOnlyCopyInProcess as a,readExistingAgentSchemaMeta as b,prepareSqliteReadOnlyLocationSyncInProcess as c,withSqliteSourceReadDatabase as d,acquireSqliteSnapshotReadToken as f,reclaimAbandonedSqliteSnapshots as g,createSqliteSnapshotStagingTokenSync as h,isSqliteReadOnlyError as i,createPrivateSqliteTempDirectorySync as j,legacySqliteSchemaIssueMessages as k,readSourceJournalMode as l,createSqliteSnapshotStagingDirectorySync as m,copySourceFile as n,prepareSqliteReadOnlyLocationFromOwnedDatabase as o,createSqliteSnapshotStagingDirectory as p,parseGatewayLockPayload as q,createOnlineReadOnlyBackup as r,prepareSqliteReadOnlyLocationInProcess as s,SqliteSourceChangedError as t,readSourceSidecars as u,Co as v,tableExists as w,classifySqliteTableReadError as x,publishAgentSchemaMetadata as y,resolveGatewayStateOwnerPath as z};