@inkeep/open-knowledge 0.0.0-dev-20260428211426 → 0.0.0-dev-20260429160105
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD_PARTY_NOTICES.md +15 -0
- package/dist/cli.mjs +284 -281
- package/dist/constants-DLhaxFjM.mjs +2 -0
- package/dist/{dist-CXdg7KnM.mjs → dist-CIeZOXfv.mjs} +22 -19
- package/dist/{dist-Ct-gJ7iD.mjs → dist-CNDKfHI8.mjs} +1 -1
- package/dist/{dist-0qFIeeXA.mjs → dist-DD_wEI4a.mjs} +15 -15
- package/dist/index.mjs +1 -1
- package/dist/{init-D0YdyLe_.mjs → init-2ZbpRqT6.mjs} +4 -4
- package/dist/init-Cy-4UOwQ.mjs +1 -0
- package/dist/{init-CMkePWjl.mjs → init-DWGTb8QS.mjs} +22 -7
- package/dist/init-DWvyb5i4.mjs +1 -0
- package/dist/{loader-BJU3jneI.mjs → loader-B73SzGQk.mjs} +2 -2
- package/dist/loader-Ce28eAYb.mjs +1 -0
- package/dist/paths-CcD8Nh_5.mjs +1 -0
- package/dist/paths-DqWCeGWM.mjs +2 -0
- package/dist/{preview-CXP9kBv6.mjs → preview-DRDic3pF.mjs} +2 -2
- package/dist/preview-DT0ltjSs.mjs +1 -0
- package/dist/public/assets/ActivityModeContent-spvhVGSd.js +2 -0
- package/dist/public/assets/DocumentContext-Xq_dn8Vf.js +33 -0
- package/dist/public/assets/GraphPanel-C36W-gM6.js +46 -0
- package/dist/public/assets/McpConsentDialogBody-CDOor7qb.js +1 -0
- package/dist/public/assets/SourceEditor-BeRKaESA.js +2 -0
- package/dist/public/assets/{agent-presence-BXsx4eTl.js → agent-presence-XtMgnv3n.js} +1 -1
- package/dist/public/assets/clipboard-0XbokP0-.js +5 -0
- package/dist/public/assets/{dialog-CtSN0d2b.js → dialog-B7UAZUVJ.js} +1 -1
- package/dist/public/assets/{dist-DeDgmJv2.js → dist-5Xm_mb8k.js} +1 -1
- package/dist/public/assets/{dist-GlH2KPqY.js → dist-BkmmA9Kx.js} +1 -1
- package/dist/public/assets/{dist-BqO6NfD-.js → dist-CBfh7n1S.js} +1 -1
- package/dist/public/assets/{dist-DR1MrLJC.js → dist-DUCdsXly.js} +1 -1
- package/dist/public/assets/{dist-DlS42TIP.js → dist-DxKDMu0r.js} +1 -1
- package/dist/public/assets/{dist-D2wwoXzm.js → dist-gwU6yV0l.js} +1 -1
- package/dist/public/assets/index-DmSa5KwJ.js +1843 -0
- package/dist/public/assets/index-ldPPE8aY.css +1 -0
- package/dist/public/assets/{panel-BCRdtBla.js → panel-DiSt1efw.js} +1 -1
- package/dist/public/assets/target-navigation-intent-DlP83APM.js +1 -0
- package/dist/public/assets/toggle-group-Cg6YuFV4.js +281 -0
- package/dist/public/assets/tooltip-BaQG219g.js +1 -0
- package/dist/public/index.html +14 -14
- package/dist/src-CCUnFptH.mjs +1 -0
- package/dist/start-BaIxHOku.mjs +1 -0
- package/dist/start-nj1M3dB_.mjs +2 -0
- package/package.json +1 -1
- package/dist/constants-DCJlLBSi.mjs +0 -2
- package/dist/init-D-5Gc0uq.mjs +0 -1
- package/dist/init-DUA_XKK1.mjs +0 -1
- package/dist/loader-1GTY76cQ.mjs +0 -1
- package/dist/paths-CNpYe27Q.mjs +0 -2
- package/dist/paths-fx16Ahvg.mjs +0 -1
- package/dist/preview-CHvLSbhb.mjs +0 -1
- package/dist/public/assets/ActivityModeContent-Ccu_n0bV.js +0 -2
- package/dist/public/assets/DocumentContext-C1msvcHp.js +0 -5
- package/dist/public/assets/GraphPanel-CJ_U3W3L.js +0 -46
- package/dist/public/assets/McpConsentDialogBody-Csjet19t.js +0 -1
- package/dist/public/assets/PageListContext-B5SWnlyE.js +0 -278
- package/dist/public/assets/SourceEditor-OFesfBB2.js +0 -3
- package/dist/public/assets/clipboard-DAcKCHl1.js +0 -32
- package/dist/public/assets/index-CwFTGDhe.js +0 -1843
- package/dist/public/assets/index-DjR45Lon.css +0 -1
- package/dist/public/assets/toggle-group-LDOO6zaV.js +0 -1
- package/dist/public/assets/tooltip-D0MnQ7ZX.js +0 -1
- package/dist/src-BIqAAP5m.mjs +0 -1
- package/dist/start-BOjBm-nL.mjs +0 -2
- package/dist/start-CZFHRjtT.mjs +0 -1
- /package/dist/public/assets/{button-BPXuMr5W.js → button-CXhPNzpp.js} +0 -0
- /package/dist/public/assets/{dist-CgLbXgrr.js → dist-Bgq0sPT8.js} +0 -0
package/dist/cli.mjs
CHANGED
|
@@ -1,42 +1,45 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{t as r}from"./esm-wByiX8MO.mjs";import{t as i}from"./dist-BCyi1oM7.mjs";import{n as a,r as o,t as s}from"./dist-bundle-BSdjl7Rj.mjs";import{i as c,r as l}from"./constants-
|
|
3
|
-
`),new
|
|
4
|
-
`),new
|
|
5
|
-
`)){let e=n.trim();if(e===``)continue;let r=e.indexOf(`=`);r!==-1&&(t[e.slice(0,r)]=e.slice(r+1))}return t}function dr(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function fr(e){let t=new r(`git-credential`);return t.description(`Git credential helper (git credential-helper protocol)`),t.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await lr(process.stdin,process.stdout,t);process.exit(n)}),t}function pr(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function mr(e,t,n){let r={baseUrl:pr(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new a(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function hr(e){let t=e.request||s,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),mr(t,`POST /login/device/code`,n)}async function gr(e){let t=await mr(e.request||s,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=_r(e,t.data.expires_in),n.refreshTokenExpiresAt=_r(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function _r(e,t){return new Date(e+t*1e3).toISOString()}async function vr(e,t){let n=yr(e,t.auth);if(n)return n;let{data:r}=await hr({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await xr(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function yr(e,t){if(t.refresh===!0||!e.authentication)return!1;if(e.clientType===`github-app`)return e.authentication;let n=e.authentication;return(`scopes`in t&&t.scopes||e.scopes).join(` `)===n.scopes.join(` `)?n:!1}async function br(e){await new Promise(t=>setTimeout(t,e*1e3))}async function xr(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await gr({...i,clientType:`oauth-app`}):await gr({...i,clientType:`github-app`});return{type:`token`,tokenType:`oauth`,...a}}catch(i){if(!i.response)throw i;let a=i.response.data.error;if(a===`authorization_pending`)return await br(r.interval),xr(e,t,n,r);if(a===`slow_down`)return await br(r.interval+7),xr(e,t,n,r);throw i}}async function Sr(e,t){return vr(e,{auth:t})}async function Cr(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);let{token:a}=await vr(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var wr=`0.0.0-development`;function Tr(e){let t=e.request||s.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${wr} ${o()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(Sr.bind(null,i),{hook:Cr.bind(null,i)})}async function Er(e){let{clientId:t,scopes:n=[`repo`,`read:user`,`user:email`],onVerification:r,host:i}=e,a=i&&i!==`github.com`?`https://${i}/api/v3`:`https://api.github.com`,o=Tr({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`./dist-bundle-BmF5_Mcp.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}function Dr(e){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??e?.github?.oauthAppClientId??`Ov23liqlSd0V1MwR6rhI`}const Or=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function kr(e){let t=e.toLowerCase().replace(/:\d+$/,``);Or.has(t)&&(process.stderr.write(`Error: ${e} is not a GitHub host. Only GitHub and GitHub Enterprise Server are supported.\n`),process.exit(1))}function Ar(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function jr(e,t,n,r=Er){let i=Dr(n),{host:a,json:o}=e;kr(a),o||process.stderr.write(`Logging in to ${a}…\n`);let s=await r({clientId:i,host:a===`github.com`?void 0:a,onVerification:e=>{e.userCode,e.verificationUri,o?Ar(!0,{type:`verification`,user_code:e.userCode,verification_uri:e.verificationUri,expires_in:e.expiresIn}):process.stderr.write(`Open: ${e.verificationUri}\nEnter code: ${e.userCode}\n`)}}),c=`unknown`,l,u;try{let e=a===`github.com`?`https://api.github.com`:`https://${a}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${s.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();c=e.login??c,l=e.name??void 0,u=e.email??void 0}}catch{}await t.set(a,c,s.token,{gitProtocol:`https`,name:l,email:u}),o?Ar(!0,{type:`complete`,host:a,login:c}):process.stderr.write(`✓ Logged in as ${c} on ${a}\n`)}function Mr(e,t){return new r(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSONL progress events`,!1).action(async n=>{await jr(n,await t(),e())})}const Nr=e=>e.name===`enter`||e.name===`return`;var Pr=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Fr=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Ir=class extends Error{name=`ExitPromptError`},Lr=class extends Error{name=`HookError`},Rr=class extends Error{name=`ValidationError`};const zr=new Hn;function Br(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Vr(e,t){let n=Br(e);return zr.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function Hr(){let e=zr.getStore();if(!e)throw new Lr(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function Ur(){return Hr().rl}function Wr(e){return Un.bind((...t)=>{let n=Hr(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function Gr(e){let t=Hr(),{index:n}=t,r=e({get(){return t.hooks[n]},set(e){t.hooks[n]=e},initialized:n in t.hooks});return t.index++,r}function Kr(){Hr().handleChange()}const qr={queue(e){let t=Hr(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(Ur());if(r!=null&&typeof r!=`function`)throw new Rr(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=Hr();Wr(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=Hr();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function Jr(e){return typeof e==`function`}function Yr(e){return Gr(t=>{let n=Un.bind(function(e){t.get()!==e&&(t.set(e),Kr())});if(t.initialized)return[t.get(),n];let r=Jr(e)?e():e;return t.set(r),[r,n]})}function Xr(e,t){Gr(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&qr.queue(e),n.set(t)})}function Zr(){return Rn.platform.startsWith(`win`)?!!Rn.env.CI||!!Rn.env.WT_SESSION||!!Rn.env.TERMINUS_SUBLIME||Rn.env.ConEmuTask===`{cmd::Cmder}`||Rn.env.TERM_PROGRAM===`Terminus-Sublime`||Rn.env.TERM_PROGRAM===`vscode`||Rn.env.TERM===`xterm-256color`||Rn.env.TERM===`alacritty`||Rn.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:Rn.env.TERM!==`linux`}const Qr={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},$r={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},ei={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},ti={...Qr,...$r},ni={...Qr,...ei},ri=Zr()?ti:ni;Object.entries($r);const ii={prefix:{idle:Gn(`blue`,`?`),done:Gn(`green`,ri.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>Gn(`yellow`,e))},style:{answer:e=>Gn(`cyan`,e),message:e=>Gn(`bold`,e),error:e=>Gn(`red`,`> ${e}`),defaultAnswer:e=>Gn(`dim`,`(${e})`),help:e=>Gn(`dim`,e),highlight:e=>Gn(`cyan`,e),key:e=>Gn(`cyan`,Gn(`bold`,`<${e}>`))}};function ai(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function oi(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=ai(n)&&ai(r)?oi(n,r):r}return t}function si(...e){return oi(ii,...e.filter(e=>e!=null))}function ci({status:e=`idle`,theme:t}){let[n,r]=Yr(!1),[i,a]=Yr(0),{prefix:o,spinner:s}=si(t);return Xr(()=>{if(e===`loading`){let e,t=-1,n=setTimeout(()=>{r(!0),e=setInterval(()=>{t+=1,a(t%s.frames.length)},s.interval)},300);return()=>{clearTimeout(n),clearInterval(e)}}else r(!1)},[e]),n?s.frames[i]:typeof o==`string`?o:o[e===`loading`?`idle`:e]??o.idle}function li(e){return Yr({current:e})[0]}function ui(e){let t=li(e);t.current=e,Xr(e=>{let n=!1,r=Wr((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var di=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const fi=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),pi=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,mi=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,hi=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,gi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,_i=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,vi=/\t{1,1000}/y,yi=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,bi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,xi=/\p{M}+/gu,Si={limit:1/0,ellipsis:``},Ci=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Ci(i,Si,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[bi,l],[hi,0],[gi,o],[vi,s],[yi,c],[_i,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(xi,``)){let t=e.codePointAt(0)||0;if(S=pi(t)?2:mi(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===_i?fi(e.slice(p,n.lastIndex)):n===yi?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},wi={limit:1/0,ellipsis:``,ellipsisWidth:0},Ti=(e,t={})=>Ci(e,wi,t).width,Ei=`]8;;`,Di=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ei}(?<uri>.*))`,`y`),Oi=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},ki=e=>`[${e}m`,Ai=e=>`${Ei}${e}`,ji=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:Ti(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=Ti(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(Ei,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Mi=e=>{let t=e.split(` `),n=t.length;for(;n&&!Ti(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ni=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=Ti(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=Ti(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),ji(s,r,t),c=Ti(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){ji(s,r,t),c=Ti(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){ji(s,r,t),c=Ti(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Mi(e)));let l=s.join(`
|
|
6
|
-
`),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===``){
|
|
7
|
-
`){a&&(r+=
|
|
8
|
-
`&&(i&&
|
|
9
|
-
`)}var
|
|
10
|
-
`).flatMap(e=>
|
|
2
|
+
import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{t as r}from"./esm-wByiX8MO.mjs";import{t as i}from"./dist-BCyi1oM7.mjs";import{n as a,r as o,t as s}from"./dist-bundle-BSdjl7Rj.mjs";import{i as c,r as l}from"./constants-DLhaxFjM.mjs";import{$ as u,B as d,G as f,H as p,J as m,K as h,Q as g,R as _,U as v,V as y,W as b,X as x,Y as S,Z as ee,ct as te,dt as ne,et as C,ft as w,g as re,gt as ie,h as T,ht as ae,it as oe,lt as se,mt as ce,pt as le,q as ue,rt as de,st as fe,tt as pe,ut as me,w as he,z as ge}from"./dist-CIeZOXfv.mjs";import{n as _e,t as ve}from"./paths-DqWCeGWM.mjs";import{l as ye,o as be,s as xe}from"./server-lock-n3Y5JWNv-3o7br8XE.mjs";import{i as Se}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{$t as Ce,A as we,C as Te,Ct as Ee,P as De,Qt as Oe,bt as ke,en as Ae,nn as je,tn as Me}from"./dist-DD_wEI4a.mjs";import{r as Ne}from"./init-2ZbpRqT6.mjs";import{i as Pe,n as Fe,o as Ie,r as Le,s as Re,t as ze}from"./colors-DoPZvo1q.mjs";import{t as Be}from"./is-object-BNVklKxg.mjs";import{i as Ve,n as He,t as Ue}from"./loader-B73SzGQk.mjs";import{t as We}from"./chunk-YNYSPYQ5-BpP11HXS.mjs";import{a as Ge,c as Ke,d as qe,f as Je,h as Ye,i as Xe,l as Ze,m as Qe,n as $e,o as et,p as tt,r as nt,s as rt,t as it,u as at}from"./chunk-GFQRA5P5-1fzItQ8F.mjs";import{A as ot,B as st,C as ct,D as lt,E as ut,F as dt,H as ft,I as pt,L as mt,M as ht,N as gt,O as _t,P as vt,S as yt,T as bt,V as xt,_ as St,a as Ct,b as wt,c as Tt,d as Et,f as E,g as Dt,h as Ot,i as kt,j as At,k as jt,l as Mt,m as Nt,n as Pt,o as Ft,p as It,r as Lt,s as Rt,t as zt,u as Bt,v as Vt,w as Ht,x as Ut,y as Wt,z as Gt}from"./chunk-FEIOJCZD-C4x0A4rb.mjs";import{a as Kt,c as qt,d as Jt,i as D,l as Yt,n as Xt,o as Zt,r as Qt,s as O,t as $t,u as en}from"./chunk-XHM67O4N-Cg35xc6b.mjs";import{n as tn,r as nn,t as rn}from"./chunk-R6VWJ2ZL-B0CcMPyK.mjs";import{r as an}from"./chunk-CWQS3NFK-DFdwmFxJ.mjs";import"./chunk-DXB73IDG-C774okS0.mjs";import{n as on,t as sn}from"./chunk-5QMZ5MUS-DWTkM0vM.mjs";import{n as cn,t as ln}from"./chunk-A5O5YHGN-C7BVq0eF.mjs";import{n as un,r as dn,t as fn}from"./chunk-OJDRYQWQ-BV5MVRVg.mjs";import{r as pn,t as mn}from"./chunk-24IMIIXA-Bz7rlZT3.mjs";import{n as hn}from"./chunk-3THT3N7L-klp8GP84.mjs";import{t as gn}from"./chunk-44UOCSGV-BUBpWxXm.mjs";import{o as _n,s as vn}from"./start-nj1M3dB_.mjs";import"./src-CCUnFptH.mjs";import{execFileSync as yn,spawn as bn}from"node:child_process";import*as k from"node:path";import xn,{basename as Sn,dirname as Cn,isAbsolute as wn,join as Tn,relative as En,resolve as Dn}from"node:path";import*as A from"node:fs";import{appendFileSync as On,closeSync as kn,existsSync as An,mkdirSync as jn,openSync as Mn,readFileSync as Nn,readdirSync as Pn,realpathSync as Fn,statSync as In,unlinkSync as Ln,writeFileSync as Rn}from"node:fs";import zn from"node:process";import{homedir as Bn,hostname as Vn,platform as Hn}from"node:os";import{AsyncLocalStorage as Un,AsyncResource as Wn}from"node:async_hooks";import{stripVTControlCharacters as Gn,styleText as Kn}from"node:util";import*as qn from"node:readline";import{fileURLToPath as Jn}from"node:url";import{randomUUID as Yn}from"node:crypto";import{setTimeout as Xn}from"node:timers/promises";import{mkdir as Zn,readFile as Qn,readdir as $n,stat as er}from"node:fs/promises";import{createServer as tr,request as nr}from"node:http";import{lookup as rr}from"node:dns";import{createInterface as ir}from"node:readline/promises";var ar=i();const or=`open-knowledge`;var sr=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(or,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(or,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(or,e).deletePassword()}catch{}}},cr=class{backend=`file`;authFile;constructor(e){this.authFile=e??Tn(Bn(),`.open-knowledge`,`auth.yml`)}read(){if(!An(this.authFile))return{};try{return(0,ar.parse)(Nn(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=Cn(this.authFile);An(t)||jn(t,{recursive:!0,mode:448}),Rn(this.authFile,(0,ar.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function lr(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(or,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
|
|
3
|
+
`),new sr}catch{return process.stderr.write(`[auth] token storage: file (~/.open-knowledge/auth.yml)
|
|
4
|
+
`),new cr(e)}}async function ur(e,t,n){let r=dr(await fr(e)).host??``;if(!r)return 1;let i=await n.get(r);if(i==null)return 1;let a=e=>e.replace(/[\r\n]/g,``);return t.write(`username=${a(i.login)}\npassword=${a(i.token)}\n`),0}function dr(e){let t={};for(let n of e.split(`
|
|
5
|
+
`)){let e=n.trim();if(e===``)continue;let r=e.indexOf(`=`);r!==-1&&(t[e.slice(0,r)]=e.slice(r+1))}return t}function fr(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function pr(e){let t=new r(`git-credential`);return t.description(`Git credential helper (git credential-helper protocol)`),t.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await ur(process.stdin,process.stdout,t);process.exit(n)}),t}function mr(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function hr(e,t,n){let r={baseUrl:mr(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new a(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function gr(e){let t=e.request||s,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),hr(t,`POST /login/device/code`,n)}async function _r(e){let t=await hr(e.request||s,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=vr(e,t.data.expires_in),n.refreshTokenExpiresAt=vr(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function vr(e,t){return new Date(e+t*1e3).toISOString()}async function yr(e,t){let n=br(e,t.auth);if(n)return n;let{data:r}=await gr({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await Sr(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function br(e,t){if(t.refresh===!0||!e.authentication)return!1;if(e.clientType===`github-app`)return e.authentication;let n=e.authentication;return(`scopes`in t&&t.scopes||e.scopes).join(` `)===n.scopes.join(` `)?n:!1}async function xr(e){await new Promise(t=>setTimeout(t,e*1e3))}async function Sr(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await _r({...i,clientType:`oauth-app`}):await _r({...i,clientType:`github-app`});return{type:`token`,tokenType:`oauth`,...a}}catch(i){if(!i.response)throw i;let a=i.response.data.error;if(a===`authorization_pending`)return await xr(r.interval),Sr(e,t,n,r);if(a===`slow_down`)return await xr(r.interval+7),Sr(e,t,n,r);throw i}}async function Cr(e,t){return yr(e,{auth:t})}async function wr(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);let{token:a}=await yr(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Tr=`0.0.0-development`;function Er(e){let t=e.request||s.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Tr} ${o()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(Cr.bind(null,i),{hook:wr.bind(null,i)})}async function Dr(e){let{clientId:t,scopes:n=[`repo`,`read:user`,`user:email`],onVerification:r,host:i}=e,a=i&&i!==`github.com`?`https://${i}/api/v3`:`https://api.github.com`,o=Er({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`./dist-bundle-BmF5_Mcp.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}function Or(e){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??e?.github?.oauthAppClientId??`Ov23liqlSd0V1MwR6rhI`}const kr=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function Ar(e){let t=e.toLowerCase().replace(/:\d+$/,``);kr.has(t)&&(process.stderr.write(`Error: ${e} is not a GitHub host. Only GitHub and GitHub Enterprise Server are supported.\n`),process.exit(1))}function jr(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Mr(e,t,n,r=Dr){let i=Or(n),{host:a,json:o}=e;Ar(a),o||process.stderr.write(`Logging in to ${a}…\n`);let s=await r({clientId:i,host:a===`github.com`?void 0:a,onVerification:e=>{e.userCode,e.verificationUri,o?jr(!0,{type:`verification`,user_code:e.userCode,verification_uri:e.verificationUri,expires_in:e.expiresIn}):process.stderr.write(`Open: ${e.verificationUri}\nEnter code: ${e.userCode}\n`)}}),c=`unknown`,l,u;try{let e=a===`github.com`?`https://api.github.com`:`https://${a}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${s.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();c=e.login??c,l=e.name??void 0,u=e.email??void 0}}catch{}await t.set(a,c,s.token,{gitProtocol:`https`,name:l,email:u}),o?jr(!0,{type:`complete`,host:a,login:c}):process.stderr.write(`✓ Logged in as ${c} on ${a}\n`)}function Nr(e,t){return new r(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSONL progress events`,!1).action(async n=>{await Mr(n,await t(),e())})}const Pr=e=>e.name===`enter`||e.name===`return`;var Fr=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Ir=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Lr=class extends Error{name=`ExitPromptError`},Rr=class extends Error{name=`HookError`},zr=class extends Error{name=`ValidationError`};const Br=new Un;function Vr(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Hr(e,t){let n=Vr(e);return Br.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function Ur(){let e=Br.getStore();if(!e)throw new Rr(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function Wr(){return Ur().rl}function Gr(e){return Wn.bind((...t)=>{let n=Ur(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function Kr(e){let t=Ur(),{index:n}=t,r=e({get(){return t.hooks[n]},set(e){t.hooks[n]=e},initialized:n in t.hooks});return t.index++,r}function qr(){Ur().handleChange()}const Jr={queue(e){let t=Ur(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(Wr());if(r!=null&&typeof r!=`function`)throw new zr(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=Ur();Gr(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=Ur();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function Yr(e){return typeof e==`function`}function Xr(e){return Kr(t=>{let n=Wn.bind(function(e){t.get()!==e&&(t.set(e),qr())});if(t.initialized)return[t.get(),n];let r=Yr(e)?e():e;return t.set(r),[r,n]})}function Zr(e,t){Kr(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&Jr.queue(e),n.set(t)})}function Qr(){return zn.platform.startsWith(`win`)?!!zn.env.CI||!!zn.env.WT_SESSION||!!zn.env.TERMINUS_SUBLIME||zn.env.ConEmuTask===`{cmd::Cmder}`||zn.env.TERM_PROGRAM===`Terminus-Sublime`||zn.env.TERM_PROGRAM===`vscode`||zn.env.TERM===`xterm-256color`||zn.env.TERM===`alacritty`||zn.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:zn.env.TERM!==`linux`}const $r={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},ei={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},ti={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},ni={...$r,...ei},ri={...$r,...ti},ii=Qr()?ni:ri;Object.entries(ei);const ai={prefix:{idle:Kn(`blue`,`?`),done:Kn(`green`,ii.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>Kn(`yellow`,e))},style:{answer:e=>Kn(`cyan`,e),message:e=>Kn(`bold`,e),error:e=>Kn(`red`,`> ${e}`),defaultAnswer:e=>Kn(`dim`,`(${e})`),help:e=>Kn(`dim`,e),highlight:e=>Kn(`cyan`,e),key:e=>Kn(`cyan`,Kn(`bold`,`<${e}>`))}};function oi(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function si(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=oi(n)&&oi(r)?si(n,r):r}return t}function ci(...e){return si(ai,...e.filter(e=>e!=null))}function li({status:e=`idle`,theme:t}){let[n,r]=Xr(!1),[i,a]=Xr(0),{prefix:o,spinner:s}=ci(t);return Zr(()=>{if(e===`loading`){let e,t=-1,n=setTimeout(()=>{r(!0),e=setInterval(()=>{t+=1,a(t%s.frames.length)},s.interval)},300);return()=>{clearTimeout(n),clearInterval(e)}}else r(!1)},[e]),n?s.frames[i]:typeof o==`string`?o:o[e===`loading`?`idle`:e]??o.idle}function ui(e){return Xr({current:e})[0]}function di(e){let t=ui(e);t.current=e,Zr(e=>{let n=!1,r=Gr((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var fi=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const pi=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),mi=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,hi=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,gi=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,_i=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,vi=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,yi=/\t{1,1000}/y,bi=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,xi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Si=/\p{M}+/gu,Ci={limit:1/0,ellipsis:``},wi=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?wi(i,Ci,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[xi,l],[gi,0],[_i,o],[yi,s],[bi,c],[vi,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Si,``)){let t=e.codePointAt(0)||0;if(S=mi(t)?2:hi(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===vi?pi(e.slice(p,n.lastIndex)):n===bi?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Ti={limit:1/0,ellipsis:``,ellipsisWidth:0},Ei=(e,t={})=>wi(e,Ti,t).width,Di=`]8;;`,Oi=RegExp(`(?:\\[(?<code>\\d+)m|\\${Di}(?<uri>.*))`,`y`),ki=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Ai=e=>`[${e}m`,ji=e=>`${Di}${e}`,Mi=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:Ei(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=Ei(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(Di,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Ni=e=>{let t=e.split(` `),n=t.length;for(;n&&!Ei(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Pi=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=Ei(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=Ei(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Mi(s,r,t),c=Ei(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Mi(s,r,t),c=Ei(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Mi(s,r,t),c=Ei(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ni(e)));let l=s.join(`
|
|
6
|
+
`),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===``){Oi.lastIndex=e+1;let t=Oi.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
|
|
7
|
+
`){a&&(r+=ji(``));let e=i?ki(i):void 0;i&&e&&(r+=Ai(e))}else t===`
|
|
8
|
+
`&&(i&&ki(i)&&(r+=Ai(i)),a&&(r+=ji(a)))}return r},Fi=/\r?\n/;function Ii(e,t,n){return String(e).normalize().split(Fi).map(e=>Pi(e,t,n)).join(`
|
|
9
|
+
`)}var Li=t(fi(),1);function Ri(e,t){return e.split(`
|
|
10
|
+
`).flatMap(e=>Ii(e,t,{trim:!1,hard:!0}).split(`
|
|
11
11
|
`).map(e=>e.trimEnd())).join(`
|
|
12
|
-
`)}function
|
|
13
|
-
`).length,
|
|
14
|
-
`).pop()??``;var
|
|
12
|
+
`)}function zi(){return(0,Li.default)({defaultWidth:80,output:Wr().output})}var Bi=n(((t,n)=>{let r=e(`stream`);n.exports=class extends r{#e=null;constructor(e={}){super(e),this.writable=this.readable=!0,this.muted=!1,this.on(`pipe`,this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,t){return this._dest?this._dest[e]:this._src?this._src[e]:t}#n(e,...t){typeof this._dest?.[e]==`function`&&this._dest[e](...t),typeof this._src?.[e]==`function`&&this._src[e](...t)}get isTTY(){return this.#e===null?this.#t(`isTTY`,!1):this.#e}set isTTY(e){this.#e=e}get rows(){return this.#t(`rows`)}get columns(){return this.#t(`columns`)}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,t){return this._dest=e,super.pipe(e,t)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/))return e.indexOf(this._prompt)===0&&(e=e.slice(this._prompt.length),e=e.replace(/./g,this.replace),e=this._prompt+e),this._hadControl=!0,this.emit(`data`,e);this._prompt&&this._hadControl&&e.indexOf(this._prompt)===0&&(this._hadControl=!1,this.emit(`data`,this._prompt),e=e.slice(this._prompt.length)),e=e.toString().replace(/./g,this.replace)}this.emit(`data`,e)}end(e){this.muted&&(e=e&&this.replace?e.toString().replace(/./g,this.replace):null),e&&this.emit(`data`,e),this.emit(`end`)}destroy(...e){return this.#n(`destroy`,...e)}destroySoon(...e){return this.#n(`destroySoon`,...e)}close(...e){return this.#n(`close`,...e)}}}));const Vi=[];Vi.push(`SIGHUP`,`SIGINT`,`SIGTERM`),process.platform!==`win32`&&Vi.push(`SIGALRM`,`SIGABRT`,`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&Vi.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`);const Hi=e=>!!e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`,Ui=Symbol.for(`signal-exit emitter`),Wi=globalThis,Gi=Object.defineProperty.bind(Object);var Ki=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Wi[Ui])return Wi[Ui];Gi(Wi,Ui,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let n=this.listeners[e],r=n.indexOf(t);r!==-1&&(r===0&&n.length===1?n.length=0:n.splice(r,1))}emit(e,t,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let r=!1;for(let i of this.listeners[e])r=i(t,n)===!0||r;return e===`exit`&&(r=this.emit(`afterExit`,t,n)||r),r}},qi=class{};const Ji=e=>({onExit(t,n){return e.onExit(t,n)},load(){return e.load()},unload(){return e.unload()}});var Yi=class extends qi{onExit(){return()=>{}}load(){}unload(){}},Xi=class extends qi{#e=Zi.platform===`win32`?`SIGINT`:`SIGHUP`;#t=new Ki;#n;#r;#i;#a={};#o=!1;constructor(e){super(),this.#n=e,this.#a={};for(let t of Vi)this.#a[t]=()=>{let n=this.#n.listeners(t),{count:r}=this.#t,i=e;if(typeof i.__signal_exit_emitter__==`object`&&typeof i.__signal_exit_emitter__.count==`number`&&(r+=i.__signal_exit_emitter__.count),n.length===r){this.unload();let n=this.#t.emit(`exit`,null,t),r=t===`SIGHUP`?this.#e:t;n||e.kill(e.pid,r)}};this.#i=e.reallyExit,this.#r=e.emit}onExit(e,t){if(!Hi(this.#n))return()=>{};this.#o===!1&&this.load();let n=t?.alwaysLast?`afterExit`:`exit`;return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#o){this.#o=!0,this.#t.count+=1;for(let e of Vi)try{let t=this.#a[e];t&&this.#n.on(e,t)}catch{}this.#n.emit=(e,...t)=>this.#c(e,...t),this.#n.reallyExit=e=>this.#s(e)}}unload(){this.#o&&(this.#o=!1,Vi.forEach(e=>{let t=this.#a[e];if(!t)throw Error(`Listener not defined for signal: `+e);try{this.#n.removeListener(e,t)}catch{}}),this.#n.emit=this.#r,this.#n.reallyExit=this.#i,--this.#t.count)}#s(e){return Hi(this.#n)?(this.#n.exitCode=e||0,this.#t.emit(`exit`,this.#n.exitCode,null),this.#i.call(this.#n,this.#n.exitCode)):0}#c(e,...t){let n=this.#r;if(e===`exit`&&Hi(this.#n)){typeof t[0]==`number`&&(this.#n.exitCode=t[0]);let r=n.call(this.#n,e,...t);return this.#t.emit(`exit`,this.#n.exitCode,null),r}else return n.call(this.#n,e,...t)}};const Zi=globalThis.process,{onExit:Qi,load:$i,unload:ea}=Ji(Hi(Zi)?new Xi(Zi):new Yi),ta=(e=1)=>e>0?`[${e}A`:``,na=(e=1)=>e>0?`[${e}B`:``,ra=(e,t)=>typeof t==`number`&&!Number.isNaN(t)?`[${t+1};${e+1}H`:`[${e+1}G`,ia=`\x1B[2K`,aa=e=>e>0?(ia+ta(1)).repeat(e-1)+ia+`\x1B[G`:``,oa=e=>e.split(`
|
|
13
|
+
`).length,sa=e=>e.split(`
|
|
14
|
+
`).pop()??``;var ca=class{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,t=``){let n=Gn(sa(e)),r=n;this.rl.line.length>0&&(r=r.slice(0,-this.rl.line.length)),this.rl.setPrompt(r),this.cursorPos=this.rl.getCursorPos();let i=zi();e=Ri(e,i),t=Ri(t,i),n.length%i===0&&(e+=`
|
|
15
15
|
`);let a=e+(t?`
|
|
16
|
-
`+t:``),o=Math.floor(n.length/i)-this.cursorPos.rows+(t?
|
|
17
|
-
`,t+=`\x1B[?25h`,this.write(t),this.rl.close()}},
|
|
16
|
+
`+t:``),o=Math.floor(n.length/i)-this.cursorPos.rows+(t?oa(t):0);o>0&&(a+=ta(o)),a+=ra(this.cursorPos.cols),this.write(na(this.extraLinesUnderPrompt)+aa(this.height)+a),this.extraLinesUnderPrompt=o,this.height=oa(a)}checkCursorPos(){let e=this.rl.getCursorPos();e.cols!==this.cursorPos.cols&&(this.write(ra(e.cols)),this.cursorPos=e)}done({clearContent:e}){this.rl.setPrompt(``);let t=na(this.extraLinesUnderPrompt);t+=e?aa(this.height):`
|
|
17
|
+
`,t+=`\x1B[?25h`,this.write(t),this.rl.close()}},la=class extends Promise{static withResolver(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}},ua=t(Bi(),1);const da=globalThis.setImmediate;function fa(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(e,n)=>{let r=n.slice(1);return t=r,r},Error().stack}catch{return t}return Error.prepareStackTrace=e,t}function pa(e){let t=fa();return(n,r={})=>{let{input:i=process.stdin,signal:a}=r,o=new Set,s=new ua.default;s.pipe(r.output??process.stdout),s.mute();let c=qn.createInterface({terminal:!0,input:i,output:s}),l=new ca(c),{promise:u,resolve:d,reject:f}=la.withResolver(),p=()=>f(new Ir);if(a){let e=()=>f(new Fr({cause:a.reason}));if(a.aborted)return e(),Object.assign(u,{cancel:p});a.addEventListener(`abort`,e),o.add(()=>a.removeEventListener(`abort`,e))}o.add(Qi((e,t)=>{f(new Lr(`User force closed the prompt with ${e} ${t}`))}));let m=()=>f(new Lr(`User force closed the prompt with SIGINT`));return c.on(`SIGINT`,m),o.add(()=>c.removeListener(`SIGINT`,m)),Hr(c,a=>{let m=Wn.bind(()=>Jr.clearAll());c.on(`close`,m),o.add(()=>c.removeListener(`close`,m));let h=()=>{let r=()=>l.checkCursorPos();c.input.on(`keypress`,r),o.add(()=>c.input.removeListener(`keypress`,r));let i=null;a(()=>{let r=!1;try{let a=e(n,e=>{r?d(e):i={value:e}});if(a===void 0){let e=t[1]?.getFileName();throw e&&!e.startsWith(`file://`)&&(e=xn.resolve(e)),Error(`Prompt functions must return a string.\n at ${e}`)}let[o,s]=typeof a==`string`?[a]:a;l.render(o,s),Jr.run()}catch(e){f(e)}if(r=!0,i!==null){let{value:e}=i;i=null,d(e)}})};return`readableFlowing`in i?da(h):h(),Object.assign(u.then(e=>(Jr.clearAll(),e),e=>{throw Jr.clearAll(),e}).finally(()=>{o.forEach(e=>e()),l.done({clearContent:!!r.clearPromptOnDone}),s.end()}).then(()=>u),{cancel:p})})}}const ma={style:{maskedText:`[input is masked]`}};var ha=pa((e,t)=>{let{validate:n=()=>!0}=e,r=ci(ma,e.theme),[i,a]=Xr(`idle`),[o,s]=Xr(),[c,l]=Xr(``),u=li({status:i,theme:r});di(async(e,r)=>{if(i===`idle`)if(Pr(e)){let e=c;a(`loading`);let i=await n(e);i===!0?(l(e),a(`done`),t(e)):(r.write(c),s(i||`You must provide a valid value`),a(`idle`))}else l(r.line),s(void 0)});let d=r.style.message(e.message,i),f=``,p;e.mask?f=(typeof e.mask==`string`?e.mask:`*`).repeat(c.length):i!==`done`&&(p=`${r.style.help(r.style.maskedText)}[?25l`),i===`done`&&(f=r.style.answer(f));let m=``;return o&&(m=r.style.error(o)),[[u,d,e.mask?f:p].join(` `),m]});function ga(e,t,n,r){if(typeof n!=`function`)throw Error(`method for before hook must be a function`);return r||={},Array.isArray(t)?t.reverse().reduce((t,n)=>ga.bind(null,e,n,t,r),n)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((e,t)=>t.hook.bind(null,e,r),n)():n(r))}function _a(e,t,n,r){let i=r;e.registry[n]||(e.registry[n]=[]),t===`before`&&(r=(e,t)=>Promise.resolve().then(i.bind(null,t)).then(e.bind(null,t))),t===`after`&&(r=(e,t)=>{let n;return Promise.resolve().then(e.bind(null,t)).then(e=>(n=e,i(n,t))).then(()=>n)}),t===`error`&&(r=(e,t)=>Promise.resolve().then(e.bind(null,t)).catch(e=>i(e,t))),e.registry[n].push({hook:r,orig:i})}function va(e,t,n){if(!e.registry[t])return;let r=e.registry[t].map(e=>e.orig).indexOf(n);r!==-1&&e.registry[t].splice(r,1)}const ya=Function.bind,ba=ya.bind(ya);function xa(e,t,n){let r=ba(va,null).apply(null,n?[t,n]:[t]);e.api={remove:r},e.remove=r,[`before`,`error`,`after`,`wrap`].forEach(r=>{let i=n?[t,r,n]:[t,r];e[r]=e.api[r]=ba(_a,null).apply(null,i)})}function Sa(){let e=Symbol(`Singular`),t={registry:{}},n=ga.bind(null,t,e);return xa(n,t,e),n}function Ca(){let e={registry:{}},t=ga.bind(null,e);return xa(t,e),t}var wa={Singular:Sa,Collection:Ca},Ta=`0.0.0-development`;function Ea(e){return`Request failed due to following response errors:
|
|
18
18
|
`+e.errors.map(e=>` - ${e.message}`).join(`
|
|
19
|
-
`)}var Ea=class extends Error{constructor(e,t,n){super(Ta(n)),this.request=e,this.headers=t,this.response=n,this.errors=n.errors,this.data=n.data,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}name=`GraphqlResponseError`;errors;data},Da=[`method`,`baseUrl`,`url`,`headers`,`request`,`query`,`mediaType`,`operationName`],Oa=[`query`,`method`,`url`],ka=/\/api\/v3\/?$/;function Aa(e,t,n){if(n){if(typeof t==`string`&&`query`in n)return Promise.reject(Error(`[@octokit/graphql] "query" cannot be used as variable name`));for(let e in n)if(Oa.includes(e))return Promise.reject(Error(`[@octokit/graphql] "${e}" cannot be used as variable name`))}let r=typeof t==`string`?Object.assign({query:t},n):t,i=Object.keys(r).reduce((e,t)=>Da.includes(t)?(e[t]=r[t],e):(e.variables||={},e.variables[t]=r[t],e),{}),a=r.baseUrl||e.endpoint.DEFAULTS.baseUrl;return ka.test(a)&&(i.url=a.replace(ka,`/api/graphql`)),e(i).then(e=>{if(e.data.errors){let t={};for(let n of Object.keys(e.headers))t[n]=e.headers[n];throw new Ea(i,t,e.data)}return e.data.data})}function ja(e,t){let n=e.defaults(t);return Object.assign((e,t)=>Aa(n,e,t),{defaults:ja.bind(null,n),endpoint:n.endpoint})}ja(s,{headers:{"user-agent":`octokit-graphql.js/${wa} ${o()}`},method:`POST`,url:`/graphql`});function Ma(e){return ja(e,{method:`POST`,url:`/graphql`})}var Na=`(?:[a-zA-Z0-9_-]+)`,Pa=`\\.`,Fa=RegExp(`^${Na}${Pa}${Na}${Pa}${Na}$`),Ia=Fa.test.bind(Fa);async function La(e){let t=Ia(e),n=e.startsWith(`v1.`)||e.startsWith(`ghs_`),r=e.startsWith(`ghu_`);return{type:`token`,token:e,tokenType:t?`app`:n?`installation`:r?`user-to-server`:`oauth`}}function Ra(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function za(e,t,n,r){let i=t.endpoint.merge(n,r);return i.headers.authorization=Ra(e),t(i)}var Ba=function(e){if(!e)throw Error(`[@octokit/auth-token] No token passed to createTokenAuth`);if(typeof e!=`string`)throw Error(`[@octokit/auth-token] Token passed to createTokenAuth is not a string`);return e=e.replace(/^(token|bearer) +/i,``),Object.assign(La.bind(null,e),{hook:za.bind(null,e)})};const Va=`7.0.6`,Ha=()=>{},Ua=console.warn.bind(console),Wa=console.error.bind(console);function Ga(e={}){return typeof e.debug!=`function`&&(e.debug=Ha),typeof e.info!=`function`&&(e.info=Ha),typeof e.warn!=`function`&&(e.warn=Ua),typeof e.error!=`function`&&(e.error=Wa),e}const Ka=`octokit-core.js/${Va} ${o()}`;var qa=class{static VERSION=Va;static defaults(e){return class extends this{constructor(...t){let n=t[0]||{};if(typeof e==`function`){super(e(n));return}super(Object.assign({},e,n,n.userAgent&&e.userAgent?{userAgent:`${n.userAgent} ${e.userAgent}`}:null))}}}static plugins=[];static plugin(...e){let t=this.plugins;return class extends this{static plugins=t.concat(e.filter(e=>!t.includes(e)))}}constructor(e={}){let t=new Ca.Collection,n={baseUrl:s.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},e.request,{hook:t.bind(null,`request`)}),mediaType:{previews:[],format:``}};if(n.headers[`user-agent`]=e.userAgent?`${e.userAgent} ${Ka}`:Ka,e.baseUrl&&(n.baseUrl=e.baseUrl),e.previews&&(n.mediaType.previews=e.previews),e.timeZone&&(n.headers[`time-zone`]=e.timeZone),this.request=s.defaults(n),this.graphql=Ma(this.request).defaults(n),this.log=Ga(e.log),this.hook=t,e.authStrategy){let{authStrategy:n,...r}=e,i=n(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:r},e.auth));t.wrap(`request`,i.hook),this.auth=i}else if(!e.auth)this.auth=async()=>({type:`unauthenticated`});else{let n=Ba(e.auth);t.wrap(`request`,n.hook),this.auth=n}let r=this.constructor;for(let t=0;t<r.plugins.length;++t)Object.assign(this,r.plugins[t](this,e))}request;graphql;log;hook;auth};function Ja(e){e.hook.wrap(`request`,(t,n)=>{e.log.debug(`request`,n);let r=Date.now(),i=e.request.endpoint.parse(n),a=i.url.replace(n.baseUrl,``);return t(n).then(t=>{let n=t.headers[`x-github-request-id`];return e.log.info(`${i.method} ${a} - ${t.status} with id ${n} in ${Date.now()-r}ms`),t}).catch(t=>{let n=t.response?.headers[`x-github-request-id`]||`UNKNOWN`;throw e.log.error(`${i.method} ${a} - ${t.status} with id ${n} in ${Date.now()-r}ms`),t})})}Ja.VERSION=`6.0.0`;var Ya=`0.0.0-development`;function Xa(e){if(!e.data)return{...e,data:[]};if(!((`total_count`in e.data||`total_commits`in e.data)&&!(`url`in e.data)))return e;let t=e.data.incomplete_results,n=e.data.repository_selection,r=e.data.total_count,i=e.data.total_commits;delete e.data.incomplete_results,delete e.data.repository_selection,delete e.data.total_count,delete e.data.total_commits;let a=Object.keys(e.data)[0];return e.data=e.data[a],t!==void 0&&(e.data.incomplete_results=t),n!==void 0&&(e.data.repository_selection=n),e.data.total_count=r,e.data.total_commits=i,e}function Za(e,t,n){let r=typeof t==`function`?t.endpoint(n):e.request.endpoint(t,n),i=typeof t==`function`?t:e.request,a=r.method,o=r.headers,s=r.url;return{[Symbol.asyncIterator]:()=>({async next(){if(!s)return{done:!0};try{let e=Xa(await i({method:a,url:s,headers:o}));if(s=((e.headers.link||``).match(/<([^<>]+)>;\s*rel="next"/)||[])[1],!s&&`total_commits`in e.data){let t=new URL(e.url),n=t.searchParams,r=parseInt(n.get(`page`)||`1`,10);r*parseInt(n.get(`per_page`)||`250`,10)<e.data.total_commits&&(n.set(`page`,String(r+1)),s=t.toString())}return{value:e}}catch(e){if(e.status!==409)throw e;return s=``,{value:{status:200,headers:{},data:[]}}}}})}}function Qa(e,t,n,r){return typeof n==`function`&&(r=n,n=void 0),$a(e,[],Za(e,t,n)[Symbol.asyncIterator](),r)}function $a(e,t,n,r){return n.next().then(i=>{if(i.done)return t;let a=!1;function o(){a=!0}return t=t.concat(r?r(i.value,o):i.value.data),a?t:$a(e,t,n,r)})}Object.assign(Qa,{iterator:Za});function eo(e){return{paginate:Object.assign(Qa.bind(null,e),{iterator:Za.bind(null,e)})}}eo.VERSION=Ya;const to=`17.0.0`;var no={actions:{addCustomLabelsToSelfHostedRunnerForOrg:[`POST /orgs/{org}/actions/runners/{runner_id}/labels`],addCustomLabelsToSelfHostedRunnerForRepo:[`POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],addRepoAccessToSelfHostedRunnerGroupInOrg:[`PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}`],addSelectedRepoToOrgSecret:[`PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}`],addSelectedRepoToOrgVariable:[`PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}`],approveWorkflowRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve`],cancelWorkflowRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel`],createEnvironmentVariable:[`POST /repos/{owner}/{repo}/environments/{environment_name}/variables`],createHostedRunnerForOrg:[`POST /orgs/{org}/actions/hosted-runners`],createOrUpdateEnvironmentSecret:[`PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}`],createOrUpdateOrgSecret:[`PUT /orgs/{org}/actions/secrets/{secret_name}`],createOrUpdateRepoSecret:[`PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}`],createOrgVariable:[`POST /orgs/{org}/actions/variables`],createRegistrationTokenForOrg:[`POST /orgs/{org}/actions/runners/registration-token`],createRegistrationTokenForRepo:[`POST /repos/{owner}/{repo}/actions/runners/registration-token`],createRemoveTokenForOrg:[`POST /orgs/{org}/actions/runners/remove-token`],createRemoveTokenForRepo:[`POST /repos/{owner}/{repo}/actions/runners/remove-token`],createRepoVariable:[`POST /repos/{owner}/{repo}/actions/variables`],createWorkflowDispatch:[`POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches`],deleteActionsCacheById:[`DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}`],deleteActionsCacheByKey:[`DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}`],deleteArtifact:[`DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}`],deleteCustomImageFromOrg:[`DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}`],deleteCustomImageVersionFromOrg:[`DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}`],deleteEnvironmentSecret:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}`],deleteEnvironmentVariable:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}`],deleteHostedRunnerForOrg:[`DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}`],deleteOrgSecret:[`DELETE /orgs/{org}/actions/secrets/{secret_name}`],deleteOrgVariable:[`DELETE /orgs/{org}/actions/variables/{name}`],deleteRepoSecret:[`DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}`],deleteRepoVariable:[`DELETE /repos/{owner}/{repo}/actions/variables/{name}`],deleteSelfHostedRunnerFromOrg:[`DELETE /orgs/{org}/actions/runners/{runner_id}`],deleteSelfHostedRunnerFromRepo:[`DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}`],deleteWorkflowRun:[`DELETE /repos/{owner}/{repo}/actions/runs/{run_id}`],deleteWorkflowRunLogs:[`DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs`],disableSelectedRepositoryGithubActionsOrganization:[`DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}`],disableWorkflow:[`PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable`],downloadArtifact:[`GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}`],downloadJobLogsForWorkflowRun:[`GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs`],downloadWorkflowRunAttemptLogs:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs`],downloadWorkflowRunLogs:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs`],enableSelectedRepositoryGithubActionsOrganization:[`PUT /orgs/{org}/actions/permissions/repositories/{repository_id}`],enableWorkflow:[`PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable`],forceCancelWorkflowRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel`],generateRunnerJitconfigForOrg:[`POST /orgs/{org}/actions/runners/generate-jitconfig`],generateRunnerJitconfigForRepo:[`POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig`],getActionsCacheList:[`GET /repos/{owner}/{repo}/actions/caches`],getActionsCacheUsage:[`GET /repos/{owner}/{repo}/actions/cache/usage`],getActionsCacheUsageByRepoForOrg:[`GET /orgs/{org}/actions/cache/usage-by-repository`],getActionsCacheUsageForOrg:[`GET /orgs/{org}/actions/cache/usage`],getAllowedActionsOrganization:[`GET /orgs/{org}/actions/permissions/selected-actions`],getAllowedActionsRepository:[`GET /repos/{owner}/{repo}/actions/permissions/selected-actions`],getArtifact:[`GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}`],getCustomImageForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}`],getCustomImageVersionForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}`],getCustomOidcSubClaimForRepo:[`GET /repos/{owner}/{repo}/actions/oidc/customization/sub`],getEnvironmentPublicKey:[`GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key`],getEnvironmentSecret:[`GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}`],getEnvironmentVariable:[`GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}`],getGithubActionsDefaultWorkflowPermissionsOrganization:[`GET /orgs/{org}/actions/permissions/workflow`],getGithubActionsDefaultWorkflowPermissionsRepository:[`GET /repos/{owner}/{repo}/actions/permissions/workflow`],getGithubActionsPermissionsOrganization:[`GET /orgs/{org}/actions/permissions`],getGithubActionsPermissionsRepository:[`GET /repos/{owner}/{repo}/actions/permissions`],getHostedRunnerForOrg:[`GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}`],getHostedRunnersGithubOwnedImagesForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/github-owned`],getHostedRunnersLimitsForOrg:[`GET /orgs/{org}/actions/hosted-runners/limits`],getHostedRunnersMachineSpecsForOrg:[`GET /orgs/{org}/actions/hosted-runners/machine-sizes`],getHostedRunnersPartnerImagesForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/partner`],getHostedRunnersPlatformsForOrg:[`GET /orgs/{org}/actions/hosted-runners/platforms`],getJobForWorkflowRun:[`GET /repos/{owner}/{repo}/actions/jobs/{job_id}`],getOrgPublicKey:[`GET /orgs/{org}/actions/secrets/public-key`],getOrgSecret:[`GET /orgs/{org}/actions/secrets/{secret_name}`],getOrgVariable:[`GET /orgs/{org}/actions/variables/{name}`],getPendingDeploymentsForRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments`],getRepoPermissions:[`GET /repos/{owner}/{repo}/actions/permissions`,{},{renamed:[`actions`,`getGithubActionsPermissionsRepository`]}],getRepoPublicKey:[`GET /repos/{owner}/{repo}/actions/secrets/public-key`],getRepoSecret:[`GET /repos/{owner}/{repo}/actions/secrets/{secret_name}`],getRepoVariable:[`GET /repos/{owner}/{repo}/actions/variables/{name}`],getReviewsForRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals`],getSelfHostedRunnerForOrg:[`GET /orgs/{org}/actions/runners/{runner_id}`],getSelfHostedRunnerForRepo:[`GET /repos/{owner}/{repo}/actions/runners/{runner_id}`],getWorkflow:[`GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}`],getWorkflowAccessToRepository:[`GET /repos/{owner}/{repo}/actions/permissions/access`],getWorkflowRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}`],getWorkflowRunAttempt:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}`],getWorkflowRunUsage:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing`],getWorkflowUsage:[`GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing`],listArtifactsForRepo:[`GET /repos/{owner}/{repo}/actions/artifacts`],listCustomImageVersionsForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions`],listCustomImagesForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom`],listEnvironmentSecrets:[`GET /repos/{owner}/{repo}/environments/{environment_name}/secrets`],listEnvironmentVariables:[`GET /repos/{owner}/{repo}/environments/{environment_name}/variables`],listGithubHostedRunnersInGroupForOrg:[`GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners`],listHostedRunnersForOrg:[`GET /orgs/{org}/actions/hosted-runners`],listJobsForWorkflowRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs`],listJobsForWorkflowRunAttempt:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs`],listLabelsForSelfHostedRunnerForOrg:[`GET /orgs/{org}/actions/runners/{runner_id}/labels`],listLabelsForSelfHostedRunnerForRepo:[`GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],listOrgSecrets:[`GET /orgs/{org}/actions/secrets`],listOrgVariables:[`GET /orgs/{org}/actions/variables`],listRepoOrganizationSecrets:[`GET /repos/{owner}/{repo}/actions/organization-secrets`],listRepoOrganizationVariables:[`GET /repos/{owner}/{repo}/actions/organization-variables`],listRepoSecrets:[`GET /repos/{owner}/{repo}/actions/secrets`],listRepoVariables:[`GET /repos/{owner}/{repo}/actions/variables`],listRepoWorkflows:[`GET /repos/{owner}/{repo}/actions/workflows`],listRunnerApplicationsForOrg:[`GET /orgs/{org}/actions/runners/downloads`],listRunnerApplicationsForRepo:[`GET /repos/{owner}/{repo}/actions/runners/downloads`],listSelectedReposForOrgSecret:[`GET /orgs/{org}/actions/secrets/{secret_name}/repositories`],listSelectedReposForOrgVariable:[`GET /orgs/{org}/actions/variables/{name}/repositories`],listSelectedRepositoriesEnabledGithubActionsOrganization:[`GET /orgs/{org}/actions/permissions/repositories`],listSelfHostedRunnersForOrg:[`GET /orgs/{org}/actions/runners`],listSelfHostedRunnersForRepo:[`GET /repos/{owner}/{repo}/actions/runners`],listWorkflowRunArtifacts:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts`],listWorkflowRuns:[`GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs`],listWorkflowRunsForRepo:[`GET /repos/{owner}/{repo}/actions/runs`],reRunJobForWorkflowRun:[`POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun`],reRunWorkflow:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun`],reRunWorkflowFailedJobs:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs`],removeAllCustomLabelsFromSelfHostedRunnerForOrg:[`DELETE /orgs/{org}/actions/runners/{runner_id}/labels`],removeAllCustomLabelsFromSelfHostedRunnerForRepo:[`DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],removeCustomLabelFromSelfHostedRunnerForOrg:[`DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}`],removeCustomLabelFromSelfHostedRunnerForRepo:[`DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}`],removeSelectedRepoFromOrgSecret:[`DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}`],removeSelectedRepoFromOrgVariable:[`DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}`],reviewCustomGatesForRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule`],reviewPendingDeploymentsForRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments`],setAllowedActionsOrganization:[`PUT /orgs/{org}/actions/permissions/selected-actions`],setAllowedActionsRepository:[`PUT /repos/{owner}/{repo}/actions/permissions/selected-actions`],setCustomLabelsForSelfHostedRunnerForOrg:[`PUT /orgs/{org}/actions/runners/{runner_id}/labels`],setCustomLabelsForSelfHostedRunnerForRepo:[`PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],setCustomOidcSubClaimForRepo:[`PUT /repos/{owner}/{repo}/actions/oidc/customization/sub`],setGithubActionsDefaultWorkflowPermissionsOrganization:[`PUT /orgs/{org}/actions/permissions/workflow`],setGithubActionsDefaultWorkflowPermissionsRepository:[`PUT /repos/{owner}/{repo}/actions/permissions/workflow`],setGithubActionsPermissionsOrganization:[`PUT /orgs/{org}/actions/permissions`],setGithubActionsPermissionsRepository:[`PUT /repos/{owner}/{repo}/actions/permissions`],setSelectedReposForOrgSecret:[`PUT /orgs/{org}/actions/secrets/{secret_name}/repositories`],setSelectedReposForOrgVariable:[`PUT /orgs/{org}/actions/variables/{name}/repositories`],setSelectedRepositoriesEnabledGithubActionsOrganization:[`PUT /orgs/{org}/actions/permissions/repositories`],setWorkflowAccessToRepository:[`PUT /repos/{owner}/{repo}/actions/permissions/access`],updateEnvironmentVariable:[`PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}`],updateHostedRunnerForOrg:[`PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}`],updateOrgVariable:[`PATCH /orgs/{org}/actions/variables/{name}`],updateRepoVariable:[`PATCH /repos/{owner}/{repo}/actions/variables/{name}`]},activity:{checkRepoIsStarredByAuthenticatedUser:[`GET /user/starred/{owner}/{repo}`],deleteRepoSubscription:[`DELETE /repos/{owner}/{repo}/subscription`],deleteThreadSubscription:[`DELETE /notifications/threads/{thread_id}/subscription`],getFeeds:[`GET /feeds`],getRepoSubscription:[`GET /repos/{owner}/{repo}/subscription`],getThread:[`GET /notifications/threads/{thread_id}`],getThreadSubscriptionForAuthenticatedUser:[`GET /notifications/threads/{thread_id}/subscription`],listEventsForAuthenticatedUser:[`GET /users/{username}/events`],listNotificationsForAuthenticatedUser:[`GET /notifications`],listOrgEventsForAuthenticatedUser:[`GET /users/{username}/events/orgs/{org}`],listPublicEvents:[`GET /events`],listPublicEventsForRepoNetwork:[`GET /networks/{owner}/{repo}/events`],listPublicEventsForUser:[`GET /users/{username}/events/public`],listPublicOrgEvents:[`GET /orgs/{org}/events`],listReceivedEventsForUser:[`GET /users/{username}/received_events`],listReceivedPublicEventsForUser:[`GET /users/{username}/received_events/public`],listRepoEvents:[`GET /repos/{owner}/{repo}/events`],listRepoNotificationsForAuthenticatedUser:[`GET /repos/{owner}/{repo}/notifications`],listReposStarredByAuthenticatedUser:[`GET /user/starred`],listReposStarredByUser:[`GET /users/{username}/starred`],listReposWatchedByUser:[`GET /users/{username}/subscriptions`],listStargazersForRepo:[`GET /repos/{owner}/{repo}/stargazers`],listWatchedReposForAuthenticatedUser:[`GET /user/subscriptions`],listWatchersForRepo:[`GET /repos/{owner}/{repo}/subscribers`],markNotificationsAsRead:[`PUT /notifications`],markRepoNotificationsAsRead:[`PUT /repos/{owner}/{repo}/notifications`],markThreadAsDone:[`DELETE /notifications/threads/{thread_id}`],markThreadAsRead:[`PATCH /notifications/threads/{thread_id}`],setRepoSubscription:[`PUT /repos/{owner}/{repo}/subscription`],setThreadSubscription:[`PUT /notifications/threads/{thread_id}/subscription`],starRepoForAuthenticatedUser:[`PUT /user/starred/{owner}/{repo}`],unstarRepoForAuthenticatedUser:[`DELETE /user/starred/{owner}/{repo}`]},apps:{addRepoToInstallation:[`PUT /user/installations/{installation_id}/repositories/{repository_id}`,{},{renamed:[`apps`,`addRepoToInstallationForAuthenticatedUser`]}],addRepoToInstallationForAuthenticatedUser:[`PUT /user/installations/{installation_id}/repositories/{repository_id}`],checkToken:[`POST /applications/{client_id}/token`],createFromManifest:[`POST /app-manifests/{code}/conversions`],createInstallationAccessToken:[`POST /app/installations/{installation_id}/access_tokens`],deleteAuthorization:[`DELETE /applications/{client_id}/grant`],deleteInstallation:[`DELETE /app/installations/{installation_id}`],deleteToken:[`DELETE /applications/{client_id}/token`],getAuthenticated:[`GET /app`],getBySlug:[`GET /apps/{app_slug}`],getInstallation:[`GET /app/installations/{installation_id}`],getOrgInstallation:[`GET /orgs/{org}/installation`],getRepoInstallation:[`GET /repos/{owner}/{repo}/installation`],getSubscriptionPlanForAccount:[`GET /marketplace_listing/accounts/{account_id}`],getSubscriptionPlanForAccountStubbed:[`GET /marketplace_listing/stubbed/accounts/{account_id}`],getUserInstallation:[`GET /users/{username}/installation`],getWebhookConfigForApp:[`GET /app/hook/config`],getWebhookDelivery:[`GET /app/hook/deliveries/{delivery_id}`],listAccountsForPlan:[`GET /marketplace_listing/plans/{plan_id}/accounts`],listAccountsForPlanStubbed:[`GET /marketplace_listing/stubbed/plans/{plan_id}/accounts`],listInstallationReposForAuthenticatedUser:[`GET /user/installations/{installation_id}/repositories`],listInstallationRequestsForAuthenticatedApp:[`GET /app/installation-requests`],listInstallations:[`GET /app/installations`],listInstallationsForAuthenticatedUser:[`GET /user/installations`],listPlans:[`GET /marketplace_listing/plans`],listPlansStubbed:[`GET /marketplace_listing/stubbed/plans`],listReposAccessibleToInstallation:[`GET /installation/repositories`],listSubscriptionsForAuthenticatedUser:[`GET /user/marketplace_purchases`],listSubscriptionsForAuthenticatedUserStubbed:[`GET /user/marketplace_purchases/stubbed`],listWebhookDeliveries:[`GET /app/hook/deliveries`],redeliverWebhookDelivery:[`POST /app/hook/deliveries/{delivery_id}/attempts`],removeRepoFromInstallation:[`DELETE /user/installations/{installation_id}/repositories/{repository_id}`,{},{renamed:[`apps`,`removeRepoFromInstallationForAuthenticatedUser`]}],removeRepoFromInstallationForAuthenticatedUser:[`DELETE /user/installations/{installation_id}/repositories/{repository_id}`],resetToken:[`PATCH /applications/{client_id}/token`],revokeInstallationAccessToken:[`DELETE /installation/token`],scopeToken:[`POST /applications/{client_id}/token/scoped`],suspendInstallation:[`PUT /app/installations/{installation_id}/suspended`],unsuspendInstallation:[`DELETE /app/installations/{installation_id}/suspended`],updateWebhookConfigForApp:[`PATCH /app/hook/config`]},billing:{getGithubActionsBillingOrg:[`GET /orgs/{org}/settings/billing/actions`],getGithubActionsBillingUser:[`GET /users/{username}/settings/billing/actions`],getGithubBillingPremiumRequestUsageReportOrg:[`GET /organizations/{org}/settings/billing/premium_request/usage`],getGithubBillingPremiumRequestUsageReportUser:[`GET /users/{username}/settings/billing/premium_request/usage`],getGithubBillingUsageReportOrg:[`GET /organizations/{org}/settings/billing/usage`],getGithubBillingUsageReportUser:[`GET /users/{username}/settings/billing/usage`],getGithubPackagesBillingOrg:[`GET /orgs/{org}/settings/billing/packages`],getGithubPackagesBillingUser:[`GET /users/{username}/settings/billing/packages`],getSharedStorageBillingOrg:[`GET /orgs/{org}/settings/billing/shared-storage`],getSharedStorageBillingUser:[`GET /users/{username}/settings/billing/shared-storage`]},campaigns:{createCampaign:[`POST /orgs/{org}/campaigns`],deleteCampaign:[`DELETE /orgs/{org}/campaigns/{campaign_number}`],getCampaignSummary:[`GET /orgs/{org}/campaigns/{campaign_number}`],listOrgCampaigns:[`GET /orgs/{org}/campaigns`],updateCampaign:[`PATCH /orgs/{org}/campaigns/{campaign_number}`]},checks:{create:[`POST /repos/{owner}/{repo}/check-runs`],createSuite:[`POST /repos/{owner}/{repo}/check-suites`],get:[`GET /repos/{owner}/{repo}/check-runs/{check_run_id}`],getSuite:[`GET /repos/{owner}/{repo}/check-suites/{check_suite_id}`],listAnnotations:[`GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations`],listForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/check-runs`],listForSuite:[`GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs`],listSuitesForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/check-suites`],rerequestRun:[`POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest`],rerequestSuite:[`POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest`],setSuitesPreferences:[`PATCH /repos/{owner}/{repo}/check-suites/preferences`],update:[`PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}`]},codeScanning:{commitAutofix:[`POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits`],createAutofix:[`POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix`],createVariantAnalysis:[`POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses`],deleteAnalysis:[`DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}`],deleteCodeqlDatabase:[`DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}`],getAlert:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}`,{},{renamedParameters:{alert_id:`alert_number`}}],getAnalysis:[`GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}`],getAutofix:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix`],getCodeqlDatabase:[`GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}`],getDefaultSetup:[`GET /repos/{owner}/{repo}/code-scanning/default-setup`],getSarif:[`GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}`],getVariantAnalysis:[`GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}`],getVariantAnalysisRepoTask:[`GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}`],listAlertInstances:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances`],listAlertsForOrg:[`GET /orgs/{org}/code-scanning/alerts`],listAlertsForRepo:[`GET /repos/{owner}/{repo}/code-scanning/alerts`],listAlertsInstances:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances`,{},{renamed:[`codeScanning`,`listAlertInstances`]}],listCodeqlDatabases:[`GET /repos/{owner}/{repo}/code-scanning/codeql/databases`],listRecentAnalyses:[`GET /repos/{owner}/{repo}/code-scanning/analyses`],updateAlert:[`PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}`],updateDefaultSetup:[`PATCH /repos/{owner}/{repo}/code-scanning/default-setup`],uploadSarif:[`POST /repos/{owner}/{repo}/code-scanning/sarifs`]},codeSecurity:{attachConfiguration:[`POST /orgs/{org}/code-security/configurations/{configuration_id}/attach`],attachEnterpriseConfiguration:[`POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach`],createConfiguration:[`POST /orgs/{org}/code-security/configurations`],createConfigurationForEnterprise:[`POST /enterprises/{enterprise}/code-security/configurations`],deleteConfiguration:[`DELETE /orgs/{org}/code-security/configurations/{configuration_id}`],deleteConfigurationForEnterprise:[`DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}`],detachConfiguration:[`DELETE /orgs/{org}/code-security/configurations/detach`],getConfiguration:[`GET /orgs/{org}/code-security/configurations/{configuration_id}`],getConfigurationForRepository:[`GET /repos/{owner}/{repo}/code-security-configuration`],getConfigurationsForEnterprise:[`GET /enterprises/{enterprise}/code-security/configurations`],getConfigurationsForOrg:[`GET /orgs/{org}/code-security/configurations`],getDefaultConfigurations:[`GET /orgs/{org}/code-security/configurations/defaults`],getDefaultConfigurationsForEnterprise:[`GET /enterprises/{enterprise}/code-security/configurations/defaults`],getRepositoriesForConfiguration:[`GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories`],getRepositoriesForEnterpriseConfiguration:[`GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories`],getSingleConfigurationForEnterprise:[`GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}`],setConfigurationAsDefault:[`PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults`],setConfigurationAsDefaultForEnterprise:[`PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults`],updateConfiguration:[`PATCH /orgs/{org}/code-security/configurations/{configuration_id}`],updateEnterpriseConfiguration:[`PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}`]},codesOfConduct:{getAllCodesOfConduct:[`GET /codes_of_conduct`],getConductCode:[`GET /codes_of_conduct/{key}`]},codespaces:{addRepositoryForSecretForAuthenticatedUser:[`PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}`],addSelectedRepoToOrgSecret:[`PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}`],checkPermissionsForDevcontainer:[`GET /repos/{owner}/{repo}/codespaces/permissions_check`],codespaceMachinesForAuthenticatedUser:[`GET /user/codespaces/{codespace_name}/machines`],createForAuthenticatedUser:[`POST /user/codespaces`],createOrUpdateOrgSecret:[`PUT /orgs/{org}/codespaces/secrets/{secret_name}`],createOrUpdateRepoSecret:[`PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}`],createOrUpdateSecretForAuthenticatedUser:[`PUT /user/codespaces/secrets/{secret_name}`],createWithPrForAuthenticatedUser:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces`],createWithRepoForAuthenticatedUser:[`POST /repos/{owner}/{repo}/codespaces`],deleteForAuthenticatedUser:[`DELETE /user/codespaces/{codespace_name}`],deleteFromOrganization:[`DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}`],deleteOrgSecret:[`DELETE /orgs/{org}/codespaces/secrets/{secret_name}`],deleteRepoSecret:[`DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}`],deleteSecretForAuthenticatedUser:[`DELETE /user/codespaces/secrets/{secret_name}`],exportForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/exports`],getCodespacesForUserInOrg:[`GET /orgs/{org}/members/{username}/codespaces`],getExportDetailsForAuthenticatedUser:[`GET /user/codespaces/{codespace_name}/exports/{export_id}`],getForAuthenticatedUser:[`GET /user/codespaces/{codespace_name}`],getOrgPublicKey:[`GET /orgs/{org}/codespaces/secrets/public-key`],getOrgSecret:[`GET /orgs/{org}/codespaces/secrets/{secret_name}`],getPublicKeyForAuthenticatedUser:[`GET /user/codespaces/secrets/public-key`],getRepoPublicKey:[`GET /repos/{owner}/{repo}/codespaces/secrets/public-key`],getRepoSecret:[`GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}`],getSecretForAuthenticatedUser:[`GET /user/codespaces/secrets/{secret_name}`],listDevcontainersInRepositoryForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces/devcontainers`],listForAuthenticatedUser:[`GET /user/codespaces`],listInOrganization:[`GET /orgs/{org}/codespaces`,{},{renamedParameters:{org_id:`org`}}],listInRepositoryForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces`],listOrgSecrets:[`GET /orgs/{org}/codespaces/secrets`],listRepoSecrets:[`GET /repos/{owner}/{repo}/codespaces/secrets`],listRepositoriesForSecretForAuthenticatedUser:[`GET /user/codespaces/secrets/{secret_name}/repositories`],listSecretsForAuthenticatedUser:[`GET /user/codespaces/secrets`],listSelectedReposForOrgSecret:[`GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories`],preFlightWithRepoForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces/new`],publishForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/publish`],removeRepositoryForSecretForAuthenticatedUser:[`DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}`],removeSelectedRepoFromOrgSecret:[`DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}`],repoMachinesForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces/machines`],setRepositoriesForSecretForAuthenticatedUser:[`PUT /user/codespaces/secrets/{secret_name}/repositories`],setSelectedReposForOrgSecret:[`PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories`],startForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/start`],stopForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/stop`],stopInOrganization:[`POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop`],updateForAuthenticatedUser:[`PATCH /user/codespaces/{codespace_name}`]},copilot:{addCopilotSeatsForTeams:[`POST /orgs/{org}/copilot/billing/selected_teams`],addCopilotSeatsForUsers:[`POST /orgs/{org}/copilot/billing/selected_users`],cancelCopilotSeatAssignmentForTeams:[`DELETE /orgs/{org}/copilot/billing/selected_teams`],cancelCopilotSeatAssignmentForUsers:[`DELETE /orgs/{org}/copilot/billing/selected_users`],copilotMetricsForOrganization:[`GET /orgs/{org}/copilot/metrics`],copilotMetricsForTeam:[`GET /orgs/{org}/team/{team_slug}/copilot/metrics`],getCopilotOrganizationDetails:[`GET /orgs/{org}/copilot/billing`],getCopilotSeatDetailsForUser:[`GET /orgs/{org}/members/{username}/copilot`],listCopilotSeats:[`GET /orgs/{org}/copilot/billing/seats`]},credentials:{revoke:[`POST /credentials/revoke`]},dependabot:{addSelectedRepoToOrgSecret:[`PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}`],createOrUpdateOrgSecret:[`PUT /orgs/{org}/dependabot/secrets/{secret_name}`],createOrUpdateRepoSecret:[`PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}`],deleteOrgSecret:[`DELETE /orgs/{org}/dependabot/secrets/{secret_name}`],deleteRepoSecret:[`DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}`],getAlert:[`GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}`],getOrgPublicKey:[`GET /orgs/{org}/dependabot/secrets/public-key`],getOrgSecret:[`GET /orgs/{org}/dependabot/secrets/{secret_name}`],getRepoPublicKey:[`GET /repos/{owner}/{repo}/dependabot/secrets/public-key`],getRepoSecret:[`GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}`],listAlertsForEnterprise:[`GET /enterprises/{enterprise}/dependabot/alerts`],listAlertsForOrg:[`GET /orgs/{org}/dependabot/alerts`],listAlertsForRepo:[`GET /repos/{owner}/{repo}/dependabot/alerts`],listOrgSecrets:[`GET /orgs/{org}/dependabot/secrets`],listRepoSecrets:[`GET /repos/{owner}/{repo}/dependabot/secrets`],listSelectedReposForOrgSecret:[`GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories`],removeSelectedRepoFromOrgSecret:[`DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}`],repositoryAccessForOrg:[`GET /organizations/{org}/dependabot/repository-access`],setRepositoryAccessDefaultLevel:[`PUT /organizations/{org}/dependabot/repository-access/default-level`],setSelectedReposForOrgSecret:[`PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories`],updateAlert:[`PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}`],updateRepositoryAccessForOrg:[`PATCH /organizations/{org}/dependabot/repository-access`]},dependencyGraph:{createRepositorySnapshot:[`POST /repos/{owner}/{repo}/dependency-graph/snapshots`],diffRange:[`GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}`],exportSbom:[`GET /repos/{owner}/{repo}/dependency-graph/sbom`]},emojis:{get:[`GET /emojis`]},enterpriseTeamMemberships:{add:[`PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}`],bulkAdd:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add`],bulkRemove:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove`],get:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}`],list:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships`],remove:[`DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}`]},enterpriseTeamOrganizations:{add:[`PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}`],bulkAdd:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add`],bulkRemove:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove`],delete:[`DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}`],getAssignment:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}`],getAssignments:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations`]},enterpriseTeams:{create:[`POST /enterprises/{enterprise}/teams`],delete:[`DELETE /enterprises/{enterprise}/teams/{team_slug}`],get:[`GET /enterprises/{enterprise}/teams/{team_slug}`],list:[`GET /enterprises/{enterprise}/teams`],update:[`PATCH /enterprises/{enterprise}/teams/{team_slug}`]},gists:{checkIsStarred:[`GET /gists/{gist_id}/star`],create:[`POST /gists`],createComment:[`POST /gists/{gist_id}/comments`],delete:[`DELETE /gists/{gist_id}`],deleteComment:[`DELETE /gists/{gist_id}/comments/{comment_id}`],fork:[`POST /gists/{gist_id}/forks`],get:[`GET /gists/{gist_id}`],getComment:[`GET /gists/{gist_id}/comments/{comment_id}`],getRevision:[`GET /gists/{gist_id}/{sha}`],list:[`GET /gists`],listComments:[`GET /gists/{gist_id}/comments`],listCommits:[`GET /gists/{gist_id}/commits`],listForUser:[`GET /users/{username}/gists`],listForks:[`GET /gists/{gist_id}/forks`],listPublic:[`GET /gists/public`],listStarred:[`GET /gists/starred`],star:[`PUT /gists/{gist_id}/star`],unstar:[`DELETE /gists/{gist_id}/star`],update:[`PATCH /gists/{gist_id}`],updateComment:[`PATCH /gists/{gist_id}/comments/{comment_id}`]},git:{createBlob:[`POST /repos/{owner}/{repo}/git/blobs`],createCommit:[`POST /repos/{owner}/{repo}/git/commits`],createRef:[`POST /repos/{owner}/{repo}/git/refs`],createTag:[`POST /repos/{owner}/{repo}/git/tags`],createTree:[`POST /repos/{owner}/{repo}/git/trees`],deleteRef:[`DELETE /repos/{owner}/{repo}/git/refs/{ref}`],getBlob:[`GET /repos/{owner}/{repo}/git/blobs/{file_sha}`],getCommit:[`GET /repos/{owner}/{repo}/git/commits/{commit_sha}`],getRef:[`GET /repos/{owner}/{repo}/git/ref/{ref}`],getTag:[`GET /repos/{owner}/{repo}/git/tags/{tag_sha}`],getTree:[`GET /repos/{owner}/{repo}/git/trees/{tree_sha}`],listMatchingRefs:[`GET /repos/{owner}/{repo}/git/matching-refs/{ref}`],updateRef:[`PATCH /repos/{owner}/{repo}/git/refs/{ref}`]},gitignore:{getAllTemplates:[`GET /gitignore/templates`],getTemplate:[`GET /gitignore/templates/{name}`]},hostedCompute:{createNetworkConfigurationForOrg:[`POST /orgs/{org}/settings/network-configurations`],deleteNetworkConfigurationFromOrg:[`DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}`],getNetworkConfigurationForOrg:[`GET /orgs/{org}/settings/network-configurations/{network_configuration_id}`],getNetworkSettingsForOrg:[`GET /orgs/{org}/settings/network-settings/{network_settings_id}`],listNetworkConfigurationsForOrg:[`GET /orgs/{org}/settings/network-configurations`],updateNetworkConfigurationForOrg:[`PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}`]},interactions:{getRestrictionsForAuthenticatedUser:[`GET /user/interaction-limits`],getRestrictionsForOrg:[`GET /orgs/{org}/interaction-limits`],getRestrictionsForRepo:[`GET /repos/{owner}/{repo}/interaction-limits`],getRestrictionsForYourPublicRepos:[`GET /user/interaction-limits`,{},{renamed:[`interactions`,`getRestrictionsForAuthenticatedUser`]}],removeRestrictionsForAuthenticatedUser:[`DELETE /user/interaction-limits`],removeRestrictionsForOrg:[`DELETE /orgs/{org}/interaction-limits`],removeRestrictionsForRepo:[`DELETE /repos/{owner}/{repo}/interaction-limits`],removeRestrictionsForYourPublicRepos:[`DELETE /user/interaction-limits`,{},{renamed:[`interactions`,`removeRestrictionsForAuthenticatedUser`]}],setRestrictionsForAuthenticatedUser:[`PUT /user/interaction-limits`],setRestrictionsForOrg:[`PUT /orgs/{org}/interaction-limits`],setRestrictionsForRepo:[`PUT /repos/{owner}/{repo}/interaction-limits`],setRestrictionsForYourPublicRepos:[`PUT /user/interaction-limits`,{},{renamed:[`interactions`,`setRestrictionsForAuthenticatedUser`]}]},issues:{addAssignees:[`POST /repos/{owner}/{repo}/issues/{issue_number}/assignees`],addBlockedByDependency:[`POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by`],addLabels:[`POST /repos/{owner}/{repo}/issues/{issue_number}/labels`],addSubIssue:[`POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues`],checkUserCanBeAssigned:[`GET /repos/{owner}/{repo}/assignees/{assignee}`],checkUserCanBeAssignedToIssue:[`GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}`],create:[`POST /repos/{owner}/{repo}/issues`],createComment:[`POST /repos/{owner}/{repo}/issues/{issue_number}/comments`],createLabel:[`POST /repos/{owner}/{repo}/labels`],createMilestone:[`POST /repos/{owner}/{repo}/milestones`],deleteComment:[`DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}`],deleteLabel:[`DELETE /repos/{owner}/{repo}/labels/{name}`],deleteMilestone:[`DELETE /repos/{owner}/{repo}/milestones/{milestone_number}`],get:[`GET /repos/{owner}/{repo}/issues/{issue_number}`],getComment:[`GET /repos/{owner}/{repo}/issues/comments/{comment_id}`],getEvent:[`GET /repos/{owner}/{repo}/issues/events/{event_id}`],getLabel:[`GET /repos/{owner}/{repo}/labels/{name}`],getMilestone:[`GET /repos/{owner}/{repo}/milestones/{milestone_number}`],getParent:[`GET /repos/{owner}/{repo}/issues/{issue_number}/parent`],list:[`GET /issues`],listAssignees:[`GET /repos/{owner}/{repo}/assignees`],listComments:[`GET /repos/{owner}/{repo}/issues/{issue_number}/comments`],listCommentsForRepo:[`GET /repos/{owner}/{repo}/issues/comments`],listDependenciesBlockedBy:[`GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by`],listDependenciesBlocking:[`GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking`],listEvents:[`GET /repos/{owner}/{repo}/issues/{issue_number}/events`],listEventsForRepo:[`GET /repos/{owner}/{repo}/issues/events`],listEventsForTimeline:[`GET /repos/{owner}/{repo}/issues/{issue_number}/timeline`],listForAuthenticatedUser:[`GET /user/issues`],listForOrg:[`GET /orgs/{org}/issues`],listForRepo:[`GET /repos/{owner}/{repo}/issues`],listLabelsForMilestone:[`GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels`],listLabelsForRepo:[`GET /repos/{owner}/{repo}/labels`],listLabelsOnIssue:[`GET /repos/{owner}/{repo}/issues/{issue_number}/labels`],listMilestones:[`GET /repos/{owner}/{repo}/milestones`],listSubIssues:[`GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues`],lock:[`PUT /repos/{owner}/{repo}/issues/{issue_number}/lock`],removeAllLabels:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels`],removeAssignees:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees`],removeDependencyBlockedBy:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}`],removeLabel:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}`],removeSubIssue:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue`],reprioritizeSubIssue:[`PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority`],setLabels:[`PUT /repos/{owner}/{repo}/issues/{issue_number}/labels`],unlock:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock`],update:[`PATCH /repos/{owner}/{repo}/issues/{issue_number}`],updateComment:[`PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}`],updateLabel:[`PATCH /repos/{owner}/{repo}/labels/{name}`],updateMilestone:[`PATCH /repos/{owner}/{repo}/milestones/{milestone_number}`]},licenses:{get:[`GET /licenses/{license}`],getAllCommonlyUsed:[`GET /licenses`],getForRepo:[`GET /repos/{owner}/{repo}/license`]},markdown:{render:[`POST /markdown`],renderRaw:[`POST /markdown/raw`,{headers:{"content-type":`text/plain; charset=utf-8`}}]},meta:{get:[`GET /meta`],getAllVersions:[`GET /versions`],getOctocat:[`GET /octocat`],getZen:[`GET /zen`],root:[`GET /`]},migrations:{deleteArchiveForAuthenticatedUser:[`DELETE /user/migrations/{migration_id}/archive`],deleteArchiveForOrg:[`DELETE /orgs/{org}/migrations/{migration_id}/archive`],downloadArchiveForOrg:[`GET /orgs/{org}/migrations/{migration_id}/archive`],getArchiveForAuthenticatedUser:[`GET /user/migrations/{migration_id}/archive`],getStatusForAuthenticatedUser:[`GET /user/migrations/{migration_id}`],getStatusForOrg:[`GET /orgs/{org}/migrations/{migration_id}`],listForAuthenticatedUser:[`GET /user/migrations`],listForOrg:[`GET /orgs/{org}/migrations`],listReposForAuthenticatedUser:[`GET /user/migrations/{migration_id}/repositories`],listReposForOrg:[`GET /orgs/{org}/migrations/{migration_id}/repositories`],listReposForUser:[`GET /user/migrations/{migration_id}/repositories`,{},{renamed:[`migrations`,`listReposForAuthenticatedUser`]}],startForAuthenticatedUser:[`POST /user/migrations`],startForOrg:[`POST /orgs/{org}/migrations`],unlockRepoForAuthenticatedUser:[`DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock`],unlockRepoForOrg:[`DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock`]},oidc:{getOidcCustomSubTemplateForOrg:[`GET /orgs/{org}/actions/oidc/customization/sub`],updateOidcCustomSubTemplateForOrg:[`PUT /orgs/{org}/actions/oidc/customization/sub`]},orgs:{addSecurityManagerTeam:[`PUT /orgs/{org}/security-managers/teams/{team_slug}`,{},{deprecated:`octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team`}],assignTeamToOrgRole:[`PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}`],assignUserToOrgRole:[`PUT /orgs/{org}/organization-roles/users/{username}/{role_id}`],blockUser:[`PUT /orgs/{org}/blocks/{username}`],cancelInvitation:[`DELETE /orgs/{org}/invitations/{invitation_id}`],checkBlockedUser:[`GET /orgs/{org}/blocks/{username}`],checkMembershipForUser:[`GET /orgs/{org}/members/{username}`],checkPublicMembershipForUser:[`GET /orgs/{org}/public_members/{username}`],convertMemberToOutsideCollaborator:[`PUT /orgs/{org}/outside_collaborators/{username}`],createArtifactStorageRecord:[`POST /orgs/{org}/artifacts/metadata/storage-record`],createInvitation:[`POST /orgs/{org}/invitations`],createIssueType:[`POST /orgs/{org}/issue-types`],createWebhook:[`POST /orgs/{org}/hooks`],customPropertiesForOrgsCreateOrUpdateOrganizationValues:[`PATCH /organizations/{org}/org-properties/values`],customPropertiesForOrgsGetOrganizationValues:[`GET /organizations/{org}/org-properties/values`],customPropertiesForReposCreateOrUpdateOrganizationDefinition:[`PUT /orgs/{org}/properties/schema/{custom_property_name}`],customPropertiesForReposCreateOrUpdateOrganizationDefinitions:[`PATCH /orgs/{org}/properties/schema`],customPropertiesForReposCreateOrUpdateOrganizationValues:[`PATCH /orgs/{org}/properties/values`],customPropertiesForReposDeleteOrganizationDefinition:[`DELETE /orgs/{org}/properties/schema/{custom_property_name}`],customPropertiesForReposGetOrganizationDefinition:[`GET /orgs/{org}/properties/schema/{custom_property_name}`],customPropertiesForReposGetOrganizationDefinitions:[`GET /orgs/{org}/properties/schema`],customPropertiesForReposGetOrganizationValues:[`GET /orgs/{org}/properties/values`],delete:[`DELETE /orgs/{org}`],deleteAttestationsBulk:[`POST /orgs/{org}/attestations/delete-request`],deleteAttestationsById:[`DELETE /orgs/{org}/attestations/{attestation_id}`],deleteAttestationsBySubjectDigest:[`DELETE /orgs/{org}/attestations/digest/{subject_digest}`],deleteIssueType:[`DELETE /orgs/{org}/issue-types/{issue_type_id}`],deleteWebhook:[`DELETE /orgs/{org}/hooks/{hook_id}`],disableSelectedRepositoryImmutableReleasesOrganization:[`DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}`],enableSelectedRepositoryImmutableReleasesOrganization:[`PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}`],get:[`GET /orgs/{org}`],getImmutableReleasesSettings:[`GET /orgs/{org}/settings/immutable-releases`],getImmutableReleasesSettingsRepositories:[`GET /orgs/{org}/settings/immutable-releases/repositories`],getMembershipForAuthenticatedUser:[`GET /user/memberships/orgs/{org}`],getMembershipForUser:[`GET /orgs/{org}/memberships/{username}`],getOrgRole:[`GET /orgs/{org}/organization-roles/{role_id}`],getOrgRulesetHistory:[`GET /orgs/{org}/rulesets/{ruleset_id}/history`],getOrgRulesetVersion:[`GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}`],getWebhook:[`GET /orgs/{org}/hooks/{hook_id}`],getWebhookConfigForOrg:[`GET /orgs/{org}/hooks/{hook_id}/config`],getWebhookDelivery:[`GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}`],list:[`GET /organizations`],listAppInstallations:[`GET /orgs/{org}/installations`],listArtifactStorageRecords:[`GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records`],listAttestationRepositories:[`GET /orgs/{org}/attestations/repositories`],listAttestations:[`GET /orgs/{org}/attestations/{subject_digest}`],listAttestationsBulk:[`POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}`],listBlockedUsers:[`GET /orgs/{org}/blocks`],listFailedInvitations:[`GET /orgs/{org}/failed_invitations`],listForAuthenticatedUser:[`GET /user/orgs`],listForUser:[`GET /users/{username}/orgs`],listInvitationTeams:[`GET /orgs/{org}/invitations/{invitation_id}/teams`],listIssueTypes:[`GET /orgs/{org}/issue-types`],listMembers:[`GET /orgs/{org}/members`],listMembershipsForAuthenticatedUser:[`GET /user/memberships/orgs`],listOrgRoleTeams:[`GET /orgs/{org}/organization-roles/{role_id}/teams`],listOrgRoleUsers:[`GET /orgs/{org}/organization-roles/{role_id}/users`],listOrgRoles:[`GET /orgs/{org}/organization-roles`],listOrganizationFineGrainedPermissions:[`GET /orgs/{org}/organization-fine-grained-permissions`],listOutsideCollaborators:[`GET /orgs/{org}/outside_collaborators`],listPatGrantRepositories:[`GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories`],listPatGrantRequestRepositories:[`GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories`],listPatGrantRequests:[`GET /orgs/{org}/personal-access-token-requests`],listPatGrants:[`GET /orgs/{org}/personal-access-tokens`],listPendingInvitations:[`GET /orgs/{org}/invitations`],listPublicMembers:[`GET /orgs/{org}/public_members`],listSecurityManagerTeams:[`GET /orgs/{org}/security-managers`,{},{deprecated:`octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams`}],listWebhookDeliveries:[`GET /orgs/{org}/hooks/{hook_id}/deliveries`],listWebhooks:[`GET /orgs/{org}/hooks`],pingWebhook:[`POST /orgs/{org}/hooks/{hook_id}/pings`],redeliverWebhookDelivery:[`POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts`],removeMember:[`DELETE /orgs/{org}/members/{username}`],removeMembershipForUser:[`DELETE /orgs/{org}/memberships/{username}`],removeOutsideCollaborator:[`DELETE /orgs/{org}/outside_collaborators/{username}`],removePublicMembershipForAuthenticatedUser:[`DELETE /orgs/{org}/public_members/{username}`],removeSecurityManagerTeam:[`DELETE /orgs/{org}/security-managers/teams/{team_slug}`,{},{deprecated:`octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team`}],reviewPatGrantRequest:[`POST /orgs/{org}/personal-access-token-requests/{pat_request_id}`],reviewPatGrantRequestsInBulk:[`POST /orgs/{org}/personal-access-token-requests`],revokeAllOrgRolesTeam:[`DELETE /orgs/{org}/organization-roles/teams/{team_slug}`],revokeAllOrgRolesUser:[`DELETE /orgs/{org}/organization-roles/users/{username}`],revokeOrgRoleTeam:[`DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}`],revokeOrgRoleUser:[`DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}`],setImmutableReleasesSettings:[`PUT /orgs/{org}/settings/immutable-releases`],setImmutableReleasesSettingsRepositories:[`PUT /orgs/{org}/settings/immutable-releases/repositories`],setMembershipForUser:[`PUT /orgs/{org}/memberships/{username}`],setPublicMembershipForAuthenticatedUser:[`PUT /orgs/{org}/public_members/{username}`],unblockUser:[`DELETE /orgs/{org}/blocks/{username}`],update:[`PATCH /orgs/{org}`],updateIssueType:[`PUT /orgs/{org}/issue-types/{issue_type_id}`],updateMembershipForAuthenticatedUser:[`PATCH /user/memberships/orgs/{org}`],updatePatAccess:[`POST /orgs/{org}/personal-access-tokens/{pat_id}`],updatePatAccesses:[`POST /orgs/{org}/personal-access-tokens`],updateWebhook:[`PATCH /orgs/{org}/hooks/{hook_id}`],updateWebhookConfigForOrg:[`PATCH /orgs/{org}/hooks/{hook_id}/config`]},packages:{deletePackageForAuthenticatedUser:[`DELETE /user/packages/{package_type}/{package_name}`],deletePackageForOrg:[`DELETE /orgs/{org}/packages/{package_type}/{package_name}`],deletePackageForUser:[`DELETE /users/{username}/packages/{package_type}/{package_name}`],deletePackageVersionForAuthenticatedUser:[`DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}`],deletePackageVersionForOrg:[`DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}`],deletePackageVersionForUser:[`DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}`],getAllPackageVersionsForAPackageOwnedByAnOrg:[`GET /orgs/{org}/packages/{package_type}/{package_name}/versions`,{},{renamed:[`packages`,`getAllPackageVersionsForPackageOwnedByOrg`]}],getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}/versions`,{},{renamed:[`packages`,`getAllPackageVersionsForPackageOwnedByAuthenticatedUser`]}],getAllPackageVersionsForPackageOwnedByAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}/versions`],getAllPackageVersionsForPackageOwnedByOrg:[`GET /orgs/{org}/packages/{package_type}/{package_name}/versions`],getAllPackageVersionsForPackageOwnedByUser:[`GET /users/{username}/packages/{package_type}/{package_name}/versions`],getPackageForAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}`],getPackageForOrganization:[`GET /orgs/{org}/packages/{package_type}/{package_name}`],getPackageForUser:[`GET /users/{username}/packages/{package_type}/{package_name}`],getPackageVersionForAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}`],getPackageVersionForOrganization:[`GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}`],getPackageVersionForUser:[`GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}`],listDockerMigrationConflictingPackagesForAuthenticatedUser:[`GET /user/docker/conflicts`],listDockerMigrationConflictingPackagesForOrganization:[`GET /orgs/{org}/docker/conflicts`],listDockerMigrationConflictingPackagesForUser:[`GET /users/{username}/docker/conflicts`],listPackagesForAuthenticatedUser:[`GET /user/packages`],listPackagesForOrganization:[`GET /orgs/{org}/packages`],listPackagesForUser:[`GET /users/{username}/packages`],restorePackageForAuthenticatedUser:[`POST /user/packages/{package_type}/{package_name}/restore{?token}`],restorePackageForOrg:[`POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}`],restorePackageForUser:[`POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}`],restorePackageVersionForAuthenticatedUser:[`POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore`],restorePackageVersionForOrg:[`POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore`],restorePackageVersionForUser:[`POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore`]},privateRegistries:{createOrgPrivateRegistry:[`POST /orgs/{org}/private-registries`],deleteOrgPrivateRegistry:[`DELETE /orgs/{org}/private-registries/{secret_name}`],getOrgPrivateRegistry:[`GET /orgs/{org}/private-registries/{secret_name}`],getOrgPublicKey:[`GET /orgs/{org}/private-registries/public-key`],listOrgPrivateRegistries:[`GET /orgs/{org}/private-registries`],updateOrgPrivateRegistry:[`PATCH /orgs/{org}/private-registries/{secret_name}`]},projects:{addItemForOrg:[`POST /orgs/{org}/projectsV2/{project_number}/items`],addItemForUser:[`POST /users/{username}/projectsV2/{project_number}/items`],deleteItemForOrg:[`DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}`],deleteItemForUser:[`DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}`],getFieldForOrg:[`GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}`],getFieldForUser:[`GET /users/{username}/projectsV2/{project_number}/fields/{field_id}`],getForOrg:[`GET /orgs/{org}/projectsV2/{project_number}`],getForUser:[`GET /users/{username}/projectsV2/{project_number}`],getOrgItem:[`GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}`],getUserItem:[`GET /users/{username}/projectsV2/{project_number}/items/{item_id}`],listFieldsForOrg:[`GET /orgs/{org}/projectsV2/{project_number}/fields`],listFieldsForUser:[`GET /users/{username}/projectsV2/{project_number}/fields`],listForOrg:[`GET /orgs/{org}/projectsV2`],listForUser:[`GET /users/{username}/projectsV2`],listItemsForOrg:[`GET /orgs/{org}/projectsV2/{project_number}/items`],listItemsForUser:[`GET /users/{username}/projectsV2/{project_number}/items`],updateItemForOrg:[`PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}`],updateItemForUser:[`PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}`]},pulls:{checkIfMerged:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/merge`],create:[`POST /repos/{owner}/{repo}/pulls`],createReplyForReviewComment:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies`],createReview:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews`],createReviewComment:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/comments`],deletePendingReview:[`DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}`],deleteReviewComment:[`DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}`],dismissReview:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals`],get:[`GET /repos/{owner}/{repo}/pulls/{pull_number}`],getReview:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}`],getReviewComment:[`GET /repos/{owner}/{repo}/pulls/comments/{comment_id}`],list:[`GET /repos/{owner}/{repo}/pulls`],listCommentsForReview:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments`],listCommits:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/commits`],listFiles:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/files`],listRequestedReviewers:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`],listReviewComments:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/comments`],listReviewCommentsForRepo:[`GET /repos/{owner}/{repo}/pulls/comments`],listReviews:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews`],merge:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge`],removeRequestedReviewers:[`DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`],requestReviewers:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`],submitReview:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events`],update:[`PATCH /repos/{owner}/{repo}/pulls/{pull_number}`],updateBranch:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch`],updateReview:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}`],updateReviewComment:[`PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}`]},rateLimit:{get:[`GET /rate_limit`]},reactions:{createForCommitComment:[`POST /repos/{owner}/{repo}/comments/{comment_id}/reactions`],createForIssue:[`POST /repos/{owner}/{repo}/issues/{issue_number}/reactions`],createForIssueComment:[`POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions`],createForPullRequestReviewComment:[`POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions`],createForRelease:[`POST /repos/{owner}/{repo}/releases/{release_id}/reactions`],createForTeamDiscussionCommentInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions`],createForTeamDiscussionInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions`],deleteForCommitComment:[`DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}`],deleteForIssue:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}`],deleteForIssueComment:[`DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}`],deleteForPullRequestComment:[`DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}`],deleteForRelease:[`DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}`],deleteForTeamDiscussion:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}`],deleteForTeamDiscussionComment:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}`],listForCommitComment:[`GET /repos/{owner}/{repo}/comments/{comment_id}/reactions`],listForIssue:[`GET /repos/{owner}/{repo}/issues/{issue_number}/reactions`],listForIssueComment:[`GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions`],listForPullRequestReviewComment:[`GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions`],listForRelease:[`GET /repos/{owner}/{repo}/releases/{release_id}/reactions`],listForTeamDiscussionCommentInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions`],listForTeamDiscussionInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions`]},repos:{acceptInvitation:[`PATCH /user/repository_invitations/{invitation_id}`,{},{renamed:[`repos`,`acceptInvitationForAuthenticatedUser`]}],acceptInvitationForAuthenticatedUser:[`PATCH /user/repository_invitations/{invitation_id}`],addAppAccessRestrictions:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`,{},{mapToData:`apps`}],addCollaborator:[`PUT /repos/{owner}/{repo}/collaborators/{username}`],addStatusCheckContexts:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`,{},{mapToData:`contexts`}],addTeamAccessRestrictions:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`,{},{mapToData:`teams`}],addUserAccessRestrictions:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`,{},{mapToData:`users`}],cancelPagesDeployment:[`POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel`],checkAutomatedSecurityFixes:[`GET /repos/{owner}/{repo}/automated-security-fixes`],checkCollaborator:[`GET /repos/{owner}/{repo}/collaborators/{username}`],checkImmutableReleases:[`GET /repos/{owner}/{repo}/immutable-releases`],checkPrivateVulnerabilityReporting:[`GET /repos/{owner}/{repo}/private-vulnerability-reporting`],checkVulnerabilityAlerts:[`GET /repos/{owner}/{repo}/vulnerability-alerts`],codeownersErrors:[`GET /repos/{owner}/{repo}/codeowners/errors`],compareCommits:[`GET /repos/{owner}/{repo}/compare/{base}...{head}`],compareCommitsWithBasehead:[`GET /repos/{owner}/{repo}/compare/{basehead}`],createAttestation:[`POST /repos/{owner}/{repo}/attestations`],createAutolink:[`POST /repos/{owner}/{repo}/autolinks`],createCommitComment:[`POST /repos/{owner}/{repo}/commits/{commit_sha}/comments`],createCommitSignatureProtection:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures`],createCommitStatus:[`POST /repos/{owner}/{repo}/statuses/{sha}`],createDeployKey:[`POST /repos/{owner}/{repo}/keys`],createDeployment:[`POST /repos/{owner}/{repo}/deployments`],createDeploymentBranchPolicy:[`POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies`],createDeploymentProtectionRule:[`POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules`],createDeploymentStatus:[`POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses`],createDispatchEvent:[`POST /repos/{owner}/{repo}/dispatches`],createForAuthenticatedUser:[`POST /user/repos`],createFork:[`POST /repos/{owner}/{repo}/forks`],createInOrg:[`POST /orgs/{org}/repos`],createOrUpdateEnvironment:[`PUT /repos/{owner}/{repo}/environments/{environment_name}`],createOrUpdateFileContents:[`PUT /repos/{owner}/{repo}/contents/{path}`],createOrgRuleset:[`POST /orgs/{org}/rulesets`],createPagesDeployment:[`POST /repos/{owner}/{repo}/pages/deployments`],createPagesSite:[`POST /repos/{owner}/{repo}/pages`],createRelease:[`POST /repos/{owner}/{repo}/releases`],createRepoRuleset:[`POST /repos/{owner}/{repo}/rulesets`],createUsingTemplate:[`POST /repos/{template_owner}/{template_repo}/generate`],createWebhook:[`POST /repos/{owner}/{repo}/hooks`],customPropertiesForReposCreateOrUpdateRepositoryValues:[`PATCH /repos/{owner}/{repo}/properties/values`],customPropertiesForReposGetRepositoryValues:[`GET /repos/{owner}/{repo}/properties/values`],declineInvitation:[`DELETE /user/repository_invitations/{invitation_id}`,{},{renamed:[`repos`,`declineInvitationForAuthenticatedUser`]}],declineInvitationForAuthenticatedUser:[`DELETE /user/repository_invitations/{invitation_id}`],delete:[`DELETE /repos/{owner}/{repo}`],deleteAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions`],deleteAdminBranchProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins`],deleteAnEnvironment:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}`],deleteAutolink:[`DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}`],deleteBranchProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection`],deleteCommitComment:[`DELETE /repos/{owner}/{repo}/comments/{comment_id}`],deleteCommitSignatureProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures`],deleteDeployKey:[`DELETE /repos/{owner}/{repo}/keys/{key_id}`],deleteDeployment:[`DELETE /repos/{owner}/{repo}/deployments/{deployment_id}`],deleteDeploymentBranchPolicy:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}`],deleteFile:[`DELETE /repos/{owner}/{repo}/contents/{path}`],deleteInvitation:[`DELETE /repos/{owner}/{repo}/invitations/{invitation_id}`],deleteOrgRuleset:[`DELETE /orgs/{org}/rulesets/{ruleset_id}`],deletePagesSite:[`DELETE /repos/{owner}/{repo}/pages`],deletePullRequestReviewProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews`],deleteRelease:[`DELETE /repos/{owner}/{repo}/releases/{release_id}`],deleteReleaseAsset:[`DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}`],deleteRepoRuleset:[`DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}`],deleteWebhook:[`DELETE /repos/{owner}/{repo}/hooks/{hook_id}`],disableAutomatedSecurityFixes:[`DELETE /repos/{owner}/{repo}/automated-security-fixes`],disableDeploymentProtectionRule:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}`],disableImmutableReleases:[`DELETE /repos/{owner}/{repo}/immutable-releases`],disablePrivateVulnerabilityReporting:[`DELETE /repos/{owner}/{repo}/private-vulnerability-reporting`],disableVulnerabilityAlerts:[`DELETE /repos/{owner}/{repo}/vulnerability-alerts`],downloadArchive:[`GET /repos/{owner}/{repo}/zipball/{ref}`,{},{renamed:[`repos`,`downloadZipballArchive`]}],downloadTarballArchive:[`GET /repos/{owner}/{repo}/tarball/{ref}`],downloadZipballArchive:[`GET /repos/{owner}/{repo}/zipball/{ref}`],enableAutomatedSecurityFixes:[`PUT /repos/{owner}/{repo}/automated-security-fixes`],enableImmutableReleases:[`PUT /repos/{owner}/{repo}/immutable-releases`],enablePrivateVulnerabilityReporting:[`PUT /repos/{owner}/{repo}/private-vulnerability-reporting`],enableVulnerabilityAlerts:[`PUT /repos/{owner}/{repo}/vulnerability-alerts`],generateReleaseNotes:[`POST /repos/{owner}/{repo}/releases/generate-notes`],get:[`GET /repos/{owner}/{repo}`],getAccessRestrictions:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions`],getAdminBranchProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins`],getAllDeploymentProtectionRules:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules`],getAllEnvironments:[`GET /repos/{owner}/{repo}/environments`],getAllStatusCheckContexts:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`],getAllTopics:[`GET /repos/{owner}/{repo}/topics`],getAppsWithAccessToProtectedBranch:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`],getAutolink:[`GET /repos/{owner}/{repo}/autolinks/{autolink_id}`],getBranch:[`GET /repos/{owner}/{repo}/branches/{branch}`],getBranchProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection`],getBranchRules:[`GET /repos/{owner}/{repo}/rules/branches/{branch}`],getClones:[`GET /repos/{owner}/{repo}/traffic/clones`],getCodeFrequencyStats:[`GET /repos/{owner}/{repo}/stats/code_frequency`],getCollaboratorPermissionLevel:[`GET /repos/{owner}/{repo}/collaborators/{username}/permission`],getCombinedStatusForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/status`],getCommit:[`GET /repos/{owner}/{repo}/commits/{ref}`],getCommitActivityStats:[`GET /repos/{owner}/{repo}/stats/commit_activity`],getCommitComment:[`GET /repos/{owner}/{repo}/comments/{comment_id}`],getCommitSignatureProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures`],getCommunityProfileMetrics:[`GET /repos/{owner}/{repo}/community/profile`],getContent:[`GET /repos/{owner}/{repo}/contents/{path}`],getContributorsStats:[`GET /repos/{owner}/{repo}/stats/contributors`],getCustomDeploymentProtectionRule:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}`],getDeployKey:[`GET /repos/{owner}/{repo}/keys/{key_id}`],getDeployment:[`GET /repos/{owner}/{repo}/deployments/{deployment_id}`],getDeploymentBranchPolicy:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}`],getDeploymentStatus:[`GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}`],getEnvironment:[`GET /repos/{owner}/{repo}/environments/{environment_name}`],getLatestPagesBuild:[`GET /repos/{owner}/{repo}/pages/builds/latest`],getLatestRelease:[`GET /repos/{owner}/{repo}/releases/latest`],getOrgRuleSuite:[`GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}`],getOrgRuleSuites:[`GET /orgs/{org}/rulesets/rule-suites`],getOrgRuleset:[`GET /orgs/{org}/rulesets/{ruleset_id}`],getOrgRulesets:[`GET /orgs/{org}/rulesets`],getPages:[`GET /repos/{owner}/{repo}/pages`],getPagesBuild:[`GET /repos/{owner}/{repo}/pages/builds/{build_id}`],getPagesDeployment:[`GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}`],getPagesHealthCheck:[`GET /repos/{owner}/{repo}/pages/health`],getParticipationStats:[`GET /repos/{owner}/{repo}/stats/participation`],getPullRequestReviewProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews`],getPunchCardStats:[`GET /repos/{owner}/{repo}/stats/punch_card`],getReadme:[`GET /repos/{owner}/{repo}/readme`],getReadmeInDirectory:[`GET /repos/{owner}/{repo}/readme/{dir}`],getRelease:[`GET /repos/{owner}/{repo}/releases/{release_id}`],getReleaseAsset:[`GET /repos/{owner}/{repo}/releases/assets/{asset_id}`],getReleaseByTag:[`GET /repos/{owner}/{repo}/releases/tags/{tag}`],getRepoRuleSuite:[`GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}`],getRepoRuleSuites:[`GET /repos/{owner}/{repo}/rulesets/rule-suites`],getRepoRuleset:[`GET /repos/{owner}/{repo}/rulesets/{ruleset_id}`],getRepoRulesetHistory:[`GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history`],getRepoRulesetVersion:[`GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}`],getRepoRulesets:[`GET /repos/{owner}/{repo}/rulesets`],getStatusChecksProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`],getTeamsWithAccessToProtectedBranch:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`],getTopPaths:[`GET /repos/{owner}/{repo}/traffic/popular/paths`],getTopReferrers:[`GET /repos/{owner}/{repo}/traffic/popular/referrers`],getUsersWithAccessToProtectedBranch:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`],getViews:[`GET /repos/{owner}/{repo}/traffic/views`],getWebhook:[`GET /repos/{owner}/{repo}/hooks/{hook_id}`],getWebhookConfigForRepo:[`GET /repos/{owner}/{repo}/hooks/{hook_id}/config`],getWebhookDelivery:[`GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}`],listActivities:[`GET /repos/{owner}/{repo}/activity`],listAttestations:[`GET /repos/{owner}/{repo}/attestations/{subject_digest}`],listAutolinks:[`GET /repos/{owner}/{repo}/autolinks`],listBranches:[`GET /repos/{owner}/{repo}/branches`],listBranchesForHeadCommit:[`GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head`],listCollaborators:[`GET /repos/{owner}/{repo}/collaborators`],listCommentsForCommit:[`GET /repos/{owner}/{repo}/commits/{commit_sha}/comments`],listCommitCommentsForRepo:[`GET /repos/{owner}/{repo}/comments`],listCommitStatusesForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/statuses`],listCommits:[`GET /repos/{owner}/{repo}/commits`],listContributors:[`GET /repos/{owner}/{repo}/contributors`],listCustomDeploymentRuleIntegrations:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps`],listDeployKeys:[`GET /repos/{owner}/{repo}/keys`],listDeploymentBranchPolicies:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies`],listDeploymentStatuses:[`GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses`],listDeployments:[`GET /repos/{owner}/{repo}/deployments`],listForAuthenticatedUser:[`GET /user/repos`],listForOrg:[`GET /orgs/{org}/repos`],listForUser:[`GET /users/{username}/repos`],listForks:[`GET /repos/{owner}/{repo}/forks`],listInvitations:[`GET /repos/{owner}/{repo}/invitations`],listInvitationsForAuthenticatedUser:[`GET /user/repository_invitations`],listLanguages:[`GET /repos/{owner}/{repo}/languages`],listPagesBuilds:[`GET /repos/{owner}/{repo}/pages/builds`],listPublic:[`GET /repositories`],listPullRequestsAssociatedWithCommit:[`GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls`],listReleaseAssets:[`GET /repos/{owner}/{repo}/releases/{release_id}/assets`],listReleases:[`GET /repos/{owner}/{repo}/releases`],listTags:[`GET /repos/{owner}/{repo}/tags`],listTeams:[`GET /repos/{owner}/{repo}/teams`],listWebhookDeliveries:[`GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries`],listWebhooks:[`GET /repos/{owner}/{repo}/hooks`],merge:[`POST /repos/{owner}/{repo}/merges`],mergeUpstream:[`POST /repos/{owner}/{repo}/merge-upstream`],pingWebhook:[`POST /repos/{owner}/{repo}/hooks/{hook_id}/pings`],redeliverWebhookDelivery:[`POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts`],removeAppAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`,{},{mapToData:`apps`}],removeCollaborator:[`DELETE /repos/{owner}/{repo}/collaborators/{username}`],removeStatusCheckContexts:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`,{},{mapToData:`contexts`}],removeStatusCheckProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`],removeTeamAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`,{},{mapToData:`teams`}],removeUserAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`,{},{mapToData:`users`}],renameBranch:[`POST /repos/{owner}/{repo}/branches/{branch}/rename`],replaceAllTopics:[`PUT /repos/{owner}/{repo}/topics`],requestPagesBuild:[`POST /repos/{owner}/{repo}/pages/builds`],setAdminBranchProtection:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins`],setAppAccessRestrictions:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`,{},{mapToData:`apps`}],setStatusCheckContexts:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`,{},{mapToData:`contexts`}],setTeamAccessRestrictions:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`,{},{mapToData:`teams`}],setUserAccessRestrictions:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`,{},{mapToData:`users`}],testPushWebhook:[`POST /repos/{owner}/{repo}/hooks/{hook_id}/tests`],transfer:[`POST /repos/{owner}/{repo}/transfer`],update:[`PATCH /repos/{owner}/{repo}`],updateBranchProtection:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection`],updateCommitComment:[`PATCH /repos/{owner}/{repo}/comments/{comment_id}`],updateDeploymentBranchPolicy:[`PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}`],updateInformationAboutPagesSite:[`PUT /repos/{owner}/{repo}/pages`],updateInvitation:[`PATCH /repos/{owner}/{repo}/invitations/{invitation_id}`],updateOrgRuleset:[`PUT /orgs/{org}/rulesets/{ruleset_id}`],updatePullRequestReviewProtection:[`PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews`],updateRelease:[`PATCH /repos/{owner}/{repo}/releases/{release_id}`],updateReleaseAsset:[`PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}`],updateRepoRuleset:[`PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}`],updateStatusCheckPotection:[`PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`,{},{renamed:[`repos`,`updateStatusCheckProtection`]}],updateStatusCheckProtection:[`PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`],updateWebhook:[`PATCH /repos/{owner}/{repo}/hooks/{hook_id}`],updateWebhookConfigForRepo:[`PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config`],uploadReleaseAsset:[`POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}`,{baseUrl:`https://uploads.github.com`}]},search:{code:[`GET /search/code`],commits:[`GET /search/commits`],issuesAndPullRequests:[`GET /search/issues`],labels:[`GET /search/labels`],repos:[`GET /search/repositories`],topics:[`GET /search/topics`],users:[`GET /search/users`]},secretScanning:{createPushProtectionBypass:[`POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses`],getAlert:[`GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}`],getScanHistory:[`GET /repos/{owner}/{repo}/secret-scanning/scan-history`],listAlertsForOrg:[`GET /orgs/{org}/secret-scanning/alerts`],listAlertsForRepo:[`GET /repos/{owner}/{repo}/secret-scanning/alerts`],listLocationsForAlert:[`GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations`],listOrgPatternConfigs:[`GET /orgs/{org}/secret-scanning/pattern-configurations`],updateAlert:[`PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}`],updateOrgPatternConfigs:[`PATCH /orgs/{org}/secret-scanning/pattern-configurations`]},securityAdvisories:{createFork:[`POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks`],createPrivateVulnerabilityReport:[`POST /repos/{owner}/{repo}/security-advisories/reports`],createRepositoryAdvisory:[`POST /repos/{owner}/{repo}/security-advisories`],createRepositoryAdvisoryCveRequest:[`POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve`],getGlobalAdvisory:[`GET /advisories/{ghsa_id}`],getRepositoryAdvisory:[`GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}`],listGlobalAdvisories:[`GET /advisories`],listOrgRepositoryAdvisories:[`GET /orgs/{org}/security-advisories`],listRepositoryAdvisories:[`GET /repos/{owner}/{repo}/security-advisories`],updateRepositoryAdvisory:[`PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}`]},teams:{addOrUpdateMembershipForUserInOrg:[`PUT /orgs/{org}/teams/{team_slug}/memberships/{username}`],addOrUpdateRepoPermissionsInOrg:[`PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}`],checkPermissionsForRepoInOrg:[`GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}`],create:[`POST /orgs/{org}/teams`],createDiscussionCommentInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments`],createDiscussionInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions`],deleteDiscussionCommentInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}`],deleteDiscussionInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}`],deleteInOrg:[`DELETE /orgs/{org}/teams/{team_slug}`],getByName:[`GET /orgs/{org}/teams/{team_slug}`],getDiscussionCommentInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}`],getDiscussionInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}`],getMembershipForUserInOrg:[`GET /orgs/{org}/teams/{team_slug}/memberships/{username}`],list:[`GET /orgs/{org}/teams`],listChildInOrg:[`GET /orgs/{org}/teams/{team_slug}/teams`],listDiscussionCommentsInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments`],listDiscussionsInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions`],listForAuthenticatedUser:[`GET /user/teams`],listMembersInOrg:[`GET /orgs/{org}/teams/{team_slug}/members`],listPendingInvitationsInOrg:[`GET /orgs/{org}/teams/{team_slug}/invitations`],listReposInOrg:[`GET /orgs/{org}/teams/{team_slug}/repos`],removeMembershipForUserInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}`],removeRepoInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}`],updateDiscussionCommentInOrg:[`PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}`],updateDiscussionInOrg:[`PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}`],updateInOrg:[`PATCH /orgs/{org}/teams/{team_slug}`]},users:{addEmailForAuthenticated:[`POST /user/emails`,{},{renamed:[`users`,`addEmailForAuthenticatedUser`]}],addEmailForAuthenticatedUser:[`POST /user/emails`],addSocialAccountForAuthenticatedUser:[`POST /user/social_accounts`],block:[`PUT /user/blocks/{username}`],checkBlocked:[`GET /user/blocks/{username}`],checkFollowingForUser:[`GET /users/{username}/following/{target_user}`],checkPersonIsFollowedByAuthenticated:[`GET /user/following/{username}`],createGpgKeyForAuthenticated:[`POST /user/gpg_keys`,{},{renamed:[`users`,`createGpgKeyForAuthenticatedUser`]}],createGpgKeyForAuthenticatedUser:[`POST /user/gpg_keys`],createPublicSshKeyForAuthenticated:[`POST /user/keys`,{},{renamed:[`users`,`createPublicSshKeyForAuthenticatedUser`]}],createPublicSshKeyForAuthenticatedUser:[`POST /user/keys`],createSshSigningKeyForAuthenticatedUser:[`POST /user/ssh_signing_keys`],deleteAttestationsBulk:[`POST /users/{username}/attestations/delete-request`],deleteAttestationsById:[`DELETE /users/{username}/attestations/{attestation_id}`],deleteAttestationsBySubjectDigest:[`DELETE /users/{username}/attestations/digest/{subject_digest}`],deleteEmailForAuthenticated:[`DELETE /user/emails`,{},{renamed:[`users`,`deleteEmailForAuthenticatedUser`]}],deleteEmailForAuthenticatedUser:[`DELETE /user/emails`],deleteGpgKeyForAuthenticated:[`DELETE /user/gpg_keys/{gpg_key_id}`,{},{renamed:[`users`,`deleteGpgKeyForAuthenticatedUser`]}],deleteGpgKeyForAuthenticatedUser:[`DELETE /user/gpg_keys/{gpg_key_id}`],deletePublicSshKeyForAuthenticated:[`DELETE /user/keys/{key_id}`,{},{renamed:[`users`,`deletePublicSshKeyForAuthenticatedUser`]}],deletePublicSshKeyForAuthenticatedUser:[`DELETE /user/keys/{key_id}`],deleteSocialAccountForAuthenticatedUser:[`DELETE /user/social_accounts`],deleteSshSigningKeyForAuthenticatedUser:[`DELETE /user/ssh_signing_keys/{ssh_signing_key_id}`],follow:[`PUT /user/following/{username}`],getAuthenticated:[`GET /user`],getById:[`GET /user/{account_id}`],getByUsername:[`GET /users/{username}`],getContextForUser:[`GET /users/{username}/hovercard`],getGpgKeyForAuthenticated:[`GET /user/gpg_keys/{gpg_key_id}`,{},{renamed:[`users`,`getGpgKeyForAuthenticatedUser`]}],getGpgKeyForAuthenticatedUser:[`GET /user/gpg_keys/{gpg_key_id}`],getPublicSshKeyForAuthenticated:[`GET /user/keys/{key_id}`,{},{renamed:[`users`,`getPublicSshKeyForAuthenticatedUser`]}],getPublicSshKeyForAuthenticatedUser:[`GET /user/keys/{key_id}`],getSshSigningKeyForAuthenticatedUser:[`GET /user/ssh_signing_keys/{ssh_signing_key_id}`],list:[`GET /users`],listAttestations:[`GET /users/{username}/attestations/{subject_digest}`],listAttestationsBulk:[`POST /users/{username}/attestations/bulk-list{?per_page,before,after}`],listBlockedByAuthenticated:[`GET /user/blocks`,{},{renamed:[`users`,`listBlockedByAuthenticatedUser`]}],listBlockedByAuthenticatedUser:[`GET /user/blocks`],listEmailsForAuthenticated:[`GET /user/emails`,{},{renamed:[`users`,`listEmailsForAuthenticatedUser`]}],listEmailsForAuthenticatedUser:[`GET /user/emails`],listFollowedByAuthenticated:[`GET /user/following`,{},{renamed:[`users`,`listFollowedByAuthenticatedUser`]}],listFollowedByAuthenticatedUser:[`GET /user/following`],listFollowersForAuthenticatedUser:[`GET /user/followers`],listFollowersForUser:[`GET /users/{username}/followers`],listFollowingForUser:[`GET /users/{username}/following`],listGpgKeysForAuthenticated:[`GET /user/gpg_keys`,{},{renamed:[`users`,`listGpgKeysForAuthenticatedUser`]}],listGpgKeysForAuthenticatedUser:[`GET /user/gpg_keys`],listGpgKeysForUser:[`GET /users/{username}/gpg_keys`],listPublicEmailsForAuthenticated:[`GET /user/public_emails`,{},{renamed:[`users`,`listPublicEmailsForAuthenticatedUser`]}],listPublicEmailsForAuthenticatedUser:[`GET /user/public_emails`],listPublicKeysForUser:[`GET /users/{username}/keys`],listPublicSshKeysForAuthenticated:[`GET /user/keys`,{},{renamed:[`users`,`listPublicSshKeysForAuthenticatedUser`]}],listPublicSshKeysForAuthenticatedUser:[`GET /user/keys`],listSocialAccountsForAuthenticatedUser:[`GET /user/social_accounts`],listSocialAccountsForUser:[`GET /users/{username}/social_accounts`],listSshSigningKeysForAuthenticatedUser:[`GET /user/ssh_signing_keys`],listSshSigningKeysForUser:[`GET /users/{username}/ssh_signing_keys`],setPrimaryEmailVisibilityForAuthenticated:[`PATCH /user/email/visibility`,{},{renamed:[`users`,`setPrimaryEmailVisibilityForAuthenticatedUser`]}],setPrimaryEmailVisibilityForAuthenticatedUser:[`PATCH /user/email/visibility`],unblock:[`DELETE /user/blocks/{username}`],unfollow:[`DELETE /user/following/{username}`],updateAuthenticated:[`PATCH /user`]}};const ro=new Map;for(let[e,t]of Object.entries(no))for(let[n,r]of Object.entries(t)){let[t,i,a]=r,[o,s]=t.split(/ /),c=Object.assign({method:o,url:s},i);ro.has(e)||ro.set(e,new Map),ro.get(e).set(n,{scope:e,methodName:n,endpointDefaults:c,decorations:a})}const io={has({scope:e},t){return ro.get(e).has(t)},getOwnPropertyDescriptor(e,t){return{value:this.get(e,t),configurable:!0,writable:!0,enumerable:!0}},defineProperty(e,t,n){return Object.defineProperty(e.cache,t,n),!0},deleteProperty(e,t){return delete e.cache[t],!0},ownKeys({scope:e}){return[...ro.get(e).keys()]},set(e,t,n){return e.cache[t]=n},get({octokit:e,scope:t,cache:n},r){if(n[r])return n[r];let i=ro.get(t).get(r);if(!i)return;let{endpointDefaults:a,decorations:o}=i;return o?n[r]=oo(e,t,r,a,o):n[r]=e.request.defaults(a),n[r]}};function ao(e){let t={};for(let n of ro.keys())t[n]=new Proxy({octokit:e,scope:n,cache:{}},io);return t}function oo(e,t,n,r,i){let a=e.request.defaults(r);function o(...r){let o=a.endpoint.merge(...r);if(i.mapToData)return o=Object.assign({},o,{data:o[i.mapToData],[i.mapToData]:void 0}),a(o);if(i.renamed){let[r,a]=i.renamed;e.log.warn(`octokit.${t}.${n}() has been renamed to octokit.${r}.${a}()`)}if(i.deprecated&&e.log.warn(i.deprecated),i.renamedParameters){let o=a.endpoint.merge(...r);for(let[r,a]of Object.entries(i.renamedParameters))r in o&&(e.log.warn(`"${r}" parameter is deprecated for "octokit.${t}.${n}()". Use "${a}" instead`),a in o||(o[a]=o[r]),delete o[r]);return a(o)}return a(...r)}return Object.assign(o,a)}function so(e){return{rest:ao(e)}}so.VERSION=to;function co(e){let t=ao(e);return{...t,rest:t}}co.VERSION=to;const lo=qa.plugin(Ja,co,eo).defaults({userAgent:`octokit-rest.js/22.0.1`});async function uo(e,t,n){let{host:r,json:i}=e;kr(r);let a=await(n??(()=>ma({message:`Enter PAT:`})))();a||(process.stderr.write(`No token provided
|
|
20
|
-
`),process.exit(1));let o=r===`github.com`?void 0:`https://${r}/api/v3`,s=new
|
|
21
|
-
`),process.exit(1)}await t.set(r,c,a,{gitProtocol:`https`,name:l,email:u}),i?process.stdout.write(`${JSON.stringify({type:`complete`,host:r,login:c})}\n`):process.stderr.write(`✓ PAT stored for ${c} on ${r}\n`)}function
|
|
22
|
-
`):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function
|
|
23
|
-
`)){let n=
|
|
24
|
-
`)
|
|
25
|
-
`)
|
|
26
|
-
`)
|
|
27
|
-
`),exitCode:0}}function Io(){return new r(`install-skill`).description("Build openknowledge.skill and open the Claude Desktop App so you can upload it for Claude Chat & Cowork. Not needed for Claude Code — `ok init` covers that separately.").option(`--out <path>`,`Custom output path (default: ~/Downloads/openknowledge.skill)`).option(`--no-open`,`Build the file but skip the OS file-association handoff`).action(async e=>{let t=await Fo({out:e.out,noOpen:!e.open});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}var M;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(M||={});var Lo;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Lo||={});const N=M.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Ro=e=>{switch(typeof e){case`undefined`:return N.undefined;case`string`:return N.string;case`number`:return Number.isNaN(e)?N.nan:N.number;case`boolean`:return N.boolean;case`function`:return N.function;case`bigint`:return N.bigint;case`symbol`:return N.symbol;case`object`:return Array.isArray(e)?N.array:e===null?N.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?N.promise:typeof Map<`u`&&e instanceof Map?N.map:typeof Set<`u`&&e instanceof Set?N.set:typeof Date<`u`&&e instanceof Date?N.date:N.object;default:return N.unknown}},P=M.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var zo=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};zo.create=e=>new zo(e);const Bo=(e,t)=>{let n;switch(e.code){case P.invalid_type:n=e.received===N.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case P.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,M.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:n=`Unrecognized key(s) in object: ${M.joinValues(e.keys,`, `)}`;break;case P.invalid_union:n=`Invalid input`;break;case P.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${M.joinValues(e.options)}`;break;case P.invalid_enum_value:n=`Invalid enum value. Expected ${M.joinValues(e.options)}, received '${e.received}'`;break;case P.invalid_arguments:n=`Invalid function arguments`;break;case P.invalid_return_type:n=`Invalid function return type`;break;case P.invalid_date:n=`Invalid date`;break;case P.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:M.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case P.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case P.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case P.custom:n=`Invalid input`;break;case P.invalid_intersection_types:n=`Intersection results could not be merged`;break;case P.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case P.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,M.assertNever(e)}return{message:n}};let Vo=Bo;function Ho(){return Vo}const Uo=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function F(e,t){let n=Ho(),r=Uo({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Bo?void 0:Bo].filter(e=>!!e)});e.common.issues.push(r)}var Wo=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return I;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return I;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const I=Object.freeze({status:`aborted`}),Go=e=>({status:`dirty`,value:e}),Ko=e=>({status:`valid`,value:e}),qo=e=>e.status===`aborted`,Jo=e=>e.status===`dirty`,Yo=e=>e.status===`valid`,Xo=e=>typeof Promise<`u`&&e instanceof Promise;var L;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(L||={});var Zo=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const Qo=(e,t)=>{if(Yo(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new zo(e.common.issues),this._error}}};function R(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var z=class{get description(){return this._def.description}_getType(e){return Ro(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ro(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Wo,ctx:{common:e.parent.common,data:e.data,parsedType:Ro(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Xo(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ro(e)};return Qo(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ro(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Yo(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Yo(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ro(e)},r=this._parse({data:e,path:n.path,parent:n});return Qo(n,await(Xo(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:P.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new ec({schema:this,typeName:B.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return tc.create(this,this._def)}nullable(){return nc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Fs.create(this)}promise(){return $s.create(this,this._def)}or(e){return Rs.create([this,e],this._def)}and(e){return Hs.create(this,e,this._def)}transform(e){return new ec({...R(this._def),schema:this,typeName:B.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new rc({...R(this._def),innerType:this,defaultValue:t,typeName:B.ZodDefault})}brand(){return new oc({typeName:B.ZodBranded,type:this,...R(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ic({...R(this._def),innerType:this,catchValue:t,typeName:B.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return sc.create(this,e)}readonly(){return cc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const $o=/^c[^\s-]{8,}$/i,es=/^[0-9a-z]+$/,ts=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ns=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,rs=/^[a-z0-9_-]{21}$/i,is=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,as=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,os=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let ss;const cs=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ls=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,us=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ds=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,fs=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ps=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ms=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,hs=RegExp(`^${ms}$`);function gs(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function _s(e){return RegExp(`^${gs(e)}$`)}function vs(e){let t=`${ms}T${gs(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function ys(e,t){return!!((t===`v4`||!t)&&cs.test(e)||(t===`v6`||!t)&&us.test(e))}function bs(e,t){if(!is.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function xs(e,t){return!!((t===`v4`||!t)&&ls.test(e)||(t===`v6`||!t)&&ds.test(e))}var Ss=class e extends z{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==N.string){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.string,received:t.parsedType}),I}let t=new Wo,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:P.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:P.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?F(n,{code:P.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&F(n,{code:P.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)os.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`email`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)ss||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),ss.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`emoji`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)ns.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`uuid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)rs.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`nanoid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)$o.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`cuid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)es.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`cuid2`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)ts.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`ulid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),F(n,{validation:`url`,code:P.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`regex`,code:P.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?vs(r).test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?hs.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?_s(r).test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?as.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`duration`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?ys(e.data,r.version)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`ip`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?bs(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`jwt`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?xs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`cidr`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?fs.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`base64`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?ps.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`base64url`,code:P.invalid_string,message:r.message}),t.dirty()):M.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:P.invalid_string,...L.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...L.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...L.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...L.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...L.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...L.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...L.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...L.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...L.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...L.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...L.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...L.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...L.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...L.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...L.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...L.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...L.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...L.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...L.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...L.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...L.errToObj(t)})}nonempty(e){return this.min(1,L.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ss.create=e=>new Ss({checks:[],typeName:B.ZodString,coerce:e?.coerce??!1,...R(e)});function Cs(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var ws=class e extends z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==N.number){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.number,received:t.parsedType}),I}let t,n=new Wo;for(let r of this._def.checks)r.kind===`int`?M.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),F(t,{code:P.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Cs(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),F(t,{code:P.not_finite,message:r.message}),n.dirty()):M.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,L.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,L.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,L.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,L.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:L.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:L.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:L.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:L.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:L.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:L.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&M.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};ws.create=e=>new ws({checks:[],typeName:B.ZodNumber,coerce:e?.coerce||!1,...R(e)});var Ts=class e extends z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==N.bigint)return this._getInvalidInput(e);let t,n=new Wo;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):M.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.bigint,received:t.parsedType}),I}gte(e,t){return this.setLimit(`min`,e,!0,L.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,L.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,L.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,L.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:L.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:L.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ts.create=e=>new Ts({checks:[],typeName:B.ZodBigInt,coerce:e?.coerce??!1,...R(e)});var Es=class extends z{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==N.boolean){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.boolean,received:t.parsedType}),I}return Ko(e.data)}};Es.create=e=>new Es({typeName:B.ZodBoolean,coerce:e?.coerce||!1,...R(e)});var Ds=class e extends z{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==N.date){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.date,received:t.parsedType}),I}if(Number.isNaN(e.data.getTime()))return F(this._getOrReturnCtx(e),{code:P.invalid_date}),I;let t=new Wo,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:P.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:P.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):M.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:L.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:L.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Ds.create=e=>new Ds({checks:[],coerce:e?.coerce||!1,typeName:B.ZodDate,...R(e)});var Os=class extends z{_parse(e){if(this._getType(e)!==N.symbol){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.symbol,received:t.parsedType}),I}return Ko(e.data)}};Os.create=e=>new Os({typeName:B.ZodSymbol,...R(e)});var ks=class extends z{_parse(e){if(this._getType(e)!==N.undefined){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.undefined,received:t.parsedType}),I}return Ko(e.data)}};ks.create=e=>new ks({typeName:B.ZodUndefined,...R(e)});var As=class extends z{_parse(e){if(this._getType(e)!==N.null){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.null,received:t.parsedType}),I}return Ko(e.data)}};As.create=e=>new As({typeName:B.ZodNull,...R(e)});var js=class extends z{constructor(){super(...arguments),this._any=!0}_parse(e){return Ko(e.data)}};js.create=e=>new js({typeName:B.ZodAny,...R(e)});var Ms=class extends z{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ko(e.data)}};Ms.create=e=>new Ms({typeName:B.ZodUnknown,...R(e)});var Ns=class extends z{_parse(e){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.never,received:t.parsedType}),I}};Ns.create=e=>new Ns({typeName:B.ZodNever,...R(e)});var Ps=class extends z{_parse(e){if(this._getType(e)!==N.undefined){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.void,received:t.parsedType}),I}return Ko(e.data)}};Ps.create=e=>new Ps({typeName:B.ZodVoid,...R(e)});var Fs=class e extends z{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==N.array)return F(t,{code:P.invalid_type,expected:N.array,received:t.parsedType}),I;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(F(t,{code:e?P.too_big:P.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(F(t,{code:P.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(F(t,{code:P.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Zo(t,e,t.path,n)))).then(e=>Wo.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Zo(t,e,t.path,n)));return Wo.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:L.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:L.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:L.toString(n)}})}nonempty(e){return this.min(1,e)}};Fs.create=(e,t)=>new Fs({type:e,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...R(t)});function Is(e){if(e instanceof Ls){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=tc.create(Is(r))}return new Ls({...e._def,shape:()=>t})}else if(e instanceof Fs)return new Fs({...e._def,type:Is(e.element)});else if(e instanceof tc)return tc.create(Is(e.unwrap()));else if(e instanceof nc)return nc.create(Is(e.unwrap()));else if(e instanceof Us)return Us.create(e.items.map(e=>Is(e)));else return e}var Ls=class e extends z{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:M.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==N.object){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.object,received:t.parsedType}),I}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ns&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Zo(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Ns){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(F(n,{code:P.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Zo(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Wo.mergeObjectSync(t,e)):Wo.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return L.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:L.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:B.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of M.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of M.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Is(this)}partial(t){let n={};for(let e of M.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of M.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof tc;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Xs(M.objectKeys(this.shape))}};Ls.create=(e,t)=>new Ls({shape:()=>e,unknownKeys:`strip`,catchall:Ns.create(),typeName:B.ZodObject,...R(t)}),Ls.strictCreate=(e,t)=>new Ls({shape:()=>e,unknownKeys:`strict`,catchall:Ns.create(),typeName:B.ZodObject,...R(t)}),Ls.lazycreate=(e,t)=>new Ls({shape:e,unknownKeys:`strip`,catchall:Ns.create(),typeName:B.ZodObject,...R(t)});var Rs=class extends z{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new zo(e.ctx.common.issues));return F(t,{code:P.invalid_union,unionErrors:n}),I}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new zo(e));return F(t,{code:P.invalid_union,unionErrors:i}),I}}get options(){return this._def.options}};Rs.create=(e,t)=>new Rs({options:e,typeName:B.ZodUnion,...R(t)});const zs=e=>e instanceof Js?zs(e.schema):e instanceof ec?zs(e.innerType()):e instanceof Ys?[e.value]:e instanceof Zs?e.options:e instanceof Qs?M.objectValues(e.enum):e instanceof rc?zs(e._def.innerType):e instanceof ks?[void 0]:e instanceof As?[null]:e instanceof tc?[void 0,...zs(e.unwrap())]:e instanceof nc?[null,...zs(e.unwrap())]:e instanceof oc||e instanceof cc?zs(e.unwrap()):e instanceof ic?zs(e._def.innerType):[];var Bs=class e extends z{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==N.object)return F(t,{code:P.invalid_type,expected:N.object,received:t.parsedType}),I;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(F(t,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),I)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=zs(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:B.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...R(r)})}};function Vs(e,t){let n=Ro(e),r=Ro(t);if(e===t)return{valid:!0,data:e};if(n===N.object&&r===N.object){let n=M.objectKeys(t),r=M.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Vs(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===N.array&&r===N.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Vs(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===N.date&&r===N.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Hs=class extends z{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(qo(e)||qo(r))return I;let i=Vs(e.value,r.value);return i.valid?((Jo(e)||Jo(r))&&t.dirty(),{status:t.value,value:i.data}):(F(n,{code:P.invalid_intersection_types}),I)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Hs.create=(e,t,n)=>new Hs({left:e,right:t,typeName:B.ZodIntersection,...R(n)});var Us=class e extends z{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.array)return F(n,{code:P.invalid_type,expected:N.array,received:n.parsedType}),I;if(n.data.length<this._def.items.length)return F(n,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),I;!this._def.rest&&n.data.length>this._def.items.length&&(F(n,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Zo(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Wo.mergeArray(t,e)):Wo.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Us.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Us({items:e,typeName:B.ZodTuple,rest:null,...R(t)})};var Ws=class e extends z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.object)return F(n,{code:P.invalid_type,expected:N.object,received:n.parsedType}),I;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Zo(n,e,n.path,e)),value:a._parse(new Zo(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Wo.mergeObjectAsync(t,r):Wo.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof z?new e({keyType:t,valueType:n,typeName:B.ZodRecord,...R(r)}):new e({keyType:Ss.create(),valueType:t,typeName:B.ZodRecord,...R(n)})}},Gs=class extends z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.map)return F(n,{code:P.invalid_type,expected:N.map,received:n.parsedType}),I;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Zo(n,e,n.path,[a,`key`])),value:i._parse(new Zo(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return I;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return I;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Gs.create=(e,t,n)=>new Gs({valueType:t,keyType:e,typeName:B.ZodMap,...R(n)});var Ks=class e extends z{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.set)return F(n,{code:P.invalid_type,expected:N.set,received:n.parsedType}),I;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(F(n,{code:P.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(F(n,{code:P.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return I;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Zo(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:L.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:L.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Ks.create=(e,t)=>new Ks({valueType:e,minSize:null,maxSize:null,typeName:B.ZodSet,...R(t)});var qs=class e extends z{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==N.function)return F(t,{code:P.invalid_type,expected:N.function,received:t.parsedType}),I;function n(e,n){return Uo({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ho(),Bo].filter(e=>!!e),issueData:{code:P.invalid_arguments,argumentsError:n}})}function r(e,n){return Uo({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ho(),Bo].filter(e=>!!e),issueData:{code:P.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof $s){let e=this;return Ko(async function(...t){let o=new zo([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return Ko(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new zo([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new zo([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Us.create(t).rest(Ms.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Us.create([]).rest(Ms.create()),returns:n||Ms.create(),typeName:B.ZodFunction,...R(r)})}},Js=class extends z{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Js.create=(e,t)=>new Js({getter:e,typeName:B.ZodLazy,...R(t)});var Ys=class extends z{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return F(t,{received:t.data,code:P.invalid_literal,expected:this._def.value}),I}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Ys.create=(e,t)=>new Ys({value:e,typeName:B.ZodLiteral,...R(t)});function Xs(e,t){return new Zs({values:e,typeName:B.ZodEnum,...R(t)})}var Zs=class e extends z{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return F(t,{expected:M.joinValues(n),received:t.parsedType,code:P.invalid_type}),I}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return F(t,{received:t.data,code:P.invalid_enum_value,options:n}),I}return Ko(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Zs.create=Xs;var Qs=class extends z{_parse(e){let t=M.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==N.string&&n.parsedType!==N.number){let e=M.objectValues(t);return F(n,{expected:M.joinValues(e),received:n.parsedType,code:P.invalid_type}),I}if(this._cache||=new Set(M.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=M.objectValues(t);return F(n,{received:n.data,code:P.invalid_enum_value,options:e}),I}return Ko(e.data)}get enum(){return this._def.values}};Qs.create=(e,t)=>new Qs({values:e,typeName:B.ZodNativeEnum,...R(t)});var $s=class extends z{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==N.promise&&t.common.async===!1?(F(t,{code:P.invalid_type,expected:N.promise,received:t.parsedType}),I):Ko((t.parsedType===N.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};$s.create=(e,t)=>new $s({type:e,typeName:B.ZodPromise,...R(t)});var ec=class extends z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{F(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return I;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?I:r.status===`dirty`||t.value===`dirty`?Go(r.value):r});{if(t.value===`aborted`)return I;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?I:r.status===`dirty`||t.value===`dirty`?Go(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?I:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?I:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Yo(e))return I;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Yo(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):I);M.assertNever(r)}};ec.create=(e,t,n)=>new ec({schema:e,typeName:B.ZodEffects,effect:t,...R(n)}),ec.createWithPreprocess=(e,t,n)=>new ec({schema:t,effect:{type:`preprocess`,transform:e},typeName:B.ZodEffects,...R(n)});var tc=class extends z{_parse(e){return this._getType(e)===N.undefined?Ko(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};tc.create=(e,t)=>new tc({innerType:e,typeName:B.ZodOptional,...R(t)});var nc=class extends z{_parse(e){return this._getType(e)===N.null?Ko(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};nc.create=(e,t)=>new nc({innerType:e,typeName:B.ZodNullable,...R(t)});var rc=class extends z{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===N.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};rc.create=(e,t)=>new rc({innerType:e,typeName:B.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...R(t)});var ic=class extends z{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Xo(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new zo(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new zo(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ic.create=(e,t)=>new ic({innerType:e,typeName:B.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...R(t)});var ac=class extends z{_parse(e){if(this._getType(e)!==N.nan){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.nan,received:t.parsedType}),I}return{status:`valid`,value:e.data}}};ac.create=e=>new ac({typeName:B.ZodNaN,...R(e)});var oc=class extends z{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},sc=class e extends z{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?I:e.status===`dirty`?(t.dirty(),Go(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?I:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:B.ZodPipeline})}},cc=class extends z{_parse(e){let t=this._def.innerType._parse(e),n=e=>(Yo(e)&&(e.value=Object.freeze(e.value)),e);return Xo(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};cc.create=(e,t)=>new cc({innerType:e,typeName:B.ZodReadonly,...R(t)}),Ls.lazycreate;var B;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(B||={}),Ss.create,ws.create,ac.create,Ts.create,Es.create,Ds.create,Os.create,ks.create,As.create,js.create,Ms.create,Ns.create,Ps.create,Fs.create;const lc=Ls.create;Ls.strictCreate,Rs.create,Bs.create,Hs.create,Us.create,Ws.create,Gs.create,Ks.create,qs.create,Js.create,Ys.create,Zs.create,Qs.create,$s.create,ec.create,tc.create,nc.create,ec.createWithPreprocess,sc.create;const uc=oe(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);ce.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>de(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ie(e,t,n),e.parseAsync=async(t,n)=>te(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>pe(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>ne(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),dc=oe(`ZodMiniObject`,(e,t)=>{E.init(e,t),uc.init(e,t),re(e,`shape`,()=>t.shape)});function fc(e,t){return new dc({type:`object`,shape:e??{},...ue(t)})}function pc(e){return!!e._zod}function mc(e){let t=Object.values(e);if(t.length===0)return fc({});let n=t.every(pc),r=t.every(e=>!pc(e));if(n)return fc(e);if(r)return lc(e);throw Error(`Mixed Zod versions detected in object shape.`)}function hc(e,t){return pc(e)?ie(e,t):e.safeParse(t)}async function gc(e,t){return pc(e)?await pe(e,t):await e.safeParseAsync(t)}function _c(e){if(!e)return;let t;if(t=pc(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function vc(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return mc(e)}}if(pc(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function yc(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function bc(e){return e.description}function xc(e){if(pc(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Sc(e){if(pc(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const Cc=`2025-11-25`,wc=[Cc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Tc=`io.modelcontextprotocol/related-task`,Ec=S(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Dc=v([T(),g().int()]),Oc=T();f({ttl:g().optional(),pollInterval:g().optional()});const kc=D({ttl:g().optional()}),Ac=D({taskId:T()}),jc=f({progressToken:Dc.optional(),[Tc]:Ac.optional()}),Mc=D({_meta:jc.optional()}),Nc=Mc.extend({task:kc.optional()}),Pc=e=>Nc.safeParse(e).success,Fc=D({method:T(),params:Mc.loose().optional()}),Ic=D({_meta:jc.optional()}),Lc=D({method:T(),params:Ic.loose().optional()}),Rc=f({_meta:jc.optional()}),zc=v([T(),g().int()]),Bc=D({jsonrpc:C(`2.0`),id:zc,...Fc.shape}).strict(),Vc=e=>Bc.safeParse(e).success,Hc=D({jsonrpc:C(`2.0`),...Lc.shape}).strict(),Uc=e=>Hc.safeParse(e).success,Wc=D({jsonrpc:C(`2.0`),id:zc,result:Rc}).strict(),Gc=e=>Wc.safeParse(e).success;var V;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(V||={});const Kc=D({jsonrpc:C(`2.0`),id:zc.optional(),error:D({code:g().int(),message:T(),data:u().optional()})}).strict(),qc=e=>Kc.safeParse(e).success,Jc=v([Bc,Hc,Wc,Kc]);v([Wc,Kc]);const Yc=Rc.strict(),Xc=Ic.extend({requestId:zc.optional(),reason:T().optional()}),Zc=Lc.extend({method:C(`notifications/cancelled`),params:Xc}),Qc=D({icons:O(D({src:T(),mimeType:T().optional(),sizes:O(T()).optional(),theme:_([`light`,`dark`]).optional()})).optional()}),$c=D({name:T(),title:T().optional()}),el=$c.extend({...$c.shape,...Qc.shape,version:T(),websiteUrl:T().optional(),description:T().optional()}),tl=ee(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,x(D({form:x(D({applyDefaults:d().optional()}),w(T(),u())).optional(),url:Ec.optional()}),w(T(),u()).optional())),nl=f({list:Ec.optional(),cancel:Ec.optional(),requests:f({sampling:f({createMessage:Ec.optional()}).optional(),elicitation:f({create:Ec.optional()}).optional()}).optional()}),rl=f({list:Ec.optional(),cancel:Ec.optional(),requests:f({tools:f({call:Ec.optional()}).optional()}).optional()}),il=D({experimental:w(T(),Ec).optional(),sampling:D({context:Ec.optional(),tools:Ec.optional()}).optional(),elicitation:tl.optional(),roots:D({listChanged:d().optional()}).optional(),tasks:nl.optional(),extensions:w(T(),Ec).optional()}),al=Mc.extend({protocolVersion:T(),capabilities:il,clientInfo:el}),ol=Fc.extend({method:C(`initialize`),params:al}),sl=D({experimental:w(T(),Ec).optional(),logging:Ec.optional(),completions:Ec.optional(),prompts:D({listChanged:d().optional()}).optional(),resources:D({subscribe:d().optional(),listChanged:d().optional()}).optional(),tools:D({listChanged:d().optional()}).optional(),tasks:rl.optional(),extensions:w(T(),Ec).optional()}),cl=Rc.extend({protocolVersion:T(),capabilities:sl,serverInfo:el,instructions:T().optional()}),ll=Lc.extend({method:C(`notifications/initialized`),params:Ic.optional()}),ul=Fc.extend({method:C(`ping`),params:Mc.optional()}),dl=D({progress:g(),total:h(g()),message:h(T())}),fl=D({...Ic.shape,...dl.shape,progressToken:Dc}),pl=Lc.extend({method:C(`notifications/progress`),params:fl}),ml=Mc.extend({cursor:Oc.optional()}),hl=Fc.extend({params:ml.optional()}),gl=Rc.extend({nextCursor:Oc.optional()}),_l=_([`working`,`input_required`,`completed`,`failed`,`cancelled`]),vl=D({taskId:T(),status:_l,ttl:v([g(),y()]),createdAt:T(),lastUpdatedAt:T(),pollInterval:h(g()),statusMessage:h(T())}),yl=Rc.extend({task:vl}),bl=Ic.merge(vl),xl=Lc.extend({method:C(`notifications/tasks/status`),params:bl}),Sl=Fc.extend({method:C(`tasks/get`),params:Mc.extend({taskId:T()})}),Cl=Rc.merge(vl),wl=Fc.extend({method:C(`tasks/result`),params:Mc.extend({taskId:T()})});Rc.loose();const Tl=hl.extend({method:C(`tasks/list`)}),El=gl.extend({tasks:O(vl)}),Dl=Fc.extend({method:C(`tasks/cancel`),params:Mc.extend({taskId:T()})}),Ol=Rc.merge(vl),kl=D({uri:T(),mimeType:h(T()),_meta:w(T(),u()).optional()}),Al=kl.extend({text:T()}),jl=T().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Ml=kl.extend({blob:jl}),Nl=_([`user`,`assistant`]),Pl=D({audience:O(Nl).optional(),priority:g().min(0).max(1).optional(),lastModified:fe({offset:!0}).optional()}),Fl=D({...$c.shape,...Qc.shape,uri:T(),description:h(T()),mimeType:h(T()),size:h(g()),annotations:Pl.optional(),_meta:h(f({}))}),Il=D({...$c.shape,...Qc.shape,uriTemplate:T(),description:h(T()),mimeType:h(T()),annotations:Pl.optional(),_meta:h(f({}))}),Ll=hl.extend({method:C(`resources/list`)}),Rl=gl.extend({resources:O(Fl)}),zl=hl.extend({method:C(`resources/templates/list`)}),Bl=gl.extend({resourceTemplates:O(Il)}),Vl=Mc.extend({uri:T()}),Hl=Vl,Ul=Fc.extend({method:C(`resources/read`),params:Hl}),Wl=Rc.extend({contents:O(v([Al,Ml]))}),Gl=Lc.extend({method:C(`notifications/resources/list_changed`),params:Ic.optional()}),Kl=Vl,ql=Fc.extend({method:C(`resources/subscribe`),params:Kl}),Jl=Vl,Yl=Fc.extend({method:C(`resources/unsubscribe`),params:Jl}),Xl=Ic.extend({uri:T()}),Zl=Lc.extend({method:C(`notifications/resources/updated`),params:Xl}),Ql=D({name:T(),description:h(T()),required:h(d())}),$l=D({...$c.shape,...Qc.shape,description:h(T()),arguments:h(O(Ql)),_meta:h(f({}))}),eu=hl.extend({method:C(`prompts/list`)}),tu=gl.extend({prompts:O($l)}),nu=Mc.extend({name:T(),arguments:w(T(),T()).optional()}),ru=Fc.extend({method:C(`prompts/get`),params:nu}),iu=D({type:C(`text`),text:T(),annotations:Pl.optional(),_meta:w(T(),u()).optional()}),au=D({type:C(`image`),data:jl,mimeType:T(),annotations:Pl.optional(),_meta:w(T(),u()).optional()}),ou=D({type:C(`audio`),data:jl,mimeType:T(),annotations:Pl.optional(),_meta:w(T(),u()).optional()}),su=D({type:C(`tool_use`),name:T(),id:T(),input:w(T(),u()),_meta:w(T(),u()).optional()}),cu=D({type:C(`resource`),resource:v([Al,Ml]),annotations:Pl.optional(),_meta:w(T(),u()).optional()}),lu=v([iu,au,ou,Fl.extend({type:C(`resource_link`)}),cu]),uu=D({role:Nl,content:lu}),du=Rc.extend({description:T().optional(),messages:O(uu)}),fu=Lc.extend({method:C(`notifications/prompts/list_changed`),params:Ic.optional()}),pu=D({title:T().optional(),readOnlyHint:d().optional(),destructiveHint:d().optional(),idempotentHint:d().optional(),openWorldHint:d().optional()}),mu=D({taskSupport:_([`required`,`optional`,`forbidden`]).optional()}),hu=D({...$c.shape,...Qc.shape,description:T().optional(),inputSchema:D({type:C(`object`),properties:w(T(),Ec).optional(),required:O(T()).optional()}).catchall(u()),outputSchema:D({type:C(`object`),properties:w(T(),Ec).optional(),required:O(T()).optional()}).catchall(u()).optional(),annotations:pu.optional(),execution:mu.optional(),_meta:w(T(),u()).optional()}),gu=hl.extend({method:C(`tools/list`)}),_u=gl.extend({tools:O(hu)}),vu=Rc.extend({content:O(lu).default([]),structuredContent:w(T(),u()).optional(),isError:d().optional()});vu.or(Rc.extend({toolResult:u()}));const yu=Nc.extend({name:T(),arguments:w(T(),u()).optional()}),bu=Fc.extend({method:C(`tools/call`),params:yu}),xu=Lc.extend({method:C(`notifications/tools/list_changed`),params:Ic.optional()});D({autoRefresh:d().default(!0),debounceMs:g().int().nonnegative().default(300)});const Su=_([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Cu=Mc.extend({level:Su}),wu=Fc.extend({method:C(`logging/setLevel`),params:Cu}),Tu=Ic.extend({level:Su,logger:T().optional(),data:u()}),Eu=Lc.extend({method:C(`notifications/message`),params:Tu}),Du=D({hints:O(D({name:T().optional()})).optional(),costPriority:g().min(0).max(1).optional(),speedPriority:g().min(0).max(1).optional(),intelligencePriority:g().min(0).max(1).optional()}),Ou=D({mode:_([`auto`,`required`,`none`]).optional()}),ku=D({type:C(`tool_result`),toolUseId:T().describe(`The unique identifier for the corresponding tool call.`),content:O(lu).default([]),structuredContent:D({}).loose().optional(),isError:d().optional(),_meta:w(T(),u()).optional()}),Au=p(`type`,[iu,au,ou]),ju=p(`type`,[iu,au,ou,su,ku]),Mu=D({role:Nl,content:v([ju,O(ju)]),_meta:w(T(),u()).optional()}),Nu=Nc.extend({messages:O(Mu),modelPreferences:Du.optional(),systemPrompt:T().optional(),includeContext:_([`none`,`thisServer`,`allServers`]).optional(),temperature:g().optional(),maxTokens:g().int(),stopSequences:O(T()).optional(),metadata:Ec.optional(),tools:O(hu).optional(),toolChoice:Ou.optional()}),Pu=Fc.extend({method:C(`sampling/createMessage`),params:Nu}),Fu=Rc.extend({model:T(),stopReason:h(_([`endTurn`,`stopSequence`,`maxTokens`]).or(T())),role:Nl,content:Au}),Iu=Rc.extend({model:T(),stopReason:h(_([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(T())),role:Nl,content:v([ju,O(ju)])}),Lu=D({type:C(`boolean`),title:T().optional(),description:T().optional(),default:d().optional()}),Ru=D({type:C(`string`),title:T().optional(),description:T().optional(),minLength:g().optional(),maxLength:g().optional(),format:_([`email`,`uri`,`date`,`date-time`]).optional(),default:T().optional()}),zu=D({type:_([`number`,`integer`]),title:T().optional(),description:T().optional(),minimum:g().optional(),maximum:g().optional(),default:g().optional()}),Bu=D({type:C(`string`),title:T().optional(),description:T().optional(),enum:O(T()),default:T().optional()}),Vu=D({type:C(`string`),title:T().optional(),description:T().optional(),oneOf:O(D({const:T(),title:T()})),default:T().optional()}),Hu=v([v([D({type:C(`string`),title:T().optional(),description:T().optional(),enum:O(T()),enumNames:O(T()).optional(),default:T().optional()}),v([Bu,Vu]),v([D({type:C(`array`),title:T().optional(),description:T().optional(),minItems:g().optional(),maxItems:g().optional(),items:D({type:C(`string`),enum:O(T())}),default:O(T()).optional()}),D({type:C(`array`),title:T().optional(),description:T().optional(),minItems:g().optional(),maxItems:g().optional(),items:D({anyOf:O(D({const:T(),title:T()}))}),default:O(T()).optional()})])]),Lu,Ru,zu]),Uu=v([Nc.extend({mode:C(`form`).optional(),message:T(),requestedSchema:D({type:C(`object`),properties:w(T(),Hu),required:O(T()).optional()})}),Nc.extend({mode:C(`url`),message:T(),elicitationId:T(),url:T().url()})]),Wu=Fc.extend({method:C(`elicitation/create`),params:Uu}),Gu=Ic.extend({elicitationId:T()}),Ku=Lc.extend({method:C(`notifications/elicitation/complete`),params:Gu}),qu=Rc.extend({action:_([`accept`,`decline`,`cancel`]),content:ee(e=>e===null?void 0:e,w(T(),v([T(),g(),d(),O(T())])).optional())}),Ju=D({type:C(`ref/resource`),uri:T()}),Yu=D({type:C(`ref/prompt`),name:T()}),Xu=Mc.extend({ref:v([Yu,Ju]),argument:D({name:T(),value:T()}),context:D({arguments:w(T(),T()).optional()}).optional()}),Zu=Fc.extend({method:C(`completion/complete`),params:Xu});function Qu(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function $u(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const ed=Rc.extend({completion:f({values:O(T()).max(100),total:h(g().int()),hasMore:h(d())})}),td=D({uri:T().startsWith(`file://`),name:T().optional(),_meta:w(T(),u()).optional()}),nd=Fc.extend({method:C(`roots/list`),params:Mc.optional()}),rd=Rc.extend({roots:O(td)}),id=Lc.extend({method:C(`notifications/roots/list_changed`),params:Ic.optional()});v([ul,ol,Zu,wu,ru,eu,Ll,zl,Ul,ql,Yl,bu,gu,Sl,wl,Tl,Dl]),v([Zc,pl,ll,id,xl]),v([Yc,Fu,Iu,qu,rd,Cl,El,yl]),v([ul,Pu,Wu,nd,Sl,wl,Tl,Dl]),v([Zc,pl,Eu,Zl,Gl,xu,fu,xl,Ku]),v([Yc,cl,ed,du,tu,Rl,Bl,Wl,vu,_u,Cl,El,yl]);var H=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===V.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new ad(e.elicitations,n)}return new e(t,n,r)}},ad=class extends H{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(V.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function od(e){return e===`completed`||e===`failed`||e===`cancelled`}const sd=Symbol(`Let zodToJsonSchema decide on which parser to use`),cd={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},ld=e=>typeof e==`string`?{...cd,name:e}:{...cd,...e},ud=e=>{let t=ld(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function dd(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function U(e,t,n,r,i){e[t]=n,dd(e,t,r,i)}const fd=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function pd(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?fd(t,e.currentPath):t.join(`/`)}}function md(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==B.ZodAny&&(n.items=W(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&U(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&U(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(U(n,`minItems`,e.exactLength.value,e.exactLength.message,t),U(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function hd(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?U(n,`minimum`,r.value,r.message,t):U(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),U(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?U(n,`maximum`,r.value,r.message,t):U(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),U(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:U(n,`multipleOf`,r.value,r.message,t);break}return n}function gd(){return{type:`boolean`}}function _d(e,t){return W(e.type._def,t)}const vd=(e,t)=>W(e.innerType._def,t);function yd(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>yd(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return bd(e,t)}}const bd=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:U(n,`minimum`,r.value,r.message,t);break;case`max`:U(n,`maximum`,r.value,r.message,t);break}return n};function xd(e,t){return{...W(e.innerType._def,t),default:e.defaultValue()}}function Sd(e,t){return t.effectStrategy===`input`?W(e.schema._def,t):pd(t)}function Cd(e){return{type:`string`,enum:Array.from(e.values)}}const wd=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Td(e,t){let n=[W(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),W(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(wd(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Ed(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let Dd;const Od={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Dd===void 0&&(Dd=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Dd),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function kd(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:U(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:U(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:Nd(n,`email`,r.message,t);break;case`format:idn-email`:Nd(n,`idn-email`,r.message,t);break;case`pattern:zod`:Pd(n,Od.email,r.message,t);break}break;case`url`:Nd(n,`uri`,r.message,t);break;case`uuid`:Nd(n,`uuid`,r.message,t);break;case`regex`:Pd(n,r.regex,r.message,t);break;case`cuid`:Pd(n,Od.cuid,r.message,t);break;case`cuid2`:Pd(n,Od.cuid2,r.message,t);break;case`startsWith`:Pd(n,RegExp(`^${Ad(r.value,t)}`),r.message,t);break;case`endsWith`:Pd(n,RegExp(`${Ad(r.value,t)}$`),r.message,t);break;case`datetime`:Nd(n,`date-time`,r.message,t);break;case`date`:Nd(n,`date`,r.message,t);break;case`time`:Nd(n,`time`,r.message,t);break;case`duration`:Nd(n,`duration`,r.message,t);break;case`length`:U(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),U(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:Pd(n,RegExp(Ad(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Nd(n,`ipv4`,r.message,t),r.version!==`v4`&&Nd(n,`ipv6`,r.message,t);break;case`base64url`:Pd(n,Od.base64url,r.message,t);break;case`jwt`:Pd(n,Od.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&Pd(n,Od.ipv4Cidr,r.message,t),r.version!==`v4`&&Pd(n,Od.ipv6Cidr,r.message,t);break;case`emoji`:Pd(n,Od.emoji(),r.message,t);break;case`ulid`:Pd(n,Od.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Nd(n,`binary`,r.message,t);break;case`contentEncoding:base64`:U(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:Pd(n,Od.base64,r.message,t);break}break;case`nanoid`:Pd(n,Od.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function Ad(e,t){return t.patternStrategy===`escape`?Md(e):e}const jd=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Md(e){let t=``;for(let n=0;n<e.length;n++)jd.has(e[n])||(t+=`\\`),t+=e[n];return t}function Nd(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):U(e,`format`,t,n,r)}function Pd(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Fd(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):U(e,`pattern`,Fd(t,r),n,r)}function Fd(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
19
|
+
`)}var Da=class extends Error{constructor(e,t,n){super(Ea(n)),this.request=e,this.headers=t,this.response=n,this.errors=n.errors,this.data=n.data,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}name=`GraphqlResponseError`;errors;data},Oa=[`method`,`baseUrl`,`url`,`headers`,`request`,`query`,`mediaType`,`operationName`],ka=[`query`,`method`,`url`],Aa=/\/api\/v3\/?$/;function ja(e,t,n){if(n){if(typeof t==`string`&&`query`in n)return Promise.reject(Error(`[@octokit/graphql] "query" cannot be used as variable name`));for(let e in n)if(ka.includes(e))return Promise.reject(Error(`[@octokit/graphql] "${e}" cannot be used as variable name`))}let r=typeof t==`string`?Object.assign({query:t},n):t,i=Object.keys(r).reduce((e,t)=>Oa.includes(t)?(e[t]=r[t],e):(e.variables||={},e.variables[t]=r[t],e),{}),a=r.baseUrl||e.endpoint.DEFAULTS.baseUrl;return Aa.test(a)&&(i.url=a.replace(Aa,`/api/graphql`)),e(i).then(e=>{if(e.data.errors){let t={};for(let n of Object.keys(e.headers))t[n]=e.headers[n];throw new Da(i,t,e.data)}return e.data.data})}function Ma(e,t){let n=e.defaults(t);return Object.assign((e,t)=>ja(n,e,t),{defaults:Ma.bind(null,n),endpoint:n.endpoint})}Ma(s,{headers:{"user-agent":`octokit-graphql.js/${Ta} ${o()}`},method:`POST`,url:`/graphql`});function Na(e){return Ma(e,{method:`POST`,url:`/graphql`})}var Pa=`(?:[a-zA-Z0-9_-]+)`,Fa=`\\.`,Ia=RegExp(`^${Pa}${Fa}${Pa}${Fa}${Pa}$`),La=Ia.test.bind(Ia);async function Ra(e){let t=La(e),n=e.startsWith(`v1.`)||e.startsWith(`ghs_`),r=e.startsWith(`ghu_`);return{type:`token`,token:e,tokenType:t?`app`:n?`installation`:r?`user-to-server`:`oauth`}}function za(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function Ba(e,t,n,r){let i=t.endpoint.merge(n,r);return i.headers.authorization=za(e),t(i)}var Va=function(e){if(!e)throw Error(`[@octokit/auth-token] No token passed to createTokenAuth`);if(typeof e!=`string`)throw Error(`[@octokit/auth-token] Token passed to createTokenAuth is not a string`);return e=e.replace(/^(token|bearer) +/i,``),Object.assign(Ra.bind(null,e),{hook:Ba.bind(null,e)})};const Ha=`7.0.6`,Ua=()=>{},Wa=console.warn.bind(console),Ga=console.error.bind(console);function Ka(e={}){return typeof e.debug!=`function`&&(e.debug=Ua),typeof e.info!=`function`&&(e.info=Ua),typeof e.warn!=`function`&&(e.warn=Wa),typeof e.error!=`function`&&(e.error=Ga),e}const qa=`octokit-core.js/${Ha} ${o()}`;var Ja=class{static VERSION=Ha;static defaults(e){return class extends this{constructor(...t){let n=t[0]||{};if(typeof e==`function`){super(e(n));return}super(Object.assign({},e,n,n.userAgent&&e.userAgent?{userAgent:`${n.userAgent} ${e.userAgent}`}:null))}}}static plugins=[];static plugin(...e){let t=this.plugins;return class extends this{static plugins=t.concat(e.filter(e=>!t.includes(e)))}}constructor(e={}){let t=new wa.Collection,n={baseUrl:s.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},e.request,{hook:t.bind(null,`request`)}),mediaType:{previews:[],format:``}};if(n.headers[`user-agent`]=e.userAgent?`${e.userAgent} ${qa}`:qa,e.baseUrl&&(n.baseUrl=e.baseUrl),e.previews&&(n.mediaType.previews=e.previews),e.timeZone&&(n.headers[`time-zone`]=e.timeZone),this.request=s.defaults(n),this.graphql=Na(this.request).defaults(n),this.log=Ka(e.log),this.hook=t,e.authStrategy){let{authStrategy:n,...r}=e,i=n(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:r},e.auth));t.wrap(`request`,i.hook),this.auth=i}else if(!e.auth)this.auth=async()=>({type:`unauthenticated`});else{let n=Va(e.auth);t.wrap(`request`,n.hook),this.auth=n}let r=this.constructor;for(let t=0;t<r.plugins.length;++t)Object.assign(this,r.plugins[t](this,e))}request;graphql;log;hook;auth};function Ya(e){e.hook.wrap(`request`,(t,n)=>{e.log.debug(`request`,n);let r=Date.now(),i=e.request.endpoint.parse(n),a=i.url.replace(n.baseUrl,``);return t(n).then(t=>{let n=t.headers[`x-github-request-id`];return e.log.info(`${i.method} ${a} - ${t.status} with id ${n} in ${Date.now()-r}ms`),t}).catch(t=>{let n=t.response?.headers[`x-github-request-id`]||`UNKNOWN`;throw e.log.error(`${i.method} ${a} - ${t.status} with id ${n} in ${Date.now()-r}ms`),t})})}Ya.VERSION=`6.0.0`;var Xa=`0.0.0-development`;function Za(e){if(!e.data)return{...e,data:[]};if(!((`total_count`in e.data||`total_commits`in e.data)&&!(`url`in e.data)))return e;let t=e.data.incomplete_results,n=e.data.repository_selection,r=e.data.total_count,i=e.data.total_commits;delete e.data.incomplete_results,delete e.data.repository_selection,delete e.data.total_count,delete e.data.total_commits;let a=Object.keys(e.data)[0];return e.data=e.data[a],t!==void 0&&(e.data.incomplete_results=t),n!==void 0&&(e.data.repository_selection=n),e.data.total_count=r,e.data.total_commits=i,e}function Qa(e,t,n){let r=typeof t==`function`?t.endpoint(n):e.request.endpoint(t,n),i=typeof t==`function`?t:e.request,a=r.method,o=r.headers,s=r.url;return{[Symbol.asyncIterator]:()=>({async next(){if(!s)return{done:!0};try{let e=Za(await i({method:a,url:s,headers:o}));if(s=((e.headers.link||``).match(/<([^<>]+)>;\s*rel="next"/)||[])[1],!s&&`total_commits`in e.data){let t=new URL(e.url),n=t.searchParams,r=parseInt(n.get(`page`)||`1`,10);r*parseInt(n.get(`per_page`)||`250`,10)<e.data.total_commits&&(n.set(`page`,String(r+1)),s=t.toString())}return{value:e}}catch(e){if(e.status!==409)throw e;return s=``,{value:{status:200,headers:{},data:[]}}}}})}}function $a(e,t,n,r){return typeof n==`function`&&(r=n,n=void 0),eo(e,[],Qa(e,t,n)[Symbol.asyncIterator](),r)}function eo(e,t,n,r){return n.next().then(i=>{if(i.done)return t;let a=!1;function o(){a=!0}return t=t.concat(r?r(i.value,o):i.value.data),a?t:eo(e,t,n,r)})}Object.assign($a,{iterator:Qa});function to(e){return{paginate:Object.assign($a.bind(null,e),{iterator:Qa.bind(null,e)})}}to.VERSION=Xa;const no=`17.0.0`;var ro={actions:{addCustomLabelsToSelfHostedRunnerForOrg:[`POST /orgs/{org}/actions/runners/{runner_id}/labels`],addCustomLabelsToSelfHostedRunnerForRepo:[`POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],addRepoAccessToSelfHostedRunnerGroupInOrg:[`PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}`],addSelectedRepoToOrgSecret:[`PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}`],addSelectedRepoToOrgVariable:[`PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}`],approveWorkflowRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve`],cancelWorkflowRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel`],createEnvironmentVariable:[`POST /repos/{owner}/{repo}/environments/{environment_name}/variables`],createHostedRunnerForOrg:[`POST /orgs/{org}/actions/hosted-runners`],createOrUpdateEnvironmentSecret:[`PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}`],createOrUpdateOrgSecret:[`PUT /orgs/{org}/actions/secrets/{secret_name}`],createOrUpdateRepoSecret:[`PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}`],createOrgVariable:[`POST /orgs/{org}/actions/variables`],createRegistrationTokenForOrg:[`POST /orgs/{org}/actions/runners/registration-token`],createRegistrationTokenForRepo:[`POST /repos/{owner}/{repo}/actions/runners/registration-token`],createRemoveTokenForOrg:[`POST /orgs/{org}/actions/runners/remove-token`],createRemoveTokenForRepo:[`POST /repos/{owner}/{repo}/actions/runners/remove-token`],createRepoVariable:[`POST /repos/{owner}/{repo}/actions/variables`],createWorkflowDispatch:[`POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches`],deleteActionsCacheById:[`DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}`],deleteActionsCacheByKey:[`DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}`],deleteArtifact:[`DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}`],deleteCustomImageFromOrg:[`DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}`],deleteCustomImageVersionFromOrg:[`DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}`],deleteEnvironmentSecret:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}`],deleteEnvironmentVariable:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}`],deleteHostedRunnerForOrg:[`DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}`],deleteOrgSecret:[`DELETE /orgs/{org}/actions/secrets/{secret_name}`],deleteOrgVariable:[`DELETE /orgs/{org}/actions/variables/{name}`],deleteRepoSecret:[`DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}`],deleteRepoVariable:[`DELETE /repos/{owner}/{repo}/actions/variables/{name}`],deleteSelfHostedRunnerFromOrg:[`DELETE /orgs/{org}/actions/runners/{runner_id}`],deleteSelfHostedRunnerFromRepo:[`DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}`],deleteWorkflowRun:[`DELETE /repos/{owner}/{repo}/actions/runs/{run_id}`],deleteWorkflowRunLogs:[`DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs`],disableSelectedRepositoryGithubActionsOrganization:[`DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}`],disableWorkflow:[`PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable`],downloadArtifact:[`GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}`],downloadJobLogsForWorkflowRun:[`GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs`],downloadWorkflowRunAttemptLogs:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs`],downloadWorkflowRunLogs:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs`],enableSelectedRepositoryGithubActionsOrganization:[`PUT /orgs/{org}/actions/permissions/repositories/{repository_id}`],enableWorkflow:[`PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable`],forceCancelWorkflowRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel`],generateRunnerJitconfigForOrg:[`POST /orgs/{org}/actions/runners/generate-jitconfig`],generateRunnerJitconfigForRepo:[`POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig`],getActionsCacheList:[`GET /repos/{owner}/{repo}/actions/caches`],getActionsCacheUsage:[`GET /repos/{owner}/{repo}/actions/cache/usage`],getActionsCacheUsageByRepoForOrg:[`GET /orgs/{org}/actions/cache/usage-by-repository`],getActionsCacheUsageForOrg:[`GET /orgs/{org}/actions/cache/usage`],getAllowedActionsOrganization:[`GET /orgs/{org}/actions/permissions/selected-actions`],getAllowedActionsRepository:[`GET /repos/{owner}/{repo}/actions/permissions/selected-actions`],getArtifact:[`GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}`],getCustomImageForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}`],getCustomImageVersionForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}`],getCustomOidcSubClaimForRepo:[`GET /repos/{owner}/{repo}/actions/oidc/customization/sub`],getEnvironmentPublicKey:[`GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key`],getEnvironmentSecret:[`GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}`],getEnvironmentVariable:[`GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}`],getGithubActionsDefaultWorkflowPermissionsOrganization:[`GET /orgs/{org}/actions/permissions/workflow`],getGithubActionsDefaultWorkflowPermissionsRepository:[`GET /repos/{owner}/{repo}/actions/permissions/workflow`],getGithubActionsPermissionsOrganization:[`GET /orgs/{org}/actions/permissions`],getGithubActionsPermissionsRepository:[`GET /repos/{owner}/{repo}/actions/permissions`],getHostedRunnerForOrg:[`GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}`],getHostedRunnersGithubOwnedImagesForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/github-owned`],getHostedRunnersLimitsForOrg:[`GET /orgs/{org}/actions/hosted-runners/limits`],getHostedRunnersMachineSpecsForOrg:[`GET /orgs/{org}/actions/hosted-runners/machine-sizes`],getHostedRunnersPartnerImagesForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/partner`],getHostedRunnersPlatformsForOrg:[`GET /orgs/{org}/actions/hosted-runners/platforms`],getJobForWorkflowRun:[`GET /repos/{owner}/{repo}/actions/jobs/{job_id}`],getOrgPublicKey:[`GET /orgs/{org}/actions/secrets/public-key`],getOrgSecret:[`GET /orgs/{org}/actions/secrets/{secret_name}`],getOrgVariable:[`GET /orgs/{org}/actions/variables/{name}`],getPendingDeploymentsForRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments`],getRepoPermissions:[`GET /repos/{owner}/{repo}/actions/permissions`,{},{renamed:[`actions`,`getGithubActionsPermissionsRepository`]}],getRepoPublicKey:[`GET /repos/{owner}/{repo}/actions/secrets/public-key`],getRepoSecret:[`GET /repos/{owner}/{repo}/actions/secrets/{secret_name}`],getRepoVariable:[`GET /repos/{owner}/{repo}/actions/variables/{name}`],getReviewsForRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals`],getSelfHostedRunnerForOrg:[`GET /orgs/{org}/actions/runners/{runner_id}`],getSelfHostedRunnerForRepo:[`GET /repos/{owner}/{repo}/actions/runners/{runner_id}`],getWorkflow:[`GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}`],getWorkflowAccessToRepository:[`GET /repos/{owner}/{repo}/actions/permissions/access`],getWorkflowRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}`],getWorkflowRunAttempt:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}`],getWorkflowRunUsage:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing`],getWorkflowUsage:[`GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing`],listArtifactsForRepo:[`GET /repos/{owner}/{repo}/actions/artifacts`],listCustomImageVersionsForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions`],listCustomImagesForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom`],listEnvironmentSecrets:[`GET /repos/{owner}/{repo}/environments/{environment_name}/secrets`],listEnvironmentVariables:[`GET /repos/{owner}/{repo}/environments/{environment_name}/variables`],listGithubHostedRunnersInGroupForOrg:[`GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners`],listHostedRunnersForOrg:[`GET /orgs/{org}/actions/hosted-runners`],listJobsForWorkflowRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs`],listJobsForWorkflowRunAttempt:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs`],listLabelsForSelfHostedRunnerForOrg:[`GET /orgs/{org}/actions/runners/{runner_id}/labels`],listLabelsForSelfHostedRunnerForRepo:[`GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],listOrgSecrets:[`GET /orgs/{org}/actions/secrets`],listOrgVariables:[`GET /orgs/{org}/actions/variables`],listRepoOrganizationSecrets:[`GET /repos/{owner}/{repo}/actions/organization-secrets`],listRepoOrganizationVariables:[`GET /repos/{owner}/{repo}/actions/organization-variables`],listRepoSecrets:[`GET /repos/{owner}/{repo}/actions/secrets`],listRepoVariables:[`GET /repos/{owner}/{repo}/actions/variables`],listRepoWorkflows:[`GET /repos/{owner}/{repo}/actions/workflows`],listRunnerApplicationsForOrg:[`GET /orgs/{org}/actions/runners/downloads`],listRunnerApplicationsForRepo:[`GET /repos/{owner}/{repo}/actions/runners/downloads`],listSelectedReposForOrgSecret:[`GET /orgs/{org}/actions/secrets/{secret_name}/repositories`],listSelectedReposForOrgVariable:[`GET /orgs/{org}/actions/variables/{name}/repositories`],listSelectedRepositoriesEnabledGithubActionsOrganization:[`GET /orgs/{org}/actions/permissions/repositories`],listSelfHostedRunnersForOrg:[`GET /orgs/{org}/actions/runners`],listSelfHostedRunnersForRepo:[`GET /repos/{owner}/{repo}/actions/runners`],listWorkflowRunArtifacts:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts`],listWorkflowRuns:[`GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs`],listWorkflowRunsForRepo:[`GET /repos/{owner}/{repo}/actions/runs`],reRunJobForWorkflowRun:[`POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun`],reRunWorkflow:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun`],reRunWorkflowFailedJobs:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs`],removeAllCustomLabelsFromSelfHostedRunnerForOrg:[`DELETE /orgs/{org}/actions/runners/{runner_id}/labels`],removeAllCustomLabelsFromSelfHostedRunnerForRepo:[`DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],removeCustomLabelFromSelfHostedRunnerForOrg:[`DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}`],removeCustomLabelFromSelfHostedRunnerForRepo:[`DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}`],removeSelectedRepoFromOrgSecret:[`DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}`],removeSelectedRepoFromOrgVariable:[`DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}`],reviewCustomGatesForRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule`],reviewPendingDeploymentsForRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments`],setAllowedActionsOrganization:[`PUT /orgs/{org}/actions/permissions/selected-actions`],setAllowedActionsRepository:[`PUT /repos/{owner}/{repo}/actions/permissions/selected-actions`],setCustomLabelsForSelfHostedRunnerForOrg:[`PUT /orgs/{org}/actions/runners/{runner_id}/labels`],setCustomLabelsForSelfHostedRunnerForRepo:[`PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],setCustomOidcSubClaimForRepo:[`PUT /repos/{owner}/{repo}/actions/oidc/customization/sub`],setGithubActionsDefaultWorkflowPermissionsOrganization:[`PUT /orgs/{org}/actions/permissions/workflow`],setGithubActionsDefaultWorkflowPermissionsRepository:[`PUT /repos/{owner}/{repo}/actions/permissions/workflow`],setGithubActionsPermissionsOrganization:[`PUT /orgs/{org}/actions/permissions`],setGithubActionsPermissionsRepository:[`PUT /repos/{owner}/{repo}/actions/permissions`],setSelectedReposForOrgSecret:[`PUT /orgs/{org}/actions/secrets/{secret_name}/repositories`],setSelectedReposForOrgVariable:[`PUT /orgs/{org}/actions/variables/{name}/repositories`],setSelectedRepositoriesEnabledGithubActionsOrganization:[`PUT /orgs/{org}/actions/permissions/repositories`],setWorkflowAccessToRepository:[`PUT /repos/{owner}/{repo}/actions/permissions/access`],updateEnvironmentVariable:[`PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}`],updateHostedRunnerForOrg:[`PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}`],updateOrgVariable:[`PATCH /orgs/{org}/actions/variables/{name}`],updateRepoVariable:[`PATCH /repos/{owner}/{repo}/actions/variables/{name}`]},activity:{checkRepoIsStarredByAuthenticatedUser:[`GET /user/starred/{owner}/{repo}`],deleteRepoSubscription:[`DELETE /repos/{owner}/{repo}/subscription`],deleteThreadSubscription:[`DELETE /notifications/threads/{thread_id}/subscription`],getFeeds:[`GET /feeds`],getRepoSubscription:[`GET /repos/{owner}/{repo}/subscription`],getThread:[`GET /notifications/threads/{thread_id}`],getThreadSubscriptionForAuthenticatedUser:[`GET /notifications/threads/{thread_id}/subscription`],listEventsForAuthenticatedUser:[`GET /users/{username}/events`],listNotificationsForAuthenticatedUser:[`GET /notifications`],listOrgEventsForAuthenticatedUser:[`GET /users/{username}/events/orgs/{org}`],listPublicEvents:[`GET /events`],listPublicEventsForRepoNetwork:[`GET /networks/{owner}/{repo}/events`],listPublicEventsForUser:[`GET /users/{username}/events/public`],listPublicOrgEvents:[`GET /orgs/{org}/events`],listReceivedEventsForUser:[`GET /users/{username}/received_events`],listReceivedPublicEventsForUser:[`GET /users/{username}/received_events/public`],listRepoEvents:[`GET /repos/{owner}/{repo}/events`],listRepoNotificationsForAuthenticatedUser:[`GET /repos/{owner}/{repo}/notifications`],listReposStarredByAuthenticatedUser:[`GET /user/starred`],listReposStarredByUser:[`GET /users/{username}/starred`],listReposWatchedByUser:[`GET /users/{username}/subscriptions`],listStargazersForRepo:[`GET /repos/{owner}/{repo}/stargazers`],listWatchedReposForAuthenticatedUser:[`GET /user/subscriptions`],listWatchersForRepo:[`GET /repos/{owner}/{repo}/subscribers`],markNotificationsAsRead:[`PUT /notifications`],markRepoNotificationsAsRead:[`PUT /repos/{owner}/{repo}/notifications`],markThreadAsDone:[`DELETE /notifications/threads/{thread_id}`],markThreadAsRead:[`PATCH /notifications/threads/{thread_id}`],setRepoSubscription:[`PUT /repos/{owner}/{repo}/subscription`],setThreadSubscription:[`PUT /notifications/threads/{thread_id}/subscription`],starRepoForAuthenticatedUser:[`PUT /user/starred/{owner}/{repo}`],unstarRepoForAuthenticatedUser:[`DELETE /user/starred/{owner}/{repo}`]},apps:{addRepoToInstallation:[`PUT /user/installations/{installation_id}/repositories/{repository_id}`,{},{renamed:[`apps`,`addRepoToInstallationForAuthenticatedUser`]}],addRepoToInstallationForAuthenticatedUser:[`PUT /user/installations/{installation_id}/repositories/{repository_id}`],checkToken:[`POST /applications/{client_id}/token`],createFromManifest:[`POST /app-manifests/{code}/conversions`],createInstallationAccessToken:[`POST /app/installations/{installation_id}/access_tokens`],deleteAuthorization:[`DELETE /applications/{client_id}/grant`],deleteInstallation:[`DELETE /app/installations/{installation_id}`],deleteToken:[`DELETE /applications/{client_id}/token`],getAuthenticated:[`GET /app`],getBySlug:[`GET /apps/{app_slug}`],getInstallation:[`GET /app/installations/{installation_id}`],getOrgInstallation:[`GET /orgs/{org}/installation`],getRepoInstallation:[`GET /repos/{owner}/{repo}/installation`],getSubscriptionPlanForAccount:[`GET /marketplace_listing/accounts/{account_id}`],getSubscriptionPlanForAccountStubbed:[`GET /marketplace_listing/stubbed/accounts/{account_id}`],getUserInstallation:[`GET /users/{username}/installation`],getWebhookConfigForApp:[`GET /app/hook/config`],getWebhookDelivery:[`GET /app/hook/deliveries/{delivery_id}`],listAccountsForPlan:[`GET /marketplace_listing/plans/{plan_id}/accounts`],listAccountsForPlanStubbed:[`GET /marketplace_listing/stubbed/plans/{plan_id}/accounts`],listInstallationReposForAuthenticatedUser:[`GET /user/installations/{installation_id}/repositories`],listInstallationRequestsForAuthenticatedApp:[`GET /app/installation-requests`],listInstallations:[`GET /app/installations`],listInstallationsForAuthenticatedUser:[`GET /user/installations`],listPlans:[`GET /marketplace_listing/plans`],listPlansStubbed:[`GET /marketplace_listing/stubbed/plans`],listReposAccessibleToInstallation:[`GET /installation/repositories`],listSubscriptionsForAuthenticatedUser:[`GET /user/marketplace_purchases`],listSubscriptionsForAuthenticatedUserStubbed:[`GET /user/marketplace_purchases/stubbed`],listWebhookDeliveries:[`GET /app/hook/deliveries`],redeliverWebhookDelivery:[`POST /app/hook/deliveries/{delivery_id}/attempts`],removeRepoFromInstallation:[`DELETE /user/installations/{installation_id}/repositories/{repository_id}`,{},{renamed:[`apps`,`removeRepoFromInstallationForAuthenticatedUser`]}],removeRepoFromInstallationForAuthenticatedUser:[`DELETE /user/installations/{installation_id}/repositories/{repository_id}`],resetToken:[`PATCH /applications/{client_id}/token`],revokeInstallationAccessToken:[`DELETE /installation/token`],scopeToken:[`POST /applications/{client_id}/token/scoped`],suspendInstallation:[`PUT /app/installations/{installation_id}/suspended`],unsuspendInstallation:[`DELETE /app/installations/{installation_id}/suspended`],updateWebhookConfigForApp:[`PATCH /app/hook/config`]},billing:{getGithubActionsBillingOrg:[`GET /orgs/{org}/settings/billing/actions`],getGithubActionsBillingUser:[`GET /users/{username}/settings/billing/actions`],getGithubBillingPremiumRequestUsageReportOrg:[`GET /organizations/{org}/settings/billing/premium_request/usage`],getGithubBillingPremiumRequestUsageReportUser:[`GET /users/{username}/settings/billing/premium_request/usage`],getGithubBillingUsageReportOrg:[`GET /organizations/{org}/settings/billing/usage`],getGithubBillingUsageReportUser:[`GET /users/{username}/settings/billing/usage`],getGithubPackagesBillingOrg:[`GET /orgs/{org}/settings/billing/packages`],getGithubPackagesBillingUser:[`GET /users/{username}/settings/billing/packages`],getSharedStorageBillingOrg:[`GET /orgs/{org}/settings/billing/shared-storage`],getSharedStorageBillingUser:[`GET /users/{username}/settings/billing/shared-storage`]},campaigns:{createCampaign:[`POST /orgs/{org}/campaigns`],deleteCampaign:[`DELETE /orgs/{org}/campaigns/{campaign_number}`],getCampaignSummary:[`GET /orgs/{org}/campaigns/{campaign_number}`],listOrgCampaigns:[`GET /orgs/{org}/campaigns`],updateCampaign:[`PATCH /orgs/{org}/campaigns/{campaign_number}`]},checks:{create:[`POST /repos/{owner}/{repo}/check-runs`],createSuite:[`POST /repos/{owner}/{repo}/check-suites`],get:[`GET /repos/{owner}/{repo}/check-runs/{check_run_id}`],getSuite:[`GET /repos/{owner}/{repo}/check-suites/{check_suite_id}`],listAnnotations:[`GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations`],listForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/check-runs`],listForSuite:[`GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs`],listSuitesForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/check-suites`],rerequestRun:[`POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest`],rerequestSuite:[`POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest`],setSuitesPreferences:[`PATCH /repos/{owner}/{repo}/check-suites/preferences`],update:[`PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}`]},codeScanning:{commitAutofix:[`POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits`],createAutofix:[`POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix`],createVariantAnalysis:[`POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses`],deleteAnalysis:[`DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}`],deleteCodeqlDatabase:[`DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}`],getAlert:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}`,{},{renamedParameters:{alert_id:`alert_number`}}],getAnalysis:[`GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}`],getAutofix:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix`],getCodeqlDatabase:[`GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}`],getDefaultSetup:[`GET /repos/{owner}/{repo}/code-scanning/default-setup`],getSarif:[`GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}`],getVariantAnalysis:[`GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}`],getVariantAnalysisRepoTask:[`GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}`],listAlertInstances:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances`],listAlertsForOrg:[`GET /orgs/{org}/code-scanning/alerts`],listAlertsForRepo:[`GET /repos/{owner}/{repo}/code-scanning/alerts`],listAlertsInstances:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances`,{},{renamed:[`codeScanning`,`listAlertInstances`]}],listCodeqlDatabases:[`GET /repos/{owner}/{repo}/code-scanning/codeql/databases`],listRecentAnalyses:[`GET /repos/{owner}/{repo}/code-scanning/analyses`],updateAlert:[`PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}`],updateDefaultSetup:[`PATCH /repos/{owner}/{repo}/code-scanning/default-setup`],uploadSarif:[`POST /repos/{owner}/{repo}/code-scanning/sarifs`]},codeSecurity:{attachConfiguration:[`POST /orgs/{org}/code-security/configurations/{configuration_id}/attach`],attachEnterpriseConfiguration:[`POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach`],createConfiguration:[`POST /orgs/{org}/code-security/configurations`],createConfigurationForEnterprise:[`POST /enterprises/{enterprise}/code-security/configurations`],deleteConfiguration:[`DELETE /orgs/{org}/code-security/configurations/{configuration_id}`],deleteConfigurationForEnterprise:[`DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}`],detachConfiguration:[`DELETE /orgs/{org}/code-security/configurations/detach`],getConfiguration:[`GET /orgs/{org}/code-security/configurations/{configuration_id}`],getConfigurationForRepository:[`GET /repos/{owner}/{repo}/code-security-configuration`],getConfigurationsForEnterprise:[`GET /enterprises/{enterprise}/code-security/configurations`],getConfigurationsForOrg:[`GET /orgs/{org}/code-security/configurations`],getDefaultConfigurations:[`GET /orgs/{org}/code-security/configurations/defaults`],getDefaultConfigurationsForEnterprise:[`GET /enterprises/{enterprise}/code-security/configurations/defaults`],getRepositoriesForConfiguration:[`GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories`],getRepositoriesForEnterpriseConfiguration:[`GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories`],getSingleConfigurationForEnterprise:[`GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}`],setConfigurationAsDefault:[`PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults`],setConfigurationAsDefaultForEnterprise:[`PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults`],updateConfiguration:[`PATCH /orgs/{org}/code-security/configurations/{configuration_id}`],updateEnterpriseConfiguration:[`PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}`]},codesOfConduct:{getAllCodesOfConduct:[`GET /codes_of_conduct`],getConductCode:[`GET /codes_of_conduct/{key}`]},codespaces:{addRepositoryForSecretForAuthenticatedUser:[`PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}`],addSelectedRepoToOrgSecret:[`PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}`],checkPermissionsForDevcontainer:[`GET /repos/{owner}/{repo}/codespaces/permissions_check`],codespaceMachinesForAuthenticatedUser:[`GET /user/codespaces/{codespace_name}/machines`],createForAuthenticatedUser:[`POST /user/codespaces`],createOrUpdateOrgSecret:[`PUT /orgs/{org}/codespaces/secrets/{secret_name}`],createOrUpdateRepoSecret:[`PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}`],createOrUpdateSecretForAuthenticatedUser:[`PUT /user/codespaces/secrets/{secret_name}`],createWithPrForAuthenticatedUser:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces`],createWithRepoForAuthenticatedUser:[`POST /repos/{owner}/{repo}/codespaces`],deleteForAuthenticatedUser:[`DELETE /user/codespaces/{codespace_name}`],deleteFromOrganization:[`DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}`],deleteOrgSecret:[`DELETE /orgs/{org}/codespaces/secrets/{secret_name}`],deleteRepoSecret:[`DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}`],deleteSecretForAuthenticatedUser:[`DELETE /user/codespaces/secrets/{secret_name}`],exportForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/exports`],getCodespacesForUserInOrg:[`GET /orgs/{org}/members/{username}/codespaces`],getExportDetailsForAuthenticatedUser:[`GET /user/codespaces/{codespace_name}/exports/{export_id}`],getForAuthenticatedUser:[`GET /user/codespaces/{codespace_name}`],getOrgPublicKey:[`GET /orgs/{org}/codespaces/secrets/public-key`],getOrgSecret:[`GET /orgs/{org}/codespaces/secrets/{secret_name}`],getPublicKeyForAuthenticatedUser:[`GET /user/codespaces/secrets/public-key`],getRepoPublicKey:[`GET /repos/{owner}/{repo}/codespaces/secrets/public-key`],getRepoSecret:[`GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}`],getSecretForAuthenticatedUser:[`GET /user/codespaces/secrets/{secret_name}`],listDevcontainersInRepositoryForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces/devcontainers`],listForAuthenticatedUser:[`GET /user/codespaces`],listInOrganization:[`GET /orgs/{org}/codespaces`,{},{renamedParameters:{org_id:`org`}}],listInRepositoryForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces`],listOrgSecrets:[`GET /orgs/{org}/codespaces/secrets`],listRepoSecrets:[`GET /repos/{owner}/{repo}/codespaces/secrets`],listRepositoriesForSecretForAuthenticatedUser:[`GET /user/codespaces/secrets/{secret_name}/repositories`],listSecretsForAuthenticatedUser:[`GET /user/codespaces/secrets`],listSelectedReposForOrgSecret:[`GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories`],preFlightWithRepoForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces/new`],publishForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/publish`],removeRepositoryForSecretForAuthenticatedUser:[`DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}`],removeSelectedRepoFromOrgSecret:[`DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}`],repoMachinesForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces/machines`],setRepositoriesForSecretForAuthenticatedUser:[`PUT /user/codespaces/secrets/{secret_name}/repositories`],setSelectedReposForOrgSecret:[`PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories`],startForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/start`],stopForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/stop`],stopInOrganization:[`POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop`],updateForAuthenticatedUser:[`PATCH /user/codespaces/{codespace_name}`]},copilot:{addCopilotSeatsForTeams:[`POST /orgs/{org}/copilot/billing/selected_teams`],addCopilotSeatsForUsers:[`POST /orgs/{org}/copilot/billing/selected_users`],cancelCopilotSeatAssignmentForTeams:[`DELETE /orgs/{org}/copilot/billing/selected_teams`],cancelCopilotSeatAssignmentForUsers:[`DELETE /orgs/{org}/copilot/billing/selected_users`],copilotMetricsForOrganization:[`GET /orgs/{org}/copilot/metrics`],copilotMetricsForTeam:[`GET /orgs/{org}/team/{team_slug}/copilot/metrics`],getCopilotOrganizationDetails:[`GET /orgs/{org}/copilot/billing`],getCopilotSeatDetailsForUser:[`GET /orgs/{org}/members/{username}/copilot`],listCopilotSeats:[`GET /orgs/{org}/copilot/billing/seats`]},credentials:{revoke:[`POST /credentials/revoke`]},dependabot:{addSelectedRepoToOrgSecret:[`PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}`],createOrUpdateOrgSecret:[`PUT /orgs/{org}/dependabot/secrets/{secret_name}`],createOrUpdateRepoSecret:[`PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}`],deleteOrgSecret:[`DELETE /orgs/{org}/dependabot/secrets/{secret_name}`],deleteRepoSecret:[`DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}`],getAlert:[`GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}`],getOrgPublicKey:[`GET /orgs/{org}/dependabot/secrets/public-key`],getOrgSecret:[`GET /orgs/{org}/dependabot/secrets/{secret_name}`],getRepoPublicKey:[`GET /repos/{owner}/{repo}/dependabot/secrets/public-key`],getRepoSecret:[`GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}`],listAlertsForEnterprise:[`GET /enterprises/{enterprise}/dependabot/alerts`],listAlertsForOrg:[`GET /orgs/{org}/dependabot/alerts`],listAlertsForRepo:[`GET /repos/{owner}/{repo}/dependabot/alerts`],listOrgSecrets:[`GET /orgs/{org}/dependabot/secrets`],listRepoSecrets:[`GET /repos/{owner}/{repo}/dependabot/secrets`],listSelectedReposForOrgSecret:[`GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories`],removeSelectedRepoFromOrgSecret:[`DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}`],repositoryAccessForOrg:[`GET /organizations/{org}/dependabot/repository-access`],setRepositoryAccessDefaultLevel:[`PUT /organizations/{org}/dependabot/repository-access/default-level`],setSelectedReposForOrgSecret:[`PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories`],updateAlert:[`PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}`],updateRepositoryAccessForOrg:[`PATCH /organizations/{org}/dependabot/repository-access`]},dependencyGraph:{createRepositorySnapshot:[`POST /repos/{owner}/{repo}/dependency-graph/snapshots`],diffRange:[`GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}`],exportSbom:[`GET /repos/{owner}/{repo}/dependency-graph/sbom`]},emojis:{get:[`GET /emojis`]},enterpriseTeamMemberships:{add:[`PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}`],bulkAdd:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add`],bulkRemove:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove`],get:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}`],list:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships`],remove:[`DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}`]},enterpriseTeamOrganizations:{add:[`PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}`],bulkAdd:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add`],bulkRemove:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove`],delete:[`DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}`],getAssignment:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}`],getAssignments:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations`]},enterpriseTeams:{create:[`POST /enterprises/{enterprise}/teams`],delete:[`DELETE /enterprises/{enterprise}/teams/{team_slug}`],get:[`GET /enterprises/{enterprise}/teams/{team_slug}`],list:[`GET /enterprises/{enterprise}/teams`],update:[`PATCH /enterprises/{enterprise}/teams/{team_slug}`]},gists:{checkIsStarred:[`GET /gists/{gist_id}/star`],create:[`POST /gists`],createComment:[`POST /gists/{gist_id}/comments`],delete:[`DELETE /gists/{gist_id}`],deleteComment:[`DELETE /gists/{gist_id}/comments/{comment_id}`],fork:[`POST /gists/{gist_id}/forks`],get:[`GET /gists/{gist_id}`],getComment:[`GET /gists/{gist_id}/comments/{comment_id}`],getRevision:[`GET /gists/{gist_id}/{sha}`],list:[`GET /gists`],listComments:[`GET /gists/{gist_id}/comments`],listCommits:[`GET /gists/{gist_id}/commits`],listForUser:[`GET /users/{username}/gists`],listForks:[`GET /gists/{gist_id}/forks`],listPublic:[`GET /gists/public`],listStarred:[`GET /gists/starred`],star:[`PUT /gists/{gist_id}/star`],unstar:[`DELETE /gists/{gist_id}/star`],update:[`PATCH /gists/{gist_id}`],updateComment:[`PATCH /gists/{gist_id}/comments/{comment_id}`]},git:{createBlob:[`POST /repos/{owner}/{repo}/git/blobs`],createCommit:[`POST /repos/{owner}/{repo}/git/commits`],createRef:[`POST /repos/{owner}/{repo}/git/refs`],createTag:[`POST /repos/{owner}/{repo}/git/tags`],createTree:[`POST /repos/{owner}/{repo}/git/trees`],deleteRef:[`DELETE /repos/{owner}/{repo}/git/refs/{ref}`],getBlob:[`GET /repos/{owner}/{repo}/git/blobs/{file_sha}`],getCommit:[`GET /repos/{owner}/{repo}/git/commits/{commit_sha}`],getRef:[`GET /repos/{owner}/{repo}/git/ref/{ref}`],getTag:[`GET /repos/{owner}/{repo}/git/tags/{tag_sha}`],getTree:[`GET /repos/{owner}/{repo}/git/trees/{tree_sha}`],listMatchingRefs:[`GET /repos/{owner}/{repo}/git/matching-refs/{ref}`],updateRef:[`PATCH /repos/{owner}/{repo}/git/refs/{ref}`]},gitignore:{getAllTemplates:[`GET /gitignore/templates`],getTemplate:[`GET /gitignore/templates/{name}`]},hostedCompute:{createNetworkConfigurationForOrg:[`POST /orgs/{org}/settings/network-configurations`],deleteNetworkConfigurationFromOrg:[`DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}`],getNetworkConfigurationForOrg:[`GET /orgs/{org}/settings/network-configurations/{network_configuration_id}`],getNetworkSettingsForOrg:[`GET /orgs/{org}/settings/network-settings/{network_settings_id}`],listNetworkConfigurationsForOrg:[`GET /orgs/{org}/settings/network-configurations`],updateNetworkConfigurationForOrg:[`PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}`]},interactions:{getRestrictionsForAuthenticatedUser:[`GET /user/interaction-limits`],getRestrictionsForOrg:[`GET /orgs/{org}/interaction-limits`],getRestrictionsForRepo:[`GET /repos/{owner}/{repo}/interaction-limits`],getRestrictionsForYourPublicRepos:[`GET /user/interaction-limits`,{},{renamed:[`interactions`,`getRestrictionsForAuthenticatedUser`]}],removeRestrictionsForAuthenticatedUser:[`DELETE /user/interaction-limits`],removeRestrictionsForOrg:[`DELETE /orgs/{org}/interaction-limits`],removeRestrictionsForRepo:[`DELETE /repos/{owner}/{repo}/interaction-limits`],removeRestrictionsForYourPublicRepos:[`DELETE /user/interaction-limits`,{},{renamed:[`interactions`,`removeRestrictionsForAuthenticatedUser`]}],setRestrictionsForAuthenticatedUser:[`PUT /user/interaction-limits`],setRestrictionsForOrg:[`PUT /orgs/{org}/interaction-limits`],setRestrictionsForRepo:[`PUT /repos/{owner}/{repo}/interaction-limits`],setRestrictionsForYourPublicRepos:[`PUT /user/interaction-limits`,{},{renamed:[`interactions`,`setRestrictionsForAuthenticatedUser`]}]},issues:{addAssignees:[`POST /repos/{owner}/{repo}/issues/{issue_number}/assignees`],addBlockedByDependency:[`POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by`],addLabels:[`POST /repos/{owner}/{repo}/issues/{issue_number}/labels`],addSubIssue:[`POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues`],checkUserCanBeAssigned:[`GET /repos/{owner}/{repo}/assignees/{assignee}`],checkUserCanBeAssignedToIssue:[`GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}`],create:[`POST /repos/{owner}/{repo}/issues`],createComment:[`POST /repos/{owner}/{repo}/issues/{issue_number}/comments`],createLabel:[`POST /repos/{owner}/{repo}/labels`],createMilestone:[`POST /repos/{owner}/{repo}/milestones`],deleteComment:[`DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}`],deleteLabel:[`DELETE /repos/{owner}/{repo}/labels/{name}`],deleteMilestone:[`DELETE /repos/{owner}/{repo}/milestones/{milestone_number}`],get:[`GET /repos/{owner}/{repo}/issues/{issue_number}`],getComment:[`GET /repos/{owner}/{repo}/issues/comments/{comment_id}`],getEvent:[`GET /repos/{owner}/{repo}/issues/events/{event_id}`],getLabel:[`GET /repos/{owner}/{repo}/labels/{name}`],getMilestone:[`GET /repos/{owner}/{repo}/milestones/{milestone_number}`],getParent:[`GET /repos/{owner}/{repo}/issues/{issue_number}/parent`],list:[`GET /issues`],listAssignees:[`GET /repos/{owner}/{repo}/assignees`],listComments:[`GET /repos/{owner}/{repo}/issues/{issue_number}/comments`],listCommentsForRepo:[`GET /repos/{owner}/{repo}/issues/comments`],listDependenciesBlockedBy:[`GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by`],listDependenciesBlocking:[`GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking`],listEvents:[`GET /repos/{owner}/{repo}/issues/{issue_number}/events`],listEventsForRepo:[`GET /repos/{owner}/{repo}/issues/events`],listEventsForTimeline:[`GET /repos/{owner}/{repo}/issues/{issue_number}/timeline`],listForAuthenticatedUser:[`GET /user/issues`],listForOrg:[`GET /orgs/{org}/issues`],listForRepo:[`GET /repos/{owner}/{repo}/issues`],listLabelsForMilestone:[`GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels`],listLabelsForRepo:[`GET /repos/{owner}/{repo}/labels`],listLabelsOnIssue:[`GET /repos/{owner}/{repo}/issues/{issue_number}/labels`],listMilestones:[`GET /repos/{owner}/{repo}/milestones`],listSubIssues:[`GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues`],lock:[`PUT /repos/{owner}/{repo}/issues/{issue_number}/lock`],removeAllLabels:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels`],removeAssignees:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees`],removeDependencyBlockedBy:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}`],removeLabel:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}`],removeSubIssue:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue`],reprioritizeSubIssue:[`PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority`],setLabels:[`PUT /repos/{owner}/{repo}/issues/{issue_number}/labels`],unlock:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock`],update:[`PATCH /repos/{owner}/{repo}/issues/{issue_number}`],updateComment:[`PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}`],updateLabel:[`PATCH /repos/{owner}/{repo}/labels/{name}`],updateMilestone:[`PATCH /repos/{owner}/{repo}/milestones/{milestone_number}`]},licenses:{get:[`GET /licenses/{license}`],getAllCommonlyUsed:[`GET /licenses`],getForRepo:[`GET /repos/{owner}/{repo}/license`]},markdown:{render:[`POST /markdown`],renderRaw:[`POST /markdown/raw`,{headers:{"content-type":`text/plain; charset=utf-8`}}]},meta:{get:[`GET /meta`],getAllVersions:[`GET /versions`],getOctocat:[`GET /octocat`],getZen:[`GET /zen`],root:[`GET /`]},migrations:{deleteArchiveForAuthenticatedUser:[`DELETE /user/migrations/{migration_id}/archive`],deleteArchiveForOrg:[`DELETE /orgs/{org}/migrations/{migration_id}/archive`],downloadArchiveForOrg:[`GET /orgs/{org}/migrations/{migration_id}/archive`],getArchiveForAuthenticatedUser:[`GET /user/migrations/{migration_id}/archive`],getStatusForAuthenticatedUser:[`GET /user/migrations/{migration_id}`],getStatusForOrg:[`GET /orgs/{org}/migrations/{migration_id}`],listForAuthenticatedUser:[`GET /user/migrations`],listForOrg:[`GET /orgs/{org}/migrations`],listReposForAuthenticatedUser:[`GET /user/migrations/{migration_id}/repositories`],listReposForOrg:[`GET /orgs/{org}/migrations/{migration_id}/repositories`],listReposForUser:[`GET /user/migrations/{migration_id}/repositories`,{},{renamed:[`migrations`,`listReposForAuthenticatedUser`]}],startForAuthenticatedUser:[`POST /user/migrations`],startForOrg:[`POST /orgs/{org}/migrations`],unlockRepoForAuthenticatedUser:[`DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock`],unlockRepoForOrg:[`DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock`]},oidc:{getOidcCustomSubTemplateForOrg:[`GET /orgs/{org}/actions/oidc/customization/sub`],updateOidcCustomSubTemplateForOrg:[`PUT /orgs/{org}/actions/oidc/customization/sub`]},orgs:{addSecurityManagerTeam:[`PUT /orgs/{org}/security-managers/teams/{team_slug}`,{},{deprecated:`octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team`}],assignTeamToOrgRole:[`PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}`],assignUserToOrgRole:[`PUT /orgs/{org}/organization-roles/users/{username}/{role_id}`],blockUser:[`PUT /orgs/{org}/blocks/{username}`],cancelInvitation:[`DELETE /orgs/{org}/invitations/{invitation_id}`],checkBlockedUser:[`GET /orgs/{org}/blocks/{username}`],checkMembershipForUser:[`GET /orgs/{org}/members/{username}`],checkPublicMembershipForUser:[`GET /orgs/{org}/public_members/{username}`],convertMemberToOutsideCollaborator:[`PUT /orgs/{org}/outside_collaborators/{username}`],createArtifactStorageRecord:[`POST /orgs/{org}/artifacts/metadata/storage-record`],createInvitation:[`POST /orgs/{org}/invitations`],createIssueType:[`POST /orgs/{org}/issue-types`],createWebhook:[`POST /orgs/{org}/hooks`],customPropertiesForOrgsCreateOrUpdateOrganizationValues:[`PATCH /organizations/{org}/org-properties/values`],customPropertiesForOrgsGetOrganizationValues:[`GET /organizations/{org}/org-properties/values`],customPropertiesForReposCreateOrUpdateOrganizationDefinition:[`PUT /orgs/{org}/properties/schema/{custom_property_name}`],customPropertiesForReposCreateOrUpdateOrganizationDefinitions:[`PATCH /orgs/{org}/properties/schema`],customPropertiesForReposCreateOrUpdateOrganizationValues:[`PATCH /orgs/{org}/properties/values`],customPropertiesForReposDeleteOrganizationDefinition:[`DELETE /orgs/{org}/properties/schema/{custom_property_name}`],customPropertiesForReposGetOrganizationDefinition:[`GET /orgs/{org}/properties/schema/{custom_property_name}`],customPropertiesForReposGetOrganizationDefinitions:[`GET /orgs/{org}/properties/schema`],customPropertiesForReposGetOrganizationValues:[`GET /orgs/{org}/properties/values`],delete:[`DELETE /orgs/{org}`],deleteAttestationsBulk:[`POST /orgs/{org}/attestations/delete-request`],deleteAttestationsById:[`DELETE /orgs/{org}/attestations/{attestation_id}`],deleteAttestationsBySubjectDigest:[`DELETE /orgs/{org}/attestations/digest/{subject_digest}`],deleteIssueType:[`DELETE /orgs/{org}/issue-types/{issue_type_id}`],deleteWebhook:[`DELETE /orgs/{org}/hooks/{hook_id}`],disableSelectedRepositoryImmutableReleasesOrganization:[`DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}`],enableSelectedRepositoryImmutableReleasesOrganization:[`PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}`],get:[`GET /orgs/{org}`],getImmutableReleasesSettings:[`GET /orgs/{org}/settings/immutable-releases`],getImmutableReleasesSettingsRepositories:[`GET /orgs/{org}/settings/immutable-releases/repositories`],getMembershipForAuthenticatedUser:[`GET /user/memberships/orgs/{org}`],getMembershipForUser:[`GET /orgs/{org}/memberships/{username}`],getOrgRole:[`GET /orgs/{org}/organization-roles/{role_id}`],getOrgRulesetHistory:[`GET /orgs/{org}/rulesets/{ruleset_id}/history`],getOrgRulesetVersion:[`GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}`],getWebhook:[`GET /orgs/{org}/hooks/{hook_id}`],getWebhookConfigForOrg:[`GET /orgs/{org}/hooks/{hook_id}/config`],getWebhookDelivery:[`GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}`],list:[`GET /organizations`],listAppInstallations:[`GET /orgs/{org}/installations`],listArtifactStorageRecords:[`GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records`],listAttestationRepositories:[`GET /orgs/{org}/attestations/repositories`],listAttestations:[`GET /orgs/{org}/attestations/{subject_digest}`],listAttestationsBulk:[`POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}`],listBlockedUsers:[`GET /orgs/{org}/blocks`],listFailedInvitations:[`GET /orgs/{org}/failed_invitations`],listForAuthenticatedUser:[`GET /user/orgs`],listForUser:[`GET /users/{username}/orgs`],listInvitationTeams:[`GET /orgs/{org}/invitations/{invitation_id}/teams`],listIssueTypes:[`GET /orgs/{org}/issue-types`],listMembers:[`GET /orgs/{org}/members`],listMembershipsForAuthenticatedUser:[`GET /user/memberships/orgs`],listOrgRoleTeams:[`GET /orgs/{org}/organization-roles/{role_id}/teams`],listOrgRoleUsers:[`GET /orgs/{org}/organization-roles/{role_id}/users`],listOrgRoles:[`GET /orgs/{org}/organization-roles`],listOrganizationFineGrainedPermissions:[`GET /orgs/{org}/organization-fine-grained-permissions`],listOutsideCollaborators:[`GET /orgs/{org}/outside_collaborators`],listPatGrantRepositories:[`GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories`],listPatGrantRequestRepositories:[`GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories`],listPatGrantRequests:[`GET /orgs/{org}/personal-access-token-requests`],listPatGrants:[`GET /orgs/{org}/personal-access-tokens`],listPendingInvitations:[`GET /orgs/{org}/invitations`],listPublicMembers:[`GET /orgs/{org}/public_members`],listSecurityManagerTeams:[`GET /orgs/{org}/security-managers`,{},{deprecated:`octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams`}],listWebhookDeliveries:[`GET /orgs/{org}/hooks/{hook_id}/deliveries`],listWebhooks:[`GET /orgs/{org}/hooks`],pingWebhook:[`POST /orgs/{org}/hooks/{hook_id}/pings`],redeliverWebhookDelivery:[`POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts`],removeMember:[`DELETE /orgs/{org}/members/{username}`],removeMembershipForUser:[`DELETE /orgs/{org}/memberships/{username}`],removeOutsideCollaborator:[`DELETE /orgs/{org}/outside_collaborators/{username}`],removePublicMembershipForAuthenticatedUser:[`DELETE /orgs/{org}/public_members/{username}`],removeSecurityManagerTeam:[`DELETE /orgs/{org}/security-managers/teams/{team_slug}`,{},{deprecated:`octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team`}],reviewPatGrantRequest:[`POST /orgs/{org}/personal-access-token-requests/{pat_request_id}`],reviewPatGrantRequestsInBulk:[`POST /orgs/{org}/personal-access-token-requests`],revokeAllOrgRolesTeam:[`DELETE /orgs/{org}/organization-roles/teams/{team_slug}`],revokeAllOrgRolesUser:[`DELETE /orgs/{org}/organization-roles/users/{username}`],revokeOrgRoleTeam:[`DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}`],revokeOrgRoleUser:[`DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}`],setImmutableReleasesSettings:[`PUT /orgs/{org}/settings/immutable-releases`],setImmutableReleasesSettingsRepositories:[`PUT /orgs/{org}/settings/immutable-releases/repositories`],setMembershipForUser:[`PUT /orgs/{org}/memberships/{username}`],setPublicMembershipForAuthenticatedUser:[`PUT /orgs/{org}/public_members/{username}`],unblockUser:[`DELETE /orgs/{org}/blocks/{username}`],update:[`PATCH /orgs/{org}`],updateIssueType:[`PUT /orgs/{org}/issue-types/{issue_type_id}`],updateMembershipForAuthenticatedUser:[`PATCH /user/memberships/orgs/{org}`],updatePatAccess:[`POST /orgs/{org}/personal-access-tokens/{pat_id}`],updatePatAccesses:[`POST /orgs/{org}/personal-access-tokens`],updateWebhook:[`PATCH /orgs/{org}/hooks/{hook_id}`],updateWebhookConfigForOrg:[`PATCH /orgs/{org}/hooks/{hook_id}/config`]},packages:{deletePackageForAuthenticatedUser:[`DELETE /user/packages/{package_type}/{package_name}`],deletePackageForOrg:[`DELETE /orgs/{org}/packages/{package_type}/{package_name}`],deletePackageForUser:[`DELETE /users/{username}/packages/{package_type}/{package_name}`],deletePackageVersionForAuthenticatedUser:[`DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}`],deletePackageVersionForOrg:[`DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}`],deletePackageVersionForUser:[`DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}`],getAllPackageVersionsForAPackageOwnedByAnOrg:[`GET /orgs/{org}/packages/{package_type}/{package_name}/versions`,{},{renamed:[`packages`,`getAllPackageVersionsForPackageOwnedByOrg`]}],getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}/versions`,{},{renamed:[`packages`,`getAllPackageVersionsForPackageOwnedByAuthenticatedUser`]}],getAllPackageVersionsForPackageOwnedByAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}/versions`],getAllPackageVersionsForPackageOwnedByOrg:[`GET /orgs/{org}/packages/{package_type}/{package_name}/versions`],getAllPackageVersionsForPackageOwnedByUser:[`GET /users/{username}/packages/{package_type}/{package_name}/versions`],getPackageForAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}`],getPackageForOrganization:[`GET /orgs/{org}/packages/{package_type}/{package_name}`],getPackageForUser:[`GET /users/{username}/packages/{package_type}/{package_name}`],getPackageVersionForAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}`],getPackageVersionForOrganization:[`GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}`],getPackageVersionForUser:[`GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}`],listDockerMigrationConflictingPackagesForAuthenticatedUser:[`GET /user/docker/conflicts`],listDockerMigrationConflictingPackagesForOrganization:[`GET /orgs/{org}/docker/conflicts`],listDockerMigrationConflictingPackagesForUser:[`GET /users/{username}/docker/conflicts`],listPackagesForAuthenticatedUser:[`GET /user/packages`],listPackagesForOrganization:[`GET /orgs/{org}/packages`],listPackagesForUser:[`GET /users/{username}/packages`],restorePackageForAuthenticatedUser:[`POST /user/packages/{package_type}/{package_name}/restore{?token}`],restorePackageForOrg:[`POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}`],restorePackageForUser:[`POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}`],restorePackageVersionForAuthenticatedUser:[`POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore`],restorePackageVersionForOrg:[`POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore`],restorePackageVersionForUser:[`POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore`]},privateRegistries:{createOrgPrivateRegistry:[`POST /orgs/{org}/private-registries`],deleteOrgPrivateRegistry:[`DELETE /orgs/{org}/private-registries/{secret_name}`],getOrgPrivateRegistry:[`GET /orgs/{org}/private-registries/{secret_name}`],getOrgPublicKey:[`GET /orgs/{org}/private-registries/public-key`],listOrgPrivateRegistries:[`GET /orgs/{org}/private-registries`],updateOrgPrivateRegistry:[`PATCH /orgs/{org}/private-registries/{secret_name}`]},projects:{addItemForOrg:[`POST /orgs/{org}/projectsV2/{project_number}/items`],addItemForUser:[`POST /users/{username}/projectsV2/{project_number}/items`],deleteItemForOrg:[`DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}`],deleteItemForUser:[`DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}`],getFieldForOrg:[`GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}`],getFieldForUser:[`GET /users/{username}/projectsV2/{project_number}/fields/{field_id}`],getForOrg:[`GET /orgs/{org}/projectsV2/{project_number}`],getForUser:[`GET /users/{username}/projectsV2/{project_number}`],getOrgItem:[`GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}`],getUserItem:[`GET /users/{username}/projectsV2/{project_number}/items/{item_id}`],listFieldsForOrg:[`GET /orgs/{org}/projectsV2/{project_number}/fields`],listFieldsForUser:[`GET /users/{username}/projectsV2/{project_number}/fields`],listForOrg:[`GET /orgs/{org}/projectsV2`],listForUser:[`GET /users/{username}/projectsV2`],listItemsForOrg:[`GET /orgs/{org}/projectsV2/{project_number}/items`],listItemsForUser:[`GET /users/{username}/projectsV2/{project_number}/items`],updateItemForOrg:[`PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}`],updateItemForUser:[`PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}`]},pulls:{checkIfMerged:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/merge`],create:[`POST /repos/{owner}/{repo}/pulls`],createReplyForReviewComment:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies`],createReview:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews`],createReviewComment:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/comments`],deletePendingReview:[`DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}`],deleteReviewComment:[`DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}`],dismissReview:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals`],get:[`GET /repos/{owner}/{repo}/pulls/{pull_number}`],getReview:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}`],getReviewComment:[`GET /repos/{owner}/{repo}/pulls/comments/{comment_id}`],list:[`GET /repos/{owner}/{repo}/pulls`],listCommentsForReview:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments`],listCommits:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/commits`],listFiles:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/files`],listRequestedReviewers:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`],listReviewComments:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/comments`],listReviewCommentsForRepo:[`GET /repos/{owner}/{repo}/pulls/comments`],listReviews:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews`],merge:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge`],removeRequestedReviewers:[`DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`],requestReviewers:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`],submitReview:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events`],update:[`PATCH /repos/{owner}/{repo}/pulls/{pull_number}`],updateBranch:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch`],updateReview:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}`],updateReviewComment:[`PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}`]},rateLimit:{get:[`GET /rate_limit`]},reactions:{createForCommitComment:[`POST /repos/{owner}/{repo}/comments/{comment_id}/reactions`],createForIssue:[`POST /repos/{owner}/{repo}/issues/{issue_number}/reactions`],createForIssueComment:[`POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions`],createForPullRequestReviewComment:[`POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions`],createForRelease:[`POST /repos/{owner}/{repo}/releases/{release_id}/reactions`],createForTeamDiscussionCommentInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions`],createForTeamDiscussionInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions`],deleteForCommitComment:[`DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}`],deleteForIssue:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}`],deleteForIssueComment:[`DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}`],deleteForPullRequestComment:[`DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}`],deleteForRelease:[`DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}`],deleteForTeamDiscussion:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}`],deleteForTeamDiscussionComment:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}`],listForCommitComment:[`GET /repos/{owner}/{repo}/comments/{comment_id}/reactions`],listForIssue:[`GET /repos/{owner}/{repo}/issues/{issue_number}/reactions`],listForIssueComment:[`GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions`],listForPullRequestReviewComment:[`GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions`],listForRelease:[`GET /repos/{owner}/{repo}/releases/{release_id}/reactions`],listForTeamDiscussionCommentInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions`],listForTeamDiscussionInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions`]},repos:{acceptInvitation:[`PATCH /user/repository_invitations/{invitation_id}`,{},{renamed:[`repos`,`acceptInvitationForAuthenticatedUser`]}],acceptInvitationForAuthenticatedUser:[`PATCH /user/repository_invitations/{invitation_id}`],addAppAccessRestrictions:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`,{},{mapToData:`apps`}],addCollaborator:[`PUT /repos/{owner}/{repo}/collaborators/{username}`],addStatusCheckContexts:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`,{},{mapToData:`contexts`}],addTeamAccessRestrictions:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`,{},{mapToData:`teams`}],addUserAccessRestrictions:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`,{},{mapToData:`users`}],cancelPagesDeployment:[`POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel`],checkAutomatedSecurityFixes:[`GET /repos/{owner}/{repo}/automated-security-fixes`],checkCollaborator:[`GET /repos/{owner}/{repo}/collaborators/{username}`],checkImmutableReleases:[`GET /repos/{owner}/{repo}/immutable-releases`],checkPrivateVulnerabilityReporting:[`GET /repos/{owner}/{repo}/private-vulnerability-reporting`],checkVulnerabilityAlerts:[`GET /repos/{owner}/{repo}/vulnerability-alerts`],codeownersErrors:[`GET /repos/{owner}/{repo}/codeowners/errors`],compareCommits:[`GET /repos/{owner}/{repo}/compare/{base}...{head}`],compareCommitsWithBasehead:[`GET /repos/{owner}/{repo}/compare/{basehead}`],createAttestation:[`POST /repos/{owner}/{repo}/attestations`],createAutolink:[`POST /repos/{owner}/{repo}/autolinks`],createCommitComment:[`POST /repos/{owner}/{repo}/commits/{commit_sha}/comments`],createCommitSignatureProtection:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures`],createCommitStatus:[`POST /repos/{owner}/{repo}/statuses/{sha}`],createDeployKey:[`POST /repos/{owner}/{repo}/keys`],createDeployment:[`POST /repos/{owner}/{repo}/deployments`],createDeploymentBranchPolicy:[`POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies`],createDeploymentProtectionRule:[`POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules`],createDeploymentStatus:[`POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses`],createDispatchEvent:[`POST /repos/{owner}/{repo}/dispatches`],createForAuthenticatedUser:[`POST /user/repos`],createFork:[`POST /repos/{owner}/{repo}/forks`],createInOrg:[`POST /orgs/{org}/repos`],createOrUpdateEnvironment:[`PUT /repos/{owner}/{repo}/environments/{environment_name}`],createOrUpdateFileContents:[`PUT /repos/{owner}/{repo}/contents/{path}`],createOrgRuleset:[`POST /orgs/{org}/rulesets`],createPagesDeployment:[`POST /repos/{owner}/{repo}/pages/deployments`],createPagesSite:[`POST /repos/{owner}/{repo}/pages`],createRelease:[`POST /repos/{owner}/{repo}/releases`],createRepoRuleset:[`POST /repos/{owner}/{repo}/rulesets`],createUsingTemplate:[`POST /repos/{template_owner}/{template_repo}/generate`],createWebhook:[`POST /repos/{owner}/{repo}/hooks`],customPropertiesForReposCreateOrUpdateRepositoryValues:[`PATCH /repos/{owner}/{repo}/properties/values`],customPropertiesForReposGetRepositoryValues:[`GET /repos/{owner}/{repo}/properties/values`],declineInvitation:[`DELETE /user/repository_invitations/{invitation_id}`,{},{renamed:[`repos`,`declineInvitationForAuthenticatedUser`]}],declineInvitationForAuthenticatedUser:[`DELETE /user/repository_invitations/{invitation_id}`],delete:[`DELETE /repos/{owner}/{repo}`],deleteAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions`],deleteAdminBranchProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins`],deleteAnEnvironment:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}`],deleteAutolink:[`DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}`],deleteBranchProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection`],deleteCommitComment:[`DELETE /repos/{owner}/{repo}/comments/{comment_id}`],deleteCommitSignatureProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures`],deleteDeployKey:[`DELETE /repos/{owner}/{repo}/keys/{key_id}`],deleteDeployment:[`DELETE /repos/{owner}/{repo}/deployments/{deployment_id}`],deleteDeploymentBranchPolicy:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}`],deleteFile:[`DELETE /repos/{owner}/{repo}/contents/{path}`],deleteInvitation:[`DELETE /repos/{owner}/{repo}/invitations/{invitation_id}`],deleteOrgRuleset:[`DELETE /orgs/{org}/rulesets/{ruleset_id}`],deletePagesSite:[`DELETE /repos/{owner}/{repo}/pages`],deletePullRequestReviewProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews`],deleteRelease:[`DELETE /repos/{owner}/{repo}/releases/{release_id}`],deleteReleaseAsset:[`DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}`],deleteRepoRuleset:[`DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}`],deleteWebhook:[`DELETE /repos/{owner}/{repo}/hooks/{hook_id}`],disableAutomatedSecurityFixes:[`DELETE /repos/{owner}/{repo}/automated-security-fixes`],disableDeploymentProtectionRule:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}`],disableImmutableReleases:[`DELETE /repos/{owner}/{repo}/immutable-releases`],disablePrivateVulnerabilityReporting:[`DELETE /repos/{owner}/{repo}/private-vulnerability-reporting`],disableVulnerabilityAlerts:[`DELETE /repos/{owner}/{repo}/vulnerability-alerts`],downloadArchive:[`GET /repos/{owner}/{repo}/zipball/{ref}`,{},{renamed:[`repos`,`downloadZipballArchive`]}],downloadTarballArchive:[`GET /repos/{owner}/{repo}/tarball/{ref}`],downloadZipballArchive:[`GET /repos/{owner}/{repo}/zipball/{ref}`],enableAutomatedSecurityFixes:[`PUT /repos/{owner}/{repo}/automated-security-fixes`],enableImmutableReleases:[`PUT /repos/{owner}/{repo}/immutable-releases`],enablePrivateVulnerabilityReporting:[`PUT /repos/{owner}/{repo}/private-vulnerability-reporting`],enableVulnerabilityAlerts:[`PUT /repos/{owner}/{repo}/vulnerability-alerts`],generateReleaseNotes:[`POST /repos/{owner}/{repo}/releases/generate-notes`],get:[`GET /repos/{owner}/{repo}`],getAccessRestrictions:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions`],getAdminBranchProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins`],getAllDeploymentProtectionRules:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules`],getAllEnvironments:[`GET /repos/{owner}/{repo}/environments`],getAllStatusCheckContexts:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`],getAllTopics:[`GET /repos/{owner}/{repo}/topics`],getAppsWithAccessToProtectedBranch:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`],getAutolink:[`GET /repos/{owner}/{repo}/autolinks/{autolink_id}`],getBranch:[`GET /repos/{owner}/{repo}/branches/{branch}`],getBranchProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection`],getBranchRules:[`GET /repos/{owner}/{repo}/rules/branches/{branch}`],getClones:[`GET /repos/{owner}/{repo}/traffic/clones`],getCodeFrequencyStats:[`GET /repos/{owner}/{repo}/stats/code_frequency`],getCollaboratorPermissionLevel:[`GET /repos/{owner}/{repo}/collaborators/{username}/permission`],getCombinedStatusForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/status`],getCommit:[`GET /repos/{owner}/{repo}/commits/{ref}`],getCommitActivityStats:[`GET /repos/{owner}/{repo}/stats/commit_activity`],getCommitComment:[`GET /repos/{owner}/{repo}/comments/{comment_id}`],getCommitSignatureProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures`],getCommunityProfileMetrics:[`GET /repos/{owner}/{repo}/community/profile`],getContent:[`GET /repos/{owner}/{repo}/contents/{path}`],getContributorsStats:[`GET /repos/{owner}/{repo}/stats/contributors`],getCustomDeploymentProtectionRule:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}`],getDeployKey:[`GET /repos/{owner}/{repo}/keys/{key_id}`],getDeployment:[`GET /repos/{owner}/{repo}/deployments/{deployment_id}`],getDeploymentBranchPolicy:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}`],getDeploymentStatus:[`GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}`],getEnvironment:[`GET /repos/{owner}/{repo}/environments/{environment_name}`],getLatestPagesBuild:[`GET /repos/{owner}/{repo}/pages/builds/latest`],getLatestRelease:[`GET /repos/{owner}/{repo}/releases/latest`],getOrgRuleSuite:[`GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}`],getOrgRuleSuites:[`GET /orgs/{org}/rulesets/rule-suites`],getOrgRuleset:[`GET /orgs/{org}/rulesets/{ruleset_id}`],getOrgRulesets:[`GET /orgs/{org}/rulesets`],getPages:[`GET /repos/{owner}/{repo}/pages`],getPagesBuild:[`GET /repos/{owner}/{repo}/pages/builds/{build_id}`],getPagesDeployment:[`GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}`],getPagesHealthCheck:[`GET /repos/{owner}/{repo}/pages/health`],getParticipationStats:[`GET /repos/{owner}/{repo}/stats/participation`],getPullRequestReviewProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews`],getPunchCardStats:[`GET /repos/{owner}/{repo}/stats/punch_card`],getReadme:[`GET /repos/{owner}/{repo}/readme`],getReadmeInDirectory:[`GET /repos/{owner}/{repo}/readme/{dir}`],getRelease:[`GET /repos/{owner}/{repo}/releases/{release_id}`],getReleaseAsset:[`GET /repos/{owner}/{repo}/releases/assets/{asset_id}`],getReleaseByTag:[`GET /repos/{owner}/{repo}/releases/tags/{tag}`],getRepoRuleSuite:[`GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}`],getRepoRuleSuites:[`GET /repos/{owner}/{repo}/rulesets/rule-suites`],getRepoRuleset:[`GET /repos/{owner}/{repo}/rulesets/{ruleset_id}`],getRepoRulesetHistory:[`GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history`],getRepoRulesetVersion:[`GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}`],getRepoRulesets:[`GET /repos/{owner}/{repo}/rulesets`],getStatusChecksProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`],getTeamsWithAccessToProtectedBranch:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`],getTopPaths:[`GET /repos/{owner}/{repo}/traffic/popular/paths`],getTopReferrers:[`GET /repos/{owner}/{repo}/traffic/popular/referrers`],getUsersWithAccessToProtectedBranch:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`],getViews:[`GET /repos/{owner}/{repo}/traffic/views`],getWebhook:[`GET /repos/{owner}/{repo}/hooks/{hook_id}`],getWebhookConfigForRepo:[`GET /repos/{owner}/{repo}/hooks/{hook_id}/config`],getWebhookDelivery:[`GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}`],listActivities:[`GET /repos/{owner}/{repo}/activity`],listAttestations:[`GET /repos/{owner}/{repo}/attestations/{subject_digest}`],listAutolinks:[`GET /repos/{owner}/{repo}/autolinks`],listBranches:[`GET /repos/{owner}/{repo}/branches`],listBranchesForHeadCommit:[`GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head`],listCollaborators:[`GET /repos/{owner}/{repo}/collaborators`],listCommentsForCommit:[`GET /repos/{owner}/{repo}/commits/{commit_sha}/comments`],listCommitCommentsForRepo:[`GET /repos/{owner}/{repo}/comments`],listCommitStatusesForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/statuses`],listCommits:[`GET /repos/{owner}/{repo}/commits`],listContributors:[`GET /repos/{owner}/{repo}/contributors`],listCustomDeploymentRuleIntegrations:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps`],listDeployKeys:[`GET /repos/{owner}/{repo}/keys`],listDeploymentBranchPolicies:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies`],listDeploymentStatuses:[`GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses`],listDeployments:[`GET /repos/{owner}/{repo}/deployments`],listForAuthenticatedUser:[`GET /user/repos`],listForOrg:[`GET /orgs/{org}/repos`],listForUser:[`GET /users/{username}/repos`],listForks:[`GET /repos/{owner}/{repo}/forks`],listInvitations:[`GET /repos/{owner}/{repo}/invitations`],listInvitationsForAuthenticatedUser:[`GET /user/repository_invitations`],listLanguages:[`GET /repos/{owner}/{repo}/languages`],listPagesBuilds:[`GET /repos/{owner}/{repo}/pages/builds`],listPublic:[`GET /repositories`],listPullRequestsAssociatedWithCommit:[`GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls`],listReleaseAssets:[`GET /repos/{owner}/{repo}/releases/{release_id}/assets`],listReleases:[`GET /repos/{owner}/{repo}/releases`],listTags:[`GET /repos/{owner}/{repo}/tags`],listTeams:[`GET /repos/{owner}/{repo}/teams`],listWebhookDeliveries:[`GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries`],listWebhooks:[`GET /repos/{owner}/{repo}/hooks`],merge:[`POST /repos/{owner}/{repo}/merges`],mergeUpstream:[`POST /repos/{owner}/{repo}/merge-upstream`],pingWebhook:[`POST /repos/{owner}/{repo}/hooks/{hook_id}/pings`],redeliverWebhookDelivery:[`POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts`],removeAppAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`,{},{mapToData:`apps`}],removeCollaborator:[`DELETE /repos/{owner}/{repo}/collaborators/{username}`],removeStatusCheckContexts:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`,{},{mapToData:`contexts`}],removeStatusCheckProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`],removeTeamAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`,{},{mapToData:`teams`}],removeUserAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`,{},{mapToData:`users`}],renameBranch:[`POST /repos/{owner}/{repo}/branches/{branch}/rename`],replaceAllTopics:[`PUT /repos/{owner}/{repo}/topics`],requestPagesBuild:[`POST /repos/{owner}/{repo}/pages/builds`],setAdminBranchProtection:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins`],setAppAccessRestrictions:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`,{},{mapToData:`apps`}],setStatusCheckContexts:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`,{},{mapToData:`contexts`}],setTeamAccessRestrictions:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`,{},{mapToData:`teams`}],setUserAccessRestrictions:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`,{},{mapToData:`users`}],testPushWebhook:[`POST /repos/{owner}/{repo}/hooks/{hook_id}/tests`],transfer:[`POST /repos/{owner}/{repo}/transfer`],update:[`PATCH /repos/{owner}/{repo}`],updateBranchProtection:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection`],updateCommitComment:[`PATCH /repos/{owner}/{repo}/comments/{comment_id}`],updateDeploymentBranchPolicy:[`PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}`],updateInformationAboutPagesSite:[`PUT /repos/{owner}/{repo}/pages`],updateInvitation:[`PATCH /repos/{owner}/{repo}/invitations/{invitation_id}`],updateOrgRuleset:[`PUT /orgs/{org}/rulesets/{ruleset_id}`],updatePullRequestReviewProtection:[`PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews`],updateRelease:[`PATCH /repos/{owner}/{repo}/releases/{release_id}`],updateReleaseAsset:[`PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}`],updateRepoRuleset:[`PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}`],updateStatusCheckPotection:[`PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`,{},{renamed:[`repos`,`updateStatusCheckProtection`]}],updateStatusCheckProtection:[`PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`],updateWebhook:[`PATCH /repos/{owner}/{repo}/hooks/{hook_id}`],updateWebhookConfigForRepo:[`PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config`],uploadReleaseAsset:[`POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}`,{baseUrl:`https://uploads.github.com`}]},search:{code:[`GET /search/code`],commits:[`GET /search/commits`],issuesAndPullRequests:[`GET /search/issues`],labels:[`GET /search/labels`],repos:[`GET /search/repositories`],topics:[`GET /search/topics`],users:[`GET /search/users`]},secretScanning:{createPushProtectionBypass:[`POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses`],getAlert:[`GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}`],getScanHistory:[`GET /repos/{owner}/{repo}/secret-scanning/scan-history`],listAlertsForOrg:[`GET /orgs/{org}/secret-scanning/alerts`],listAlertsForRepo:[`GET /repos/{owner}/{repo}/secret-scanning/alerts`],listLocationsForAlert:[`GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations`],listOrgPatternConfigs:[`GET /orgs/{org}/secret-scanning/pattern-configurations`],updateAlert:[`PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}`],updateOrgPatternConfigs:[`PATCH /orgs/{org}/secret-scanning/pattern-configurations`]},securityAdvisories:{createFork:[`POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks`],createPrivateVulnerabilityReport:[`POST /repos/{owner}/{repo}/security-advisories/reports`],createRepositoryAdvisory:[`POST /repos/{owner}/{repo}/security-advisories`],createRepositoryAdvisoryCveRequest:[`POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve`],getGlobalAdvisory:[`GET /advisories/{ghsa_id}`],getRepositoryAdvisory:[`GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}`],listGlobalAdvisories:[`GET /advisories`],listOrgRepositoryAdvisories:[`GET /orgs/{org}/security-advisories`],listRepositoryAdvisories:[`GET /repos/{owner}/{repo}/security-advisories`],updateRepositoryAdvisory:[`PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}`]},teams:{addOrUpdateMembershipForUserInOrg:[`PUT /orgs/{org}/teams/{team_slug}/memberships/{username}`],addOrUpdateRepoPermissionsInOrg:[`PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}`],checkPermissionsForRepoInOrg:[`GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}`],create:[`POST /orgs/{org}/teams`],createDiscussionCommentInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments`],createDiscussionInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions`],deleteDiscussionCommentInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}`],deleteDiscussionInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}`],deleteInOrg:[`DELETE /orgs/{org}/teams/{team_slug}`],getByName:[`GET /orgs/{org}/teams/{team_slug}`],getDiscussionCommentInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}`],getDiscussionInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}`],getMembershipForUserInOrg:[`GET /orgs/{org}/teams/{team_slug}/memberships/{username}`],list:[`GET /orgs/{org}/teams`],listChildInOrg:[`GET /orgs/{org}/teams/{team_slug}/teams`],listDiscussionCommentsInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments`],listDiscussionsInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions`],listForAuthenticatedUser:[`GET /user/teams`],listMembersInOrg:[`GET /orgs/{org}/teams/{team_slug}/members`],listPendingInvitationsInOrg:[`GET /orgs/{org}/teams/{team_slug}/invitations`],listReposInOrg:[`GET /orgs/{org}/teams/{team_slug}/repos`],removeMembershipForUserInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}`],removeRepoInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}`],updateDiscussionCommentInOrg:[`PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}`],updateDiscussionInOrg:[`PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}`],updateInOrg:[`PATCH /orgs/{org}/teams/{team_slug}`]},users:{addEmailForAuthenticated:[`POST /user/emails`,{},{renamed:[`users`,`addEmailForAuthenticatedUser`]}],addEmailForAuthenticatedUser:[`POST /user/emails`],addSocialAccountForAuthenticatedUser:[`POST /user/social_accounts`],block:[`PUT /user/blocks/{username}`],checkBlocked:[`GET /user/blocks/{username}`],checkFollowingForUser:[`GET /users/{username}/following/{target_user}`],checkPersonIsFollowedByAuthenticated:[`GET /user/following/{username}`],createGpgKeyForAuthenticated:[`POST /user/gpg_keys`,{},{renamed:[`users`,`createGpgKeyForAuthenticatedUser`]}],createGpgKeyForAuthenticatedUser:[`POST /user/gpg_keys`],createPublicSshKeyForAuthenticated:[`POST /user/keys`,{},{renamed:[`users`,`createPublicSshKeyForAuthenticatedUser`]}],createPublicSshKeyForAuthenticatedUser:[`POST /user/keys`],createSshSigningKeyForAuthenticatedUser:[`POST /user/ssh_signing_keys`],deleteAttestationsBulk:[`POST /users/{username}/attestations/delete-request`],deleteAttestationsById:[`DELETE /users/{username}/attestations/{attestation_id}`],deleteAttestationsBySubjectDigest:[`DELETE /users/{username}/attestations/digest/{subject_digest}`],deleteEmailForAuthenticated:[`DELETE /user/emails`,{},{renamed:[`users`,`deleteEmailForAuthenticatedUser`]}],deleteEmailForAuthenticatedUser:[`DELETE /user/emails`],deleteGpgKeyForAuthenticated:[`DELETE /user/gpg_keys/{gpg_key_id}`,{},{renamed:[`users`,`deleteGpgKeyForAuthenticatedUser`]}],deleteGpgKeyForAuthenticatedUser:[`DELETE /user/gpg_keys/{gpg_key_id}`],deletePublicSshKeyForAuthenticated:[`DELETE /user/keys/{key_id}`,{},{renamed:[`users`,`deletePublicSshKeyForAuthenticatedUser`]}],deletePublicSshKeyForAuthenticatedUser:[`DELETE /user/keys/{key_id}`],deleteSocialAccountForAuthenticatedUser:[`DELETE /user/social_accounts`],deleteSshSigningKeyForAuthenticatedUser:[`DELETE /user/ssh_signing_keys/{ssh_signing_key_id}`],follow:[`PUT /user/following/{username}`],getAuthenticated:[`GET /user`],getById:[`GET /user/{account_id}`],getByUsername:[`GET /users/{username}`],getContextForUser:[`GET /users/{username}/hovercard`],getGpgKeyForAuthenticated:[`GET /user/gpg_keys/{gpg_key_id}`,{},{renamed:[`users`,`getGpgKeyForAuthenticatedUser`]}],getGpgKeyForAuthenticatedUser:[`GET /user/gpg_keys/{gpg_key_id}`],getPublicSshKeyForAuthenticated:[`GET /user/keys/{key_id}`,{},{renamed:[`users`,`getPublicSshKeyForAuthenticatedUser`]}],getPublicSshKeyForAuthenticatedUser:[`GET /user/keys/{key_id}`],getSshSigningKeyForAuthenticatedUser:[`GET /user/ssh_signing_keys/{ssh_signing_key_id}`],list:[`GET /users`],listAttestations:[`GET /users/{username}/attestations/{subject_digest}`],listAttestationsBulk:[`POST /users/{username}/attestations/bulk-list{?per_page,before,after}`],listBlockedByAuthenticated:[`GET /user/blocks`,{},{renamed:[`users`,`listBlockedByAuthenticatedUser`]}],listBlockedByAuthenticatedUser:[`GET /user/blocks`],listEmailsForAuthenticated:[`GET /user/emails`,{},{renamed:[`users`,`listEmailsForAuthenticatedUser`]}],listEmailsForAuthenticatedUser:[`GET /user/emails`],listFollowedByAuthenticated:[`GET /user/following`,{},{renamed:[`users`,`listFollowedByAuthenticatedUser`]}],listFollowedByAuthenticatedUser:[`GET /user/following`],listFollowersForAuthenticatedUser:[`GET /user/followers`],listFollowersForUser:[`GET /users/{username}/followers`],listFollowingForUser:[`GET /users/{username}/following`],listGpgKeysForAuthenticated:[`GET /user/gpg_keys`,{},{renamed:[`users`,`listGpgKeysForAuthenticatedUser`]}],listGpgKeysForAuthenticatedUser:[`GET /user/gpg_keys`],listGpgKeysForUser:[`GET /users/{username}/gpg_keys`],listPublicEmailsForAuthenticated:[`GET /user/public_emails`,{},{renamed:[`users`,`listPublicEmailsForAuthenticatedUser`]}],listPublicEmailsForAuthenticatedUser:[`GET /user/public_emails`],listPublicKeysForUser:[`GET /users/{username}/keys`],listPublicSshKeysForAuthenticated:[`GET /user/keys`,{},{renamed:[`users`,`listPublicSshKeysForAuthenticatedUser`]}],listPublicSshKeysForAuthenticatedUser:[`GET /user/keys`],listSocialAccountsForAuthenticatedUser:[`GET /user/social_accounts`],listSocialAccountsForUser:[`GET /users/{username}/social_accounts`],listSshSigningKeysForAuthenticatedUser:[`GET /user/ssh_signing_keys`],listSshSigningKeysForUser:[`GET /users/{username}/ssh_signing_keys`],setPrimaryEmailVisibilityForAuthenticated:[`PATCH /user/email/visibility`,{},{renamed:[`users`,`setPrimaryEmailVisibilityForAuthenticatedUser`]}],setPrimaryEmailVisibilityForAuthenticatedUser:[`PATCH /user/email/visibility`],unblock:[`DELETE /user/blocks/{username}`],unfollow:[`DELETE /user/following/{username}`],updateAuthenticated:[`PATCH /user`]}};const io=new Map;for(let[e,t]of Object.entries(ro))for(let[n,r]of Object.entries(t)){let[t,i,a]=r,[o,s]=t.split(/ /),c=Object.assign({method:o,url:s},i);io.has(e)||io.set(e,new Map),io.get(e).set(n,{scope:e,methodName:n,endpointDefaults:c,decorations:a})}const ao={has({scope:e},t){return io.get(e).has(t)},getOwnPropertyDescriptor(e,t){return{value:this.get(e,t),configurable:!0,writable:!0,enumerable:!0}},defineProperty(e,t,n){return Object.defineProperty(e.cache,t,n),!0},deleteProperty(e,t){return delete e.cache[t],!0},ownKeys({scope:e}){return[...io.get(e).keys()]},set(e,t,n){return e.cache[t]=n},get({octokit:e,scope:t,cache:n},r){if(n[r])return n[r];let i=io.get(t).get(r);if(!i)return;let{endpointDefaults:a,decorations:o}=i;return o?n[r]=so(e,t,r,a,o):n[r]=e.request.defaults(a),n[r]}};function oo(e){let t={};for(let n of io.keys())t[n]=new Proxy({octokit:e,scope:n,cache:{}},ao);return t}function so(e,t,n,r,i){let a=e.request.defaults(r);function o(...r){let o=a.endpoint.merge(...r);if(i.mapToData)return o=Object.assign({},o,{data:o[i.mapToData],[i.mapToData]:void 0}),a(o);if(i.renamed){let[r,a]=i.renamed;e.log.warn(`octokit.${t}.${n}() has been renamed to octokit.${r}.${a}()`)}if(i.deprecated&&e.log.warn(i.deprecated),i.renamedParameters){let o=a.endpoint.merge(...r);for(let[r,a]of Object.entries(i.renamedParameters))r in o&&(e.log.warn(`"${r}" parameter is deprecated for "octokit.${t}.${n}()". Use "${a}" instead`),a in o||(o[a]=o[r]),delete o[r]);return a(o)}return a(...r)}return Object.assign(o,a)}function co(e){return{rest:oo(e)}}co.VERSION=no;function lo(e){let t=oo(e);return{...t,rest:t}}lo.VERSION=no;const uo=Ja.plugin(Ya,lo,to).defaults({userAgent:`octokit-rest.js/22.0.1`});async function fo(e,t,n){let{host:r,json:i}=e;Ar(r);let a=await(n??(()=>ha({message:`Enter PAT:`})))();a||(process.stderr.write(`No token provided
|
|
20
|
+
`),process.exit(1));let o=r===`github.com`?void 0:`https://${r}/api/v3`,s=new uo({auth:a,...o?{baseUrl:o}:{}}),c=`unknown`,l,u;try{let{data:e}=await s.users.getAuthenticated();c=e.login,l=e.name??void 0,u=e.email??void 0}catch{process.stderr.write(`Token validation failed
|
|
21
|
+
`),process.exit(1)}await t.set(r,c,a,{gitProtocol:`https`,name:l,email:u}),i?process.stdout.write(`${JSON.stringify({type:`complete`,host:r,login:c})}\n`):process.stderr.write(`✓ PAT stored for ${c} on ${r}\n`)}function po(e){return new r(`pat`).description(`Store a Personal Access Token`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await fo(t,await e())})}async function mo(e,t){let{host:n,json:r}=e;Ar(n);let i=await t.get(n);i??(process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new uo({auth:i.token,...a?{baseUrl:a}:{}}),s=[];for await(let e of o.paginate.iterator(o.repos.listForAuthenticatedUser,{per_page:100,sort:`updated`}))for(let t of e.data)s.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private});if(r)process.stdout.write(`${JSON.stringify({type:`repos`,host:n,repos:s})}\n`);else for(let e of s)process.stdout.write(`${e.full_name} ${e.clone_url}\n`)}function ho(e){return new r(`repos`).description(`List accessible repositories`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await mo(t,await e())})}async function go(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function _o(e){return new r(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await go(t,await e())})}async function vo(e,t){let{host:n,json:r}=e;Ar(n);let i=await t.get(n);i??(r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!1})}\n`):process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new uo({auth:i.token,...a?{baseUrl:a}:{}});try{let{data:e}=await o.users.getAuthenticated();r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!0,login:e.login,name:e.name,email:e.email})}\n`):process.stderr.write(`✓ Logged in as ${e.login} on ${n}\n`)}catch{r?process.stdout.write(JSON.stringify({type:`status`,host:n,authenticated:!1,error:`token invalid`})+`
|
|
22
|
+
`):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function yo(e){return new r(`status`).description(`Show authentication status`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await vo(t,await e())})}function bo(e){let t=new r(`auth`);t.description(`GitHub authentication management`);let n=()=>lr(),i=e??(()=>({}));return t.addCommand(Nr(i,n)),t.addCommand(yo(n)),t.addCommand(ho(n)),t.addCommand(_o(n)),t.addCommand(po(n)),t.addCommand(pr(n)),t}function xo(e,t,n={}){let r=xe(e,t);if(!An(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(Nn(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||typeof i.pid!=`number`)return{status:`corrupt`,lockPath:r};let a=i,o=n.host??Vn();return a.hostname===o?(n.isAlive??be)(a.pid)?{status:`alive`,lockPath:r,lock:a}:{status:`dead-pid`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function So(e,t){let n=[];for(let[r,i]of[[`server`,e],[`ui`,t]])(i.status===`dead-pid`||i.status===`corrupt`)&&n.push({name:r,lockPath:i.lockPath,reason:i.status});return{prune:n}}function Co(e){let t=e.inspect??(t=>xo(e.lockDir,t)),n=e.unlink??(e=>Ln(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=So(t(`server`),t(`ui`));if(a.prune.length===0)return r(`No stale locks.`),{pruned:[],failed:[]};let o=[],s=[];for(let e of a.prune)try{n(e.lockPath),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}if(o.length>0){let e=o.map(e=>`${e.name} (${e.reason})`).join(`, `);r(`Pruned ${o.length} stale lock${o.length===1?``:`s`}: ${e}`)}return s.length>0&&i(`Failed to prune: ${s.map(({target:e,error:t})=>`${e.name} (${e.lockPath}): ${t}`).join(`; `)}`),{pruned:o,failed:s}}function wo(e){return new r(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{Co({lockDir:_e(ve(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}function To(){try{let e=yn(`gh`,[`auth`,`token`],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3}).trim();return e.length===0?{available:!1}:{available:!0,token:e}}catch{return{available:!1}}}async function Eo(e,t,n={},r=To){if(!n.skipGhDetect&&r().available)return{tier:`A`,credentialArgs:[`-c`,`credential.helper=!gh auth git-credential`]};let i=await t.get(e);return i==null?{tier:`none`,credentialArgs:[]}:{tier:i.gitProtocol===`ssh`?`C`:`B`,credentialArgs:[`-c`,`credential.helper=!open-knowledge auth git-credential`]}}function Do(e){return e.replace(/:\d+$/,``)}function Oo(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Do(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Do(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Do(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}const ko=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Ao(e){let t=/^([\w ]+):\s+(\d+)%/.exec(e.trim());if(!t)return null;let n=t[1].toLowerCase(),r=Number(t[2]);for(let[e,i,a]of ko)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function jo(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Mo(e,t,n,r=process.cwd()){let i=Oo(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?Dn(r,t.dir):Dn(r,i.name);if(An(a)&&Pn(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await lr(),s=await Eo(i.hostname,o,{}),c=Se({baseDir:r,config:s.credentialArgs.length>=2?[s.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),l=-1;c.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
|
|
23
|
+
`)){let n=Ao(e);n&&n.pct!==l&&(l=n.pct,jo(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning… ${n.pct}%`))}})}),await c.clone(e,a,[`--progress`]),t.json||process.stderr.write(`
|
|
24
|
+
`);try{let{runInit:e}=await import(`./init-DWvyb5i4.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?jo(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?jo(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{No(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?jo(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function No(e){let t=Tn(e,`.git`,`info`,`exclude`);if(!An(t))return`no-exclude`;let n=Nn(t,`utf-8`),r=new Set([T,`${T}/`,`/${T}`,`/${T}/`]);return n.split(`
|
|
25
|
+
`).map(e=>e.trim()).some(e=>r.has(e))?`already-present`:(Rn(t,`${n}${n.length===0||n.endsWith(`
|
|
26
|
+
`)?``:`
|
|
27
|
+
`}${T}/\n`,`utf-8`),`appended`)}function Po(e){return new r(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).action(async(t,n,r)=>{let i=e();try{let a=await Mo(t,{json:r.json,dir:n},i);if(r.json)jo(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-BaIxHOku.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?jo(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}function Fo(e=Bn()){return Tn(e,`Downloads`,`openknowledge.skill`)}function Io(e,t,n){try{return t===`darwin`?(n(`open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired. Use --no-open and open the file manually.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function Lo(e={}){let t=Dn(e.out??Fo()),n=e.platformName??Hn(),r=e.spawnFn??bn;try{await Zn(Cn(t),{recursive:!0})}catch(e){return{status:`failed`,message:`${Le(`Error:`)} could not create output directory: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}let i;try{i=await De({outputPath:t,skipVersionCheck:!0})}catch(e){return{status:`failed`,message:`${Le(`Error:`)} build failed — ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(e.noOpen)return{status:`built`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Ie(`Built ${i.outputPath}`),Fe(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}…`),Pe(` Open the Claude Desktop App, then: ${ze(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
|
|
28
|
+
`),exitCode:0};let a=Io(i.outputPath,n,r);return a.ok?{status:`installed`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Ie(`Built ${i.outputPath}`),Fe(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}… • CLI v${i.cliVersion}`),Pe(` Claude Desktop App opened. Now upload the file manually:`),` 1. ${ze(`Customize`)} (sidebar) → ${ze(`Skills`)}`,` 2. Click the ${ze(`+`)} button`,` 3. Click ${ze(`Create skill`)}`,` 4. Click ${ze(`Upload skill`)}`,` 5. Pick ${ze(`openknowledge.skill`)} from Downloads`,Fe(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${i.outputPath}`)].join(`
|
|
29
|
+
`),exitCode:0}:{status:`built`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Ie(`Built ${i.outputPath}`),Re(` Handoff failed: ${a.message}`),Pe(` Open the Claude Desktop App, then: ${ze(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
|
|
30
|
+
`),exitCode:0}}function Ro(){return new r(`install-skill`).description("Build openknowledge.skill and open the Claude Desktop App so you can upload it for Claude Chat & Cowork. Not needed for Claude Code — `ok init` covers that separately.").option(`--out <path>`,`Custom output path (default: ~/Downloads/openknowledge.skill)`).option(`--no-open`,`Build the file but skip the OS file-association handoff`).action(async e=>{let t=await Lo({out:e.out,noOpen:!e.open});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}var j;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(j||={});var zo;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(zo||={});const M=j.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Bo=e=>{switch(typeof e){case`undefined`:return M.undefined;case`string`:return M.string;case`number`:return Number.isNaN(e)?M.nan:M.number;case`boolean`:return M.boolean;case`function`:return M.function;case`bigint`:return M.bigint;case`symbol`:return M.symbol;case`object`:return Array.isArray(e)?M.array:e===null?M.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?M.promise:typeof Map<`u`&&e instanceof Map?M.map:typeof Set<`u`&&e instanceof Set?M.set:typeof Date<`u`&&e instanceof Date?M.date:M.object;default:return M.unknown}},N=j.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var Vo=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,j.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Vo.create=e=>new Vo(e);const Ho=(e,t)=>{let n;switch(e.code){case N.invalid_type:n=e.received===M.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,j.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${j.joinValues(e.keys,`, `)}`;break;case N.invalid_union:n=`Invalid input`;break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${j.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${j.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n=`Invalid function arguments`;break;case N.invalid_return_type:n=`Invalid function return type`;break;case N.invalid_date:n=`Invalid date`;break;case N.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:j.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case N.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case N.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case N.custom:n=`Invalid input`;break;case N.invalid_intersection_types:n=`Intersection results could not be merged`;break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,j.assertNever(e)}return{message:n}};let Uo=Ho;function Wo(){return Uo}const Go=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function P(e,t){let n=Wo(),r=Go({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ho?void 0:Ho].filter(e=>!!e)});e.common.issues.push(r)}var Ko=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return F;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return F;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const F=Object.freeze({status:`aborted`}),qo=e=>({status:`dirty`,value:e}),Jo=e=>({status:`valid`,value:e}),Yo=e=>e.status===`aborted`,Xo=e=>e.status===`dirty`,Zo=e=>e.status===`valid`,Qo=e=>typeof Promise<`u`&&e instanceof Promise;var I;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(I||={});var $o=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const es=(e,t)=>{if(Zo(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new Vo(e.common.issues),this._error}}};function L(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var R=class{get description(){return this._def.description}_getType(e){return Bo(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Bo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ko,ctx:{common:e.parent.common,data:e.data,parsedType:Bo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Qo(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Bo(e)};return es(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Bo(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Zo(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Zo(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Bo(e)},r=this._parse({data:e,path:n.path,parent:n});return es(n,await(Qo(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:N.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new nc({schema:this,typeName:z.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return rc.create(this,this._def)}nullable(){return ic.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ls.create(this)}promise(){return tc.create(this,this._def)}or(e){return Bs.create([this,e],this._def)}and(e){return Ws.create(this,e,this._def)}transform(e){return new nc({...L(this._def),schema:this,typeName:z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ac({...L(this._def),innerType:this,defaultValue:t,typeName:z.ZodDefault})}brand(){return new cc({typeName:z.ZodBranded,type:this,...L(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new oc({...L(this._def),innerType:this,catchValue:t,typeName:z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return lc.create(this,e)}readonly(){return uc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const ts=/^c[^\s-]{8,}$/i,ns=/^[0-9a-z]+$/,rs=/^[0-9A-HJKMNP-TV-Z]{26}$/i,is=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,as=/^[a-z0-9_-]{21}$/i,os=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ss=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,cs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let ls;const us=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ds=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,fs=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ps=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ms=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hs=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gs=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,_s=RegExp(`^${gs}$`);function vs(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function ys(e){return RegExp(`^${vs(e)}$`)}function bs(e){let t=`${gs}T${vs(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function xs(e,t){return!!((t===`v4`||!t)&&us.test(e)||(t===`v6`||!t)&&fs.test(e))}function Ss(e,t){if(!os.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Cs(e,t){return!!((t===`v4`||!t)&&ds.test(e)||(t===`v6`||!t)&&ps.test(e))}var ws=class e extends R{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.string,received:t.parsedType}),F}let t=new Ko,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?P(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&P(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)cs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`email`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)ls||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),ls.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`emoji`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)is.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`uuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)as.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`nanoid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)ts.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)ns.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid2`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)rs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ulid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),P(n,{validation:`url`,code:N.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`regex`,code:N.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?bs(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?_s.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?ys(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?ss.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`duration`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?xs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ip`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Ss(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`jwt`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Cs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cidr`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?ms.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?hs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64url`,code:N.invalid_string,message:r.message}),t.dirty()):j.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:N.invalid_string,...I.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...I.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...I.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...I.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...I.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...I.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...I.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...I.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...I.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...I.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...I.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...I.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...I.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...I.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...I.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...I.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...I.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...I.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...I.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...I.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...I.errToObj(t)})}nonempty(e){return this.min(1,I.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ws.create=e=>new ws({checks:[],typeName:z.ZodString,coerce:e?.coerce??!1,...L(e)});function Ts(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Es=class e extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.number,received:t.parsedType}),F}let t,n=new Ko;for(let r of this._def.checks)r.kind===`int`?j.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ts(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_finite,message:r.message}),n.dirty()):j.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:I.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:I.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:I.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:I.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&j.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Es.create=e=>new Es({checks:[],typeName:z.ZodNumber,coerce:e?.coerce||!1,...L(e)});var Ds=class e extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==M.bigint)return this._getInvalidInput(e);let t,n=new Ko;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):j.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.bigint,received:t.parsedType}),F}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ds.create=e=>new Ds({checks:[],typeName:z.ZodBigInt,coerce:e?.coerce??!1,...L(e)});var Os=class extends R{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.boolean,received:t.parsedType}),F}return Jo(e.data)}};Os.create=e=>new Os({typeName:z.ZodBoolean,coerce:e?.coerce||!1,...L(e)});var ks=class e extends R{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.date,received:t.parsedType}),F}if(Number.isNaN(e.data.getTime()))return P(this._getOrReturnCtx(e),{code:N.invalid_date}),F;let t=new Ko,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):j.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:I.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:I.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};ks.create=e=>new ks({checks:[],coerce:e?.coerce||!1,typeName:z.ZodDate,...L(e)});var As=class extends R{_parse(e){if(this._getType(e)!==M.symbol){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.symbol,received:t.parsedType}),F}return Jo(e.data)}};As.create=e=>new As({typeName:z.ZodSymbol,...L(e)});var js=class extends R{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.undefined,received:t.parsedType}),F}return Jo(e.data)}};js.create=e=>new js({typeName:z.ZodUndefined,...L(e)});var Ms=class extends R{_parse(e){if(this._getType(e)!==M.null){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.null,received:t.parsedType}),F}return Jo(e.data)}};Ms.create=e=>new Ms({typeName:z.ZodNull,...L(e)});var Ns=class extends R{constructor(){super(...arguments),this._any=!0}_parse(e){return Jo(e.data)}};Ns.create=e=>new Ns({typeName:z.ZodAny,...L(e)});var Ps=class extends R{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Jo(e.data)}};Ps.create=e=>new Ps({typeName:z.ZodUnknown,...L(e)});var Fs=class extends R{_parse(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.never,received:t.parsedType}),F}};Fs.create=e=>new Fs({typeName:z.ZodNever,...L(e)});var Is=class extends R{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.void,received:t.parsedType}),F}return Jo(e.data)}};Is.create=e=>new Is({typeName:z.ZodVoid,...L(e)});var Ls=class e extends R{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==M.array)return P(t,{code:N.invalid_type,expected:M.array,received:t.parsedType}),F;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(P(t,{code:e?N.too_big:N.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(P(t,{code:N.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(P(t,{code:N.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new $o(t,e,t.path,n)))).then(e=>Ko.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new $o(t,e,t.path,n)));return Ko.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(e){return this.min(1,e)}};Ls.create=(e,t)=>new Ls({type:e,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...L(t)});function Rs(e){if(e instanceof zs){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=rc.create(Rs(r))}return new zs({...e._def,shape:()=>t})}else if(e instanceof Ls)return new Ls({...e._def,type:Rs(e.element)});else if(e instanceof rc)return rc.create(Rs(e.unwrap()));else if(e instanceof ic)return ic.create(Rs(e.unwrap()));else if(e instanceof Gs)return Gs.create(e.items.map(e=>Rs(e)));else return e}var zs=class e extends R{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:j.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==M.object){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Fs&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new $o(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Fs){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(P(n,{code:N.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new $o(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Ko.mergeObjectSync(t,e)):Ko.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return I.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:I.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of j.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of j.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Rs(this)}partial(t){let n={};for(let e of j.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of j.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof rc;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Qs(j.objectKeys(this.shape))}};zs.create=(e,t)=>new zs({shape:()=>e,unknownKeys:`strip`,catchall:Fs.create(),typeName:z.ZodObject,...L(t)}),zs.strictCreate=(e,t)=>new zs({shape:()=>e,unknownKeys:`strict`,catchall:Fs.create(),typeName:z.ZodObject,...L(t)}),zs.lazycreate=(e,t)=>new zs({shape:e,unknownKeys:`strip`,catchall:Fs.create(),typeName:z.ZodObject,...L(t)});var Bs=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new Vo(e.ctx.common.issues));return P(t,{code:N.invalid_union,unionErrors:n}),F}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new Vo(e));return P(t,{code:N.invalid_union,unionErrors:i}),F}}get options(){return this._def.options}};Bs.create=(e,t)=>new Bs({options:e,typeName:z.ZodUnion,...L(t)});const Vs=e=>e instanceof Xs?Vs(e.schema):e instanceof nc?Vs(e.innerType()):e instanceof Zs?[e.value]:e instanceof $s?e.options:e instanceof ec?j.objectValues(e.enum):e instanceof ac?Vs(e._def.innerType):e instanceof js?[void 0]:e instanceof Ms?[null]:e instanceof rc?[void 0,...Vs(e.unwrap())]:e instanceof ic?[null,...Vs(e.unwrap())]:e instanceof cc||e instanceof uc?Vs(e.unwrap()):e instanceof oc?Vs(e._def.innerType):[];var Hs=class e extends R{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.object)return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(P(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),F)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=Vs(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...L(r)})}};function Us(e,t){let n=Bo(e),r=Bo(t);if(e===t)return{valid:!0,data:e};if(n===M.object&&r===M.object){let n=j.objectKeys(t),r=j.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Us(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===M.array&&r===M.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Us(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===M.date&&r===M.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Ws=class extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Yo(e)||Yo(r))return F;let i=Us(e.value,r.value);return i.valid?((Xo(e)||Xo(r))&&t.dirty(),{status:t.value,value:i.data}):(P(n,{code:N.invalid_intersection_types}),F)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ws.create=(e,t,n)=>new Ws({left:e,right:t,typeName:z.ZodIntersection,...L(n)});var Gs=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return P(n,{code:N.invalid_type,expected:M.array,received:n.parsedType}),F;if(n.data.length<this._def.items.length)return P(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),F;!this._def.rest&&n.data.length>this._def.items.length&&(P(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new $o(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Ko.mergeArray(t,e)):Ko.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Gs.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Gs({items:e,typeName:z.ZodTuple,rest:null,...L(t)})};var Ks=class e extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return P(n,{code:N.invalid_type,expected:M.object,received:n.parsedType}),F;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new $o(n,e,n.path,e)),value:a._parse(new $o(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Ko.mergeObjectAsync(t,r):Ko.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof R?new e({keyType:t,valueType:n,typeName:z.ZodRecord,...L(r)}):new e({keyType:ws.create(),valueType:t,typeName:z.ZodRecord,...L(n)})}},qs=class extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return P(n,{code:N.invalid_type,expected:M.map,received:n.parsedType}),F;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new $o(n,e,n.path,[a,`key`])),value:i._parse(new $o(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};qs.create=(e,t,n)=>new qs({valueType:t,keyType:e,typeName:z.ZodMap,...L(n)});var Js=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return P(n,{code:N.invalid_type,expected:M.set,received:n.parsedType}),F;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(P(n,{code:N.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(P(n,{code:N.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return F;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new $o(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Js.create=(e,t)=>new Js({valueType:e,minSize:null,maxSize:null,typeName:z.ZodSet,...L(t)});var Ys=class e extends R{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.function)return P(t,{code:N.invalid_type,expected:M.function,received:t.parsedType}),F;function n(e,n){return Go({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Wo(),Ho].filter(e=>!!e),issueData:{code:N.invalid_arguments,argumentsError:n}})}function r(e,n){return Go({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Wo(),Ho].filter(e=>!!e),issueData:{code:N.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof tc){let e=this;return Jo(async function(...t){let o=new Vo([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return Jo(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new Vo([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new Vo([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Gs.create(t).rest(Ps.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Gs.create([]).rest(Ps.create()),returns:n||Ps.create(),typeName:z.ZodFunction,...L(r)})}},Xs=class extends R{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Xs.create=(e,t)=>new Xs({getter:e,typeName:z.ZodLazy,...L(t)});var Zs=class extends R{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return P(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),F}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Zs.create=(e,t)=>new Zs({value:e,typeName:z.ZodLiteral,...L(t)});function Qs(e,t){return new $s({values:e,typeName:z.ZodEnum,...L(t)})}var $s=class e extends R{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{expected:j.joinValues(n),received:t.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{received:t.data,code:N.invalid_enum_value,options:n}),F}return Jo(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};$s.create=Qs;var ec=class extends R{_parse(e){let t=j.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let e=j.objectValues(t);return P(n,{expected:j.joinValues(e),received:n.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(j.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=j.objectValues(t);return P(n,{received:n.data,code:N.invalid_enum_value,options:e}),F}return Jo(e.data)}get enum(){return this._def.values}};ec.create=(e,t)=>new ec({values:e,typeName:z.ZodNativeEnum,...L(t)});var tc=class extends R{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==M.promise&&t.common.async===!1?(P(t,{code:N.invalid_type,expected:M.promise,received:t.parsedType}),F):Jo((t.parsedType===M.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};tc.create=(e,t)=>new tc({type:e,typeName:z.ZodPromise,...L(t)});var nc=class extends R{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{P(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return F;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?qo(r.value):r});{if(t.value===`aborted`)return F;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?qo(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?F:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?F:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Zo(e))return F;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Zo(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):F);j.assertNever(r)}};nc.create=(e,t,n)=>new nc({schema:e,typeName:z.ZodEffects,effect:t,...L(n)}),nc.createWithPreprocess=(e,t,n)=>new nc({schema:t,effect:{type:`preprocess`,transform:e},typeName:z.ZodEffects,...L(n)});var rc=class extends R{_parse(e){return this._getType(e)===M.undefined?Jo(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rc.create=(e,t)=>new rc({innerType:e,typeName:z.ZodOptional,...L(t)});var ic=class extends R{_parse(e){return this._getType(e)===M.null?Jo(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ic.create=(e,t)=>new ic({innerType:e,typeName:z.ZodNullable,...L(t)});var ac=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ac.create=(e,t)=>new ac({innerType:e,typeName:z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...L(t)});var oc=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Qo(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new Vo(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new Vo(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};oc.create=(e,t)=>new oc({innerType:e,typeName:z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...L(t)});var sc=class extends R{_parse(e){if(this._getType(e)!==M.nan){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.nan,received:t.parsedType}),F}return{status:`valid`,value:e.data}}};sc.create=e=>new sc({typeName:z.ZodNaN,...L(e)});var cc=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},lc=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?F:e.status===`dirty`?(t.dirty(),qo(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?F:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:z.ZodPipeline})}},uc=class extends R{_parse(e){let t=this._def.innerType._parse(e),n=e=>(Zo(e)&&(e.value=Object.freeze(e.value)),e);return Qo(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};uc.create=(e,t)=>new uc({innerType:e,typeName:z.ZodReadonly,...L(t)}),zs.lazycreate;var z;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(z||={}),ws.create,Es.create,sc.create,Ds.create,Os.create,ks.create,As.create,js.create,Ms.create,Ns.create,Ps.create,Fs.create,Is.create,Ls.create;const dc=zs.create;zs.strictCreate,Bs.create,Hs.create,Ws.create,Gs.create,Ks.create,qs.create,Js.create,Ys.create,Xs.create,Zs.create,$s.create,ec.create,tc.create,nc.create,rc.create,ic.create,nc.createWithPreprocess,lc.create;const fc=ie(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);te.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>se(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ne(e,t,n),e.parseAsync=async(t,n)=>me(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>w(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>le(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),pc=ie(`ZodMiniObject`,(e,t)=>{fe.init(e,t),fc.init(e,t),ce(e,`shape`,()=>t.shape)});function mc(e,t){return new pc({type:`object`,shape:e??{},...ae(t)})}function hc(e){return!!e._zod}function gc(e){let t=Object.values(e);if(t.length===0)return mc({});let n=t.every(hc),r=t.every(e=>!hc(e));if(n)return mc(e);if(r)return dc(e);throw Error(`Mixed Zod versions detected in object shape.`)}function _c(e,t){return hc(e)?ne(e,t):e.safeParse(t)}async function vc(e,t){return hc(e)?await w(e,t):await e.safeParseAsync(t)}function yc(e){if(!e)return;let t;if(t=hc(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function bc(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return gc(e)}}if(hc(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function xc(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Sc(e){return e.description}function Cc(e){if(hc(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function wc(e){if(hc(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const Tc=`2025-11-25`,Ec=[Tc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Dc=`io.modelcontextprotocol/related-task`,Oc=v(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),kc=C([u(),m().int()]),Ac=u();ue({ttl:m().optional(),pollInterval:m().optional()});const jc=S({ttl:m().optional()}),Mc=S({taskId:u()}),Nc=ue({progressToken:kc.optional(),[Dc]:Mc.optional()}),Pc=S({_meta:Nc.optional()}),Fc=Pc.extend({task:jc.optional()}),Ic=e=>Fc.safeParse(e).success,Lc=S({method:u(),params:Pc.loose().optional()}),Rc=S({_meta:Nc.optional()}),zc=S({method:u(),params:Rc.loose().optional()}),Bc=ue({_meta:Nc.optional()}),Vc=C([u(),m().int()]),Hc=S({jsonrpc:h(`2.0`),id:Vc,...Lc.shape}).strict(),Uc=e=>Hc.safeParse(e).success,Wc=S({jsonrpc:h(`2.0`),...zc.shape}).strict(),Gc=e=>Wc.safeParse(e).success,Kc=S({jsonrpc:h(`2.0`),id:Vc,result:Bc}).strict(),qc=e=>Kc.safeParse(e).success;var B;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(B||={});const Jc=S({jsonrpc:h(`2.0`),id:Vc.optional(),error:S({code:m().int(),message:u(),data:pe().optional()})}).strict(),Yc=e=>Jc.safeParse(e).success,Xc=C([Hc,Wc,Kc,Jc]);C([Kc,Jc]);const Zc=Bc.strict(),Qc=Rc.extend({requestId:Vc.optional(),reason:u().optional()}),$c=zc.extend({method:h(`notifications/cancelled`),params:Qc}),el=S({icons:y(S({src:u(),mimeType:u().optional(),sizes:y(u()).optional(),theme:ge([`light`,`dark`]).optional()})).optional()}),tl=S({name:u(),title:u().optional()}),nl=tl.extend({...tl.shape,...el.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),rl=ee(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,f(S({form:f(S({applyDefaults:p().optional()}),g(u(),pe())).optional(),url:Oc.optional()}),g(u(),pe()).optional())),il=ue({list:Oc.optional(),cancel:Oc.optional(),requests:ue({sampling:ue({createMessage:Oc.optional()}).optional(),elicitation:ue({create:Oc.optional()}).optional()}).optional()}),al=ue({list:Oc.optional(),cancel:Oc.optional(),requests:ue({tools:ue({call:Oc.optional()}).optional()}).optional()}),ol=S({experimental:g(u(),Oc).optional(),sampling:S({context:Oc.optional(),tools:Oc.optional()}).optional(),elicitation:rl.optional(),roots:S({listChanged:p().optional()}).optional(),tasks:il.optional(),extensions:g(u(),Oc).optional()}),sl=Pc.extend({protocolVersion:u(),capabilities:ol,clientInfo:nl}),cl=Lc.extend({method:h(`initialize`),params:sl}),ll=S({experimental:g(u(),Oc).optional(),logging:Oc.optional(),completions:Oc.optional(),prompts:S({listChanged:p().optional()}).optional(),resources:S({subscribe:p().optional(),listChanged:p().optional()}).optional(),tools:S({listChanged:p().optional()}).optional(),tasks:al.optional(),extensions:g(u(),Oc).optional()}),ul=Bc.extend({protocolVersion:u(),capabilities:ll,serverInfo:nl,instructions:u().optional()}),dl=zc.extend({method:h(`notifications/initialized`),params:Rc.optional()}),fl=Lc.extend({method:h(`ping`),params:Pc.optional()}),pl=S({progress:m(),total:x(m()),message:x(u())}),ml=S({...Rc.shape,...pl.shape,progressToken:kc}),hl=zc.extend({method:h(`notifications/progress`),params:ml}),gl=Pc.extend({cursor:Ac.optional()}),_l=Lc.extend({params:gl.optional()}),vl=Bc.extend({nextCursor:Ac.optional()}),yl=ge([`working`,`input_required`,`completed`,`failed`,`cancelled`]),bl=S({taskId:u(),status:yl,ttl:C([m(),d()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:x(m()),statusMessage:x(u())}),xl=Bc.extend({task:bl}),Sl=Rc.merge(bl),Cl=zc.extend({method:h(`notifications/tasks/status`),params:Sl}),wl=Lc.extend({method:h(`tasks/get`),params:Pc.extend({taskId:u()})}),Tl=Bc.merge(bl),El=Lc.extend({method:h(`tasks/result`),params:Pc.extend({taskId:u()})});Bc.loose();const Dl=_l.extend({method:h(`tasks/list`)}),Ol=vl.extend({tasks:y(bl)}),kl=Lc.extend({method:h(`tasks/cancel`),params:Pc.extend({taskId:u()})}),Al=Bc.merge(bl),jl=S({uri:u(),mimeType:x(u()),_meta:g(u(),pe()).optional()}),Ml=jl.extend({text:u()}),Nl=u().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Pl=jl.extend({blob:Nl}),Fl=ge([`user`,`assistant`]),Il=S({audience:y(Fl).optional(),priority:m().min(0).max(1).optional(),lastModified:de({offset:!0}).optional()}),Ll=S({...tl.shape,...el.shape,uri:u(),description:x(u()),mimeType:x(u()),size:x(m()),annotations:Il.optional(),_meta:x(ue({}))}),Rl=S({...tl.shape,...el.shape,uriTemplate:u(),description:x(u()),mimeType:x(u()),annotations:Il.optional(),_meta:x(ue({}))}),zl=_l.extend({method:h(`resources/list`)}),Bl=vl.extend({resources:y(Ll)}),Vl=_l.extend({method:h(`resources/templates/list`)}),Hl=vl.extend({resourceTemplates:y(Rl)}),Ul=Pc.extend({uri:u()}),Wl=Ul,Gl=Lc.extend({method:h(`resources/read`),params:Wl}),Kl=Bc.extend({contents:y(C([Ml,Pl]))}),ql=zc.extend({method:h(`notifications/resources/list_changed`),params:Rc.optional()}),Jl=Ul,Yl=Lc.extend({method:h(`resources/subscribe`),params:Jl}),Xl=Ul,Zl=Lc.extend({method:h(`resources/unsubscribe`),params:Xl}),Ql=Rc.extend({uri:u()}),$l=zc.extend({method:h(`notifications/resources/updated`),params:Ql}),eu=S({name:u(),description:x(u()),required:x(p())}),tu=S({...tl.shape,...el.shape,description:x(u()),arguments:x(y(eu)),_meta:x(ue({}))}),nu=_l.extend({method:h(`prompts/list`)}),ru=vl.extend({prompts:y(tu)}),iu=Pc.extend({name:u(),arguments:g(u(),u()).optional()}),au=Lc.extend({method:h(`prompts/get`),params:iu}),ou=S({type:h(`text`),text:u(),annotations:Il.optional(),_meta:g(u(),pe()).optional()}),su=S({type:h(`image`),data:Nl,mimeType:u(),annotations:Il.optional(),_meta:g(u(),pe()).optional()}),cu=S({type:h(`audio`),data:Nl,mimeType:u(),annotations:Il.optional(),_meta:g(u(),pe()).optional()}),lu=S({type:h(`tool_use`),name:u(),id:u(),input:g(u(),pe()),_meta:g(u(),pe()).optional()}),uu=S({type:h(`resource`),resource:C([Ml,Pl]),annotations:Il.optional(),_meta:g(u(),pe()).optional()}),du=C([ou,su,cu,Ll.extend({type:h(`resource_link`)}),uu]),fu=S({role:Fl,content:du}),pu=Bc.extend({description:u().optional(),messages:y(fu)}),mu=zc.extend({method:h(`notifications/prompts/list_changed`),params:Rc.optional()}),hu=S({title:u().optional(),readOnlyHint:p().optional(),destructiveHint:p().optional(),idempotentHint:p().optional(),openWorldHint:p().optional()}),gu=S({taskSupport:ge([`required`,`optional`,`forbidden`]).optional()}),_u=S({...tl.shape,...el.shape,description:u().optional(),inputSchema:S({type:h(`object`),properties:g(u(),Oc).optional(),required:y(u()).optional()}).catchall(pe()),outputSchema:S({type:h(`object`),properties:g(u(),Oc).optional(),required:y(u()).optional()}).catchall(pe()).optional(),annotations:hu.optional(),execution:gu.optional(),_meta:g(u(),pe()).optional()}),vu=_l.extend({method:h(`tools/list`)}),yu=vl.extend({tools:y(_u)}),bu=Bc.extend({content:y(du).default([]),structuredContent:g(u(),pe()).optional(),isError:p().optional()});bu.or(Bc.extend({toolResult:pe()}));const xu=Fc.extend({name:u(),arguments:g(u(),pe()).optional()}),Su=Lc.extend({method:h(`tools/call`),params:xu}),Cu=zc.extend({method:h(`notifications/tools/list_changed`),params:Rc.optional()});S({autoRefresh:p().default(!0),debounceMs:m().int().nonnegative().default(300)});const wu=ge([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Tu=Pc.extend({level:wu}),Eu=Lc.extend({method:h(`logging/setLevel`),params:Tu}),Du=Rc.extend({level:wu,logger:u().optional(),data:pe()}),Ou=zc.extend({method:h(`notifications/message`),params:Du}),ku=S({hints:y(S({name:u().optional()})).optional(),costPriority:m().min(0).max(1).optional(),speedPriority:m().min(0).max(1).optional(),intelligencePriority:m().min(0).max(1).optional()}),Au=S({mode:ge([`auto`,`required`,`none`]).optional()}),ju=S({type:h(`tool_result`),toolUseId:u().describe(`The unique identifier for the corresponding tool call.`),content:y(du).default([]),structuredContent:S({}).loose().optional(),isError:p().optional(),_meta:g(u(),pe()).optional()}),Mu=b(`type`,[ou,su,cu]),Nu=b(`type`,[ou,su,cu,lu,ju]),Pu=S({role:Fl,content:C([Nu,y(Nu)]),_meta:g(u(),pe()).optional()}),Fu=Fc.extend({messages:y(Pu),modelPreferences:ku.optional(),systemPrompt:u().optional(),includeContext:ge([`none`,`thisServer`,`allServers`]).optional(),temperature:m().optional(),maxTokens:m().int(),stopSequences:y(u()).optional(),metadata:Oc.optional(),tools:y(_u).optional(),toolChoice:Au.optional()}),Iu=Lc.extend({method:h(`sampling/createMessage`),params:Fu}),Lu=Bc.extend({model:u(),stopReason:x(ge([`endTurn`,`stopSequence`,`maxTokens`]).or(u())),role:Fl,content:Mu}),Ru=Bc.extend({model:u(),stopReason:x(ge([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(u())),role:Fl,content:C([Nu,y(Nu)])}),zu=S({type:h(`boolean`),title:u().optional(),description:u().optional(),default:p().optional()}),Bu=S({type:h(`string`),title:u().optional(),description:u().optional(),minLength:m().optional(),maxLength:m().optional(),format:ge([`email`,`uri`,`date`,`date-time`]).optional(),default:u().optional()}),Vu=S({type:ge([`number`,`integer`]),title:u().optional(),description:u().optional(),minimum:m().optional(),maximum:m().optional(),default:m().optional()}),Hu=S({type:h(`string`),title:u().optional(),description:u().optional(),enum:y(u()),default:u().optional()}),Uu=S({type:h(`string`),title:u().optional(),description:u().optional(),oneOf:y(S({const:u(),title:u()})),default:u().optional()}),Wu=C([C([S({type:h(`string`),title:u().optional(),description:u().optional(),enum:y(u()),enumNames:y(u()).optional(),default:u().optional()}),C([Hu,Uu]),C([S({type:h(`array`),title:u().optional(),description:u().optional(),minItems:m().optional(),maxItems:m().optional(),items:S({type:h(`string`),enum:y(u())}),default:y(u()).optional()}),S({type:h(`array`),title:u().optional(),description:u().optional(),minItems:m().optional(),maxItems:m().optional(),items:S({anyOf:y(S({const:u(),title:u()}))}),default:y(u()).optional()})])]),zu,Bu,Vu]),Gu=C([Fc.extend({mode:h(`form`).optional(),message:u(),requestedSchema:S({type:h(`object`),properties:g(u(),Wu),required:y(u()).optional()})}),Fc.extend({mode:h(`url`),message:u(),elicitationId:u(),url:u().url()})]),Ku=Lc.extend({method:h(`elicitation/create`),params:Gu}),qu=Rc.extend({elicitationId:u()}),Ju=zc.extend({method:h(`notifications/elicitation/complete`),params:qu}),Yu=Bc.extend({action:ge([`accept`,`decline`,`cancel`]),content:ee(e=>e===null?void 0:e,g(u(),C([u(),m(),p(),y(u())])).optional())}),Xu=S({type:h(`ref/resource`),uri:u()}),Zu=S({type:h(`ref/prompt`),name:u()}),Qu=Pc.extend({ref:C([Zu,Xu]),argument:S({name:u(),value:u()}),context:S({arguments:g(u(),u()).optional()}).optional()}),$u=Lc.extend({method:h(`completion/complete`),params:Qu});function ed(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function td(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const nd=Bc.extend({completion:ue({values:y(u()).max(100),total:x(m().int()),hasMore:x(p())})}),rd=S({uri:u().startsWith(`file://`),name:u().optional(),_meta:g(u(),pe()).optional()}),id=Lc.extend({method:h(`roots/list`),params:Pc.optional()}),ad=Bc.extend({roots:y(rd)}),od=zc.extend({method:h(`notifications/roots/list_changed`),params:Rc.optional()});C([fl,cl,$u,Eu,au,nu,zl,Vl,Gl,Yl,Zl,Su,vu,wl,El,Dl,kl]),C([$c,hl,dl,od,Cl]),C([Zc,Lu,Ru,Yu,ad,Tl,Ol,xl]),C([fl,Iu,Ku,id,wl,El,Dl,kl]),C([$c,hl,Ou,$l,ql,Cu,mu,Cl,Ju]),C([Zc,ul,nd,pu,ru,Bl,Hl,Kl,bu,yu,Tl,Ol,xl]);var V=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===B.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new sd(e.elicitations,n)}return new e(t,n,r)}},sd=class extends V{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(B.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function cd(e){return e===`completed`||e===`failed`||e===`cancelled`}const ld=Symbol(`Let zodToJsonSchema decide on which parser to use`),ud={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},dd=e=>typeof e==`string`?{...ud,name:e}:{...ud,...e},fd=e=>{let t=dd(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function pd(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function H(e,t,n,r,i){e[t]=n,pd(e,t,r,i)}const md=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function hd(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?md(t,e.currentPath):t.join(`/`)}}function gd(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==z.ZodAny&&(n.items=U(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&H(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&H(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(H(n,`minItems`,e.exactLength.value,e.exactLength.message,t),H(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function _d(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?H(n,`minimum`,r.value,r.message,t):H(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),H(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?H(n,`maximum`,r.value,r.message,t):H(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),H(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:H(n,`multipleOf`,r.value,r.message,t);break}return n}function vd(){return{type:`boolean`}}function yd(e,t){return U(e.type._def,t)}const bd=(e,t)=>U(e.innerType._def,t);function xd(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>xd(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Sd(e,t)}}const Sd=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:H(n,`minimum`,r.value,r.message,t);break;case`max`:H(n,`maximum`,r.value,r.message,t);break}return n};function Cd(e,t){return{...U(e.innerType._def,t),default:e.defaultValue()}}function wd(e,t){return t.effectStrategy===`input`?U(e.schema._def,t):hd(t)}function Td(e){return{type:`string`,enum:Array.from(e.values)}}const Ed=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Dd(e,t){let n=[U(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),U(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Ed(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Od(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let kd;const Ad={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(kd===void 0&&(kd=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),kd),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function jd(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:H(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:H(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:Fd(n,`email`,r.message,t);break;case`format:idn-email`:Fd(n,`idn-email`,r.message,t);break;case`pattern:zod`:Id(n,Ad.email,r.message,t);break}break;case`url`:Fd(n,`uri`,r.message,t);break;case`uuid`:Fd(n,`uuid`,r.message,t);break;case`regex`:Id(n,r.regex,r.message,t);break;case`cuid`:Id(n,Ad.cuid,r.message,t);break;case`cuid2`:Id(n,Ad.cuid2,r.message,t);break;case`startsWith`:Id(n,RegExp(`^${Md(r.value,t)}`),r.message,t);break;case`endsWith`:Id(n,RegExp(`${Md(r.value,t)}$`),r.message,t);break;case`datetime`:Fd(n,`date-time`,r.message,t);break;case`date`:Fd(n,`date`,r.message,t);break;case`time`:Fd(n,`time`,r.message,t);break;case`duration`:Fd(n,`duration`,r.message,t);break;case`length`:H(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),H(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:Id(n,RegExp(Md(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Fd(n,`ipv4`,r.message,t),r.version!==`v4`&&Fd(n,`ipv6`,r.message,t);break;case`base64url`:Id(n,Ad.base64url,r.message,t);break;case`jwt`:Id(n,Ad.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&Id(n,Ad.ipv4Cidr,r.message,t),r.version!==`v4`&&Id(n,Ad.ipv6Cidr,r.message,t);break;case`emoji`:Id(n,Ad.emoji(),r.message,t);break;case`ulid`:Id(n,Ad.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Fd(n,`binary`,r.message,t);break;case`contentEncoding:base64`:H(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:Id(n,Ad.base64,r.message,t);break}break;case`nanoid`:Id(n,Ad.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function Md(e,t){return t.patternStrategy===`escape`?Pd(e):e}const Nd=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Pd(e){let t=``;for(let n=0;n<e.length;n++)Nd.has(e[n])||(t+=`\\`),t+=e[n];return t}function Fd(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):H(e,`format`,t,n,r)}function Id(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Ld(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):H(e,`pattern`,Ld(t,r),n,r)}function Ld(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
28
31
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
29
|
-
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Id(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===B.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:W(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??pd(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:W(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===B.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=kd(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===B.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===B.ZodBranded&&e.keyType._def.type._def.typeName===B.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=_d(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Ld(e,t){return t.mapStrategy===`record`?Id(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[W(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||pd(t),W(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||pd(t)],minItems:2,maxItems:2}}}function Rd(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function zd(e){return e.target===`openAi`?void 0:{not:pd({...e,currentPath:[...e.currentPath,`not`]})}}function Bd(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const Vd={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Hd(e,t){if(t.target===`openApi3`)return Ud(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Vd&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Vd[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Ud(e,t)}const Ud=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>W(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Wd(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:Vd[e.innerType._def.typeName],nullable:!0}:{type:[Vd[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=W(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=W(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Gd(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,dd(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?U(n,`minimum`,r.value,r.message,t):U(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),U(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?U(n,`maximum`,r.value,r.message,t):U(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),U(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:U(n,`multipleOf`,r.value,r.message,t);break}return n}function Kd(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=Jd(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=W(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=qd(e,t);return o!==void 0&&(r.additionalProperties=o),r}function qd(e,t){if(e.catchall._def.typeName!==`ZodNever`)return W(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Jd(e){try{return e.isOptional()}catch{return!0}}const Yd=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return W(e.innerType._def,t);let n=W(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:pd(t)},n]}:pd(t)},Xd=(e,t)=>{if(t.pipeStrategy===`input`)return W(e.in._def,t);if(t.pipeStrategy===`output`)return W(e.out._def,t);let n=W(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,W(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Zd(e,t){return W(e.type._def,t)}function Qd(e,t){let n={type:`array`,uniqueItems:!0,items:W(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&U(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&U(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function $d(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>W(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:W(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>W(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function ef(e){return{not:pd(e)}}function tf(e){return pd(e)}const nf=(e,t)=>W(e.innerType._def,t),rf=(e,t,n)=>{switch(t){case B.ZodString:return kd(e,n);case B.ZodNumber:return Gd(e,n);case B.ZodObject:return Kd(e,n);case B.ZodBigInt:return hd(e,n);case B.ZodBoolean:return gd();case B.ZodDate:return yd(e,n);case B.ZodUndefined:return ef(n);case B.ZodNull:return Bd(n);case B.ZodArray:return md(e,n);case B.ZodUnion:case B.ZodDiscriminatedUnion:return Hd(e,n);case B.ZodIntersection:return Td(e,n);case B.ZodTuple:return $d(e,n);case B.ZodRecord:return Id(e,n);case B.ZodLiteral:return Ed(e,n);case B.ZodEnum:return Cd(e);case B.ZodNativeEnum:return Rd(e);case B.ZodNullable:return Wd(e,n);case B.ZodOptional:return Yd(e,n);case B.ZodMap:return Ld(e,n);case B.ZodSet:return Qd(e,n);case B.ZodLazy:return()=>e.getter()._def;case B.ZodPromise:return Zd(e,n);case B.ZodNaN:case B.ZodNever:return zd(n);case B.ZodEffects:return Sd(e,n);case B.ZodAny:return pd(n);case B.ZodUnknown:return tf(n);case B.ZodDefault:return xd(e,n);case B.ZodBranded:return _d(e,n);case B.ZodReadonly:return nf(e,n);case B.ZodCatch:return vd(e,n);case B.ZodPipeline:return Xd(e,n);case B.ZodFunction:case B.ZodVoid:case B.ZodSymbol:return;default:return(e=>void 0)(t)}};function W(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==sd)return i}if(r&&!n){let e=af(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=rf(e,e.typeName,t),o=typeof a==`function`?W(a(),t):a;if(o&&of(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const af=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:fd(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),pd(t)):t.$refStrategy===`seen`?pd(t):void 0}},of=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),sf=(e,t)=>{let n=ud(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:W(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??pd(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=W(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??pd(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function cf(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function lf(e,t){return pc(e)?se(e,{target:cf(t?.target),io:t?.pipeStrategy??`input`}):sf(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function uf(e){let t=_c(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Sc(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function df(e,t){let n=hc(e,t);if(!n.success)throw n.error;return n.data}var ff=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Zc,e=>{this._oncancel(e)}),this.setNotificationHandler(pl,e=>{this._onprogress(e)}),this.setRequestHandler(ul,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Sl,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new H(V.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(wl,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new H(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new H(V.InvalidParams,`Task not found: ${r}`);if(!od(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(od(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[Tc]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Tl,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new H(V.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Dl,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new H(V.InvalidParams,`Task not found: ${e.params.taskId}`);if(od(n.status))throw new H(V.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new H(V.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof H?e:new H(V.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),H.fromError(V.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),Gc(e)||qc(e)?this._onresponse(e):Vc(e)?this._onrequest(e,t):Uc(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=H.fromError(V.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[Tc]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:V.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=Pc(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new H(V.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:V.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),Gc(e)?n(e):n(new H(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(Gc(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),Gc(e)?r(e):r(H.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof H?e:new H(V.InternalError,String(e))}}return}let i;try{let r=await this.request(e,yl,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new H(V.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},od(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new H(V.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new H(V.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof H?e:new H(V.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Tc]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof H?e:new H(V.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=hc(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(H.fromError(V.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Cl,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},El,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Ol,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[Tc]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Tc]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Tc]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=uf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=df(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=uf(e);this._notificationHandlers.set(n,n=>{let r=df(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&Vc(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new H(V.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new H(V.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new H(V.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new H(V.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=xl.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),od(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new H(V.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(od(a.status))throw new H(V.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=xl.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),od(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function pf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mf(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];pf(a)&&pf(i)?n[r]={...a,...i}:n[r]=i}return n}var hf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),gf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=hf();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),G=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=hf(),n=gf();var r=hf();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return r.Name}});var i=gf();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=ne(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ne(this.rhs,e,n),this}get names(){return te(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ne(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(re(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>E(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(ie(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=ne(this.condition,e,t),this}get names(){let e=super.names;return te(e,this.condition),this.else&&E(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ne(this.iteration,e,t),this}get names(){return E(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return te(te(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ne(this.iterable,e,t),this}get names(){return E(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&E(e,this.catch.names),this.finally&&E(e,this.finally.names),e}},ee=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ee.kind=`catch`;var T=class extends m{render(e){return`finally`+super.render(e)}};T.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
30
|
-
`:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new ee(e),t(e)}return n&&(this._currNode=r.finally=new T,this.code(n)),this._endBlockNode(ee,T)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function E(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function te(e,n){return n instanceof t._CodeOrName?E(e,n.names):e}function ne(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function re(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function ie(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ue(e)}`}e.not=ie;let ae=le(e.operators.AND);function oe(...e){return e.reduce(ae)}e.and=oe;let se=le(e.operators.OR);function ce(...e){return e.reduce(se)}e.or=ce;function le(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ue(n)} ${e} ${ue(r)}`}function ue(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),K=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=G(),n=hf();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0?!0:(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),_f=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),vf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=G(),n=K(),r=_f();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),yf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=vf(),n=G(),r=_f(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),bf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),xf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),Sf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=bf(),n=xf(),r=vf(),i=G(),a=K();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
|
|
32
|
+
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Rd(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===z.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:U(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??hd(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:U(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===z.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=jd(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===z.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===z.ZodBranded&&e.keyType._def.type._def.typeName===z.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=yd(e.keyType._def,t);return{...n,propertyNames:i}}return n}function zd(e,t){return t.mapStrategy===`record`?Rd(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[U(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||hd(t),U(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||hd(t)],minItems:2,maxItems:2}}}function Bd(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function Vd(e){return e.target===`openAi`?void 0:{not:hd({...e,currentPath:[...e.currentPath,`not`]})}}function Hd(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const Ud={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Wd(e,t){if(t.target===`openApi3`)return Gd(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Ud&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Ud[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Gd(e,t)}const Gd=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>U(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Kd(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:Ud[e.innerType._def.typeName],nullable:!0}:{type:[Ud[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=U(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=U(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function qd(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,pd(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?H(n,`minimum`,r.value,r.message,t):H(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),H(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?H(n,`maximum`,r.value,r.message,t):H(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),H(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:H(n,`multipleOf`,r.value,r.message,t);break}return n}function Jd(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=Xd(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=U(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=Yd(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Yd(e,t){if(e.catchall._def.typeName!==`ZodNever`)return U(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Xd(e){try{return e.isOptional()}catch{return!0}}const Zd=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return U(e.innerType._def,t);let n=U(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:hd(t)},n]}:hd(t)},Qd=(e,t)=>{if(t.pipeStrategy===`input`)return U(e.in._def,t);if(t.pipeStrategy===`output`)return U(e.out._def,t);let n=U(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,U(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function $d(e,t){return U(e.type._def,t)}function ef(e,t){let n={type:`array`,uniqueItems:!0,items:U(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&H(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&H(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function tf(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>U(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:U(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>U(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function nf(e){return{not:hd(e)}}function rf(e){return hd(e)}const af=(e,t)=>U(e.innerType._def,t),of=(e,t,n)=>{switch(t){case z.ZodString:return jd(e,n);case z.ZodNumber:return qd(e,n);case z.ZodObject:return Jd(e,n);case z.ZodBigInt:return _d(e,n);case z.ZodBoolean:return vd();case z.ZodDate:return xd(e,n);case z.ZodUndefined:return nf(n);case z.ZodNull:return Hd(n);case z.ZodArray:return gd(e,n);case z.ZodUnion:case z.ZodDiscriminatedUnion:return Wd(e,n);case z.ZodIntersection:return Dd(e,n);case z.ZodTuple:return tf(e,n);case z.ZodRecord:return Rd(e,n);case z.ZodLiteral:return Od(e,n);case z.ZodEnum:return Td(e);case z.ZodNativeEnum:return Bd(e);case z.ZodNullable:return Kd(e,n);case z.ZodOptional:return Zd(e,n);case z.ZodMap:return zd(e,n);case z.ZodSet:return ef(e,n);case z.ZodLazy:return()=>e.getter()._def;case z.ZodPromise:return $d(e,n);case z.ZodNaN:case z.ZodNever:return Vd(n);case z.ZodEffects:return wd(e,n);case z.ZodAny:return hd(n);case z.ZodUnknown:return rf(n);case z.ZodDefault:return Cd(e,n);case z.ZodBranded:return yd(e,n);case z.ZodReadonly:return af(e,n);case z.ZodCatch:return bd(e,n);case z.ZodPipeline:return Qd(e,n);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(e=>void 0)(t)}};function U(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==ld)return i}if(r&&!n){let e=sf(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=of(e,e.typeName,t),o=typeof a==`function`?U(a(),t):a;if(o&&cf(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const sf=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:md(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),hd(t)):t.$refStrategy===`seen`?hd(t):void 0}},cf=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),lf=(e,t)=>{let n=fd(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:U(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??hd(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=U(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??hd(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function uf(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function df(e,t){return hc(e)?oe(e,{target:uf(t?.target),io:t?.pipeStrategy??`input`}):lf(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function ff(e){let t=yc(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=wc(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function pf(e,t){let n=_c(e,t);if(!n.success)throw n.error;return n.data}var mf=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler($c,e=>{this._oncancel(e)}),this.setNotificationHandler(hl,e=>{this._onprogress(e)}),this.setRequestHandler(fl,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(wl,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new V(B.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(El,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new V(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new V(B.InvalidParams,`Task not found: ${r}`);if(!cd(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(cd(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[Dc]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Dl,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new V(B.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(kl,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new V(B.InvalidParams,`Task not found: ${e.params.taskId}`);if(cd(n.status))throw new V(B.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new V(B.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof V?e:new V(B.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),V.fromError(B.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),qc(e)||Yc(e)?this._onresponse(e):Uc(e)?this._onrequest(e,t):Gc(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=V.fromError(B.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[Dc]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:B.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=Ic(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new V(B.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:B.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),qc(e)?n(e):n(new V(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(qc(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),qc(e)?r(e):r(V.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof V?e:new V(B.InternalError,String(e))}}return}let i;try{let r=await this.request(e,xl,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new V(B.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},cd(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new V(B.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new V(B.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof V?e:new V(B.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Dc]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof V?e:new V(B.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=_c(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(V.fromError(B.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Tl,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},Ol,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Al,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[Dc]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Dc]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Dc]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=ff(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=pf(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=ff(e);this._notificationHandlers.set(n,n=>{let r=pf(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&Uc(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new V(B.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new V(B.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new V(B.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new V(B.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Cl.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),cd(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new V(B.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(cd(a.status))throw new V(B.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=Cl.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),cd(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function hf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gf(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];hf(a)&&hf(i)?n[r]={...a,...i}:n[r]=i}return n}var _f=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),vf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=_f();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),W=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=_f(),n=vf();var r=_f();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return r.Name}});var i=vf();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=ie(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ie(this.rhs,e,n),this}get names(){return re(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ie(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(T(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>w(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(ae(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=ie(this.condition,e,t),this}get names(){let e=super.names;return re(e,this.condition),this.else&&w(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ie(this.iteration,e,t),this}get names(){return w(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return re(re(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ie(this.iterable,e,t),this}get names(){return w(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var ee=class extends p{render(e){return`return `+super.render(e)}};ee.kind=`return`;var te=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&w(e,this.catch.names),this.finally&&w(e,this.finally.names),e}},ne=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ne.kind=`catch`;var C=class extends m{render(e){return`finally`+super.render(e)}};C.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
33
|
+
`:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new ee;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(ee)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new te;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new ne(e),t(e)}return n&&(this._currNode=r.finally=new C,this.code(n)),this._endBlockNode(ne,C)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function w(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function re(e,n){return n instanceof t._CodeOrName?w(e,n.names):e}function ie(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function T(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function ae(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${de(e)}`}e.not=ae;let oe=ue(e.operators.AND);function se(...e){return e.reduce(oe)}e.and=se;let ce=ue(e.operators.OR);function le(...e){return e.reduce(ce)}e.or=le;function ue(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${de(n)} ${e} ${de(r)}`}function de(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),G=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=W(),n=_f();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0?!0:(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),yf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),bf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=W(),n=G(),r=yf();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),xf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=bf(),n=W(),r=yf(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),Sf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),Cf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),wf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Sf(),n=Cf(),r=bf(),i=W(),a=G();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
|
|
31
34
|
|| (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
|
|
32
35
|
|| (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
|
|
33
|
-
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Cf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=G(),n=K();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),wf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=G(),n=K(),r=_f(),i=K();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Tf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=G(),n=_f(),r=wf(),i=vf();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Ef=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=G(),n=K();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Df=n(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Of=n(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else (p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),kf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=K(),n=Df(),r=Of(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Af=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=yf(),n=Sf(),r=xf(),i=Sf(),a=Cf(),o=Tf(),s=Ef(),c=G(),l=_f(),u=kf(),d=K(),f=vf();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&re(e),E(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),ee(e),ie(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&re(e),te(e),ne(e);let a=r.const(`_errs`,l.default.errors);ee(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),T(e)}function ee(e,t){if(e.opts.jtd)return oe(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);oe(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function T(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function E(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function te(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function ne(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function re({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function ie(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&ae(e),t.return((0,c._)`${l.default.errors} === 0`))}function ae({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function oe(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>he(e,`$ref`,h.all.$ref.definition));return}p.jtd||ce(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),se(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):se(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function se(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&he(e,n.keyword,n.definition,t.type)})}function ce(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(le(e,t),e.opts.allowUnionTypes||ue(e,t),D(e,e.dataTypes))}function le(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{fe(e.dataTypes,t)||O(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),pe(e,t)}}function ue(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&O(e,`use allowUnionTypes to allow union type keyword`)}function D(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>de(t,e))&&O(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function de(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function fe(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function pe(e,t){let n=[];for(let r of e.dataTypes)fe(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function O(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var me=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,ve(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=me;function he(e,t,n,r){let i=new me(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let ge=/^\/(?:[^~]|~0|~1)*$/,_e=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ve(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ge.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=_e.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=ve})),jf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Mf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=kf();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),Nf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=G(),n=jf(),r=_f(),i=kf(),a=K(),o=Af();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Pf=n(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Ff=n(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function i(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let a=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function s(e,t,n){if(e.length){let r=i(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function c(e){let t=0,n={error:!1,address:``,zone:``},r=[],a=[],c=!1,l=!1,u=s;for(let i=0;i<e.length;i++){let s=e[i];if(!(s===`[`||s===`]`))if(s===`:`){if(c===!0&&(l=!0),!u(a,r,n))break;if(++t>7){n.error=!0;break}i>0&&e[i-1]===`:`&&(c=!0),r.push(`:`);continue}else if(s===`%`){if(!u(a,r,n))break;u=o}else{a.push(s);continue}}return a.length&&(u===o?n.zone=a.join(``):l?r.push(a.join(``)):r.push(i(a))),n.address=r.join(``),n}function l(e){if(u(e,`:`)<2)return{host:e,isIPV6:!1};let t=c(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function u(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function d(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}else{n.push(t);break}}else if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function f(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function p(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=l(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:a,recomposeAuthority:p,normalizeComponentEncoding:f,removeDotSegments:d,isIPv4:r,isUUID:n,normalizeIPv6:l,stringArrayToHexStripped:i}})),If=n(((e,t)=>{let{isUUID:n}=Ff(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=S(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=S(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},y={scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},b={scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0},x={http:h,https:g,ws:_,wss:v,urn:y,"urn:uuid":b};Object.setPrototypeOf(x,null);function S(e){return e&&(x[e]||x[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:x,isValidSchemeName:a,getSchemeHandler:S}})),Lf=n(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=Ff(),{SCHEMES:c,getSchemeHandler:l}=If();function u(e,t){return typeof e==`string`?e=m(g(e,t),t):typeof e==`object`&&(e=g(m(e,t),t)),e}function d(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=f(g(e,r),g(t,r),r,!0);return r.skipEscape=!0,m(i,r)}function f(e,t,n,i){let a={};return i||(e=g(m(e,n),n),t=g(m(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path=`/`+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:a.path=t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,t.query===void 0?a.query=e.query:a.query=t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function p(e,t,n){return typeof e==`string`?(e=unescape(e),e=m(a(g(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=m(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=m(a(g(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=m(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function m(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),o=[],s=l(a.scheme||n.scheme);s&&s.serialize&&s.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&o.push(n.scheme,`:`);let c=i(n);if(c!==void 0&&(a.reference!==`suffix`&&o.push(`//`),o.push(c),n.path&&n.path[0]!==`/`&&o.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!s||!s.absolutePath)&&(e=r(e)),c===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),o.push(e)}return n.query!==void 0&&o.push(`?`,n.query),n.fragment!==void 0&&o.push(`#`,n.fragment),o.join(``)}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let c=e.match(h);if(c){if(i.scheme=c[1],i.userinfo=c[3],i.host=c[4],i.port=parseInt(c[5],10),i.path=c[6]||``,i.query=c[7],i.fragment=c[8],isNaN(i.port)&&(i.port=c[5]),i.host)if(o(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0;i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?i.reference=`same-document`:i.scheme===void 0?i.reference=`relative`:i.fragment===void 0?i.reference=`absolute`:i.reference=`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=l(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&s(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let _={SCHEMES:c,normalize:u,resolve:d,resolveComponent:f,equal:p,serialize:m,parse:g};t.exports=_,t.exports.default=_,t.exports.fastUri=_})),Rf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Lf();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),zf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Af();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var n=G();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return n.CodeGen}});let r=jf(),i=Mf(),a=bf(),o=Nf(),s=G(),c=kf(),l=Sf(),u=K(),d=Pf(),f=Rf(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=E(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=ee.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(ne.call(this,n,t),!t)return(0,u.eachItem)(n,e=>re.call(this,e)),this;ae.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>re.call(this,e,r):e=>r.type.forEach(t=>re.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=se(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function ee(){let e={...this.opts};for(let t of m)delete e[t];return e}let T={log(){},warn(){},error(){}};function E(e){if(e===!1)return T;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let te=/^[a-z_$][a-z0-9_$:-]*$/i;function ne(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!te.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function re(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?ie.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function ie(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function ae(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=se(t)),e.validateSchema=this.compile(t,!0))}let oe={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function se(e){return{anyOf:[e,oe]}}})),Bf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),Vf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=Mf(),n=wf(),r=G(),i=_f(),a=Nf(),o=K(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0)if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}if(l.items!==!0)if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}e.callRef=l,e.default=s})),Hf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Bf(),n=Vf();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),Uf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),Wf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),Gf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),Kf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G(),n=K(),r=Gf();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),qf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=wf(),n=K(),r=G();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),Jf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),Yf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=wf(),n=G(),r=K();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),Xf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),Zf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Df();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),Qf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Sf(),n=G(),r=K(),i=Zf();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),$f=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G(),n=K(),r=Zf();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),ep=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G(),n=K(),r=Zf();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),tp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Uf(),n=Wf(),r=Kf(),i=qf(),a=Jf(),o=Yf(),s=Xf(),c=Qf(),l=$f(),u=ep();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),np=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=G(),n=K(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),rp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=G(),n=K(),r=wf(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),ip=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=rp();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),ap=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G(),n=K(),r=wf(),i=np();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),op=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G(),n=K();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),sp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=G(),n=K(),r=wf();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
|
|
36
|
+
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Tf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=W(),n=G();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),Ef=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=W(),n=G(),r=yf(),i=G();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Df=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=W(),n=yf(),r=Ef(),i=bf();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Of=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=W(),n=G();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),kf=n(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Af=n(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else (p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),jf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=G(),n=kf(),r=Af(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Mf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=xf(),n=wf(),r=Cf(),i=wf(),a=Tf(),o=Df(),s=Of(),c=W(),l=yf(),u=jf(),d=G(),f=bf();function p(e){if(S(e)&&(te(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&T(e),w(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),ne(e),ae(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(te(e),x(e))){ee(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function ee(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&T(e),re(e),ie(e);let a=r.const(`_errs`,l.default.errors);ne(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function te(e){(0,d.checkUnknownRules)(e),C(e)}function ne(e,t){if(e.opts.jtd)return se(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);se(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function C(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function w(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function re(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function ie(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function T({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function ae(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&oe(e),t.return((0,c._)`${l.default.errors} === 0`))}function oe({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function se(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>ve(e,`$ref`,h.all.$ref.definition));return}p.jtd||le(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),ce(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):ce(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function ce(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&ve(e,n.keyword,n.definition,t.type)})}function le(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(ue(e,t),e.opts.allowUnionTypes||de(e,t),fe(e,e.dataTypes))}function ue(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{me(e.dataTypes,t)||ge(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),he(e,t)}}function de(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ge(e,`use allowUnionTypes to allow union type keyword`)}function fe(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>pe(t,e))&&ge(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function pe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function me(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function he(e,t){let n=[];for(let r of e.dataTypes)me(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ge(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var _e=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,xe(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=_e;function ve(e,t,n,r){let i=new _e(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let ye=/^\/(?:[^~]|~0|~1)*$/,be=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function xe(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ye.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=be.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=xe})),Nf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Pf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=jf();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),Ff=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=W(),n=Nf(),r=yf(),i=jf(),a=G(),o=Mf();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),If=n(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Lf=n(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function i(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let a=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function s(e,t,n){if(e.length){let r=i(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function c(e){let t=0,n={error:!1,address:``,zone:``},r=[],a=[],c=!1,l=!1,u=s;for(let i=0;i<e.length;i++){let s=e[i];if(!(s===`[`||s===`]`))if(s===`:`){if(c===!0&&(l=!0),!u(a,r,n))break;if(++t>7){n.error=!0;break}i>0&&e[i-1]===`:`&&(c=!0),r.push(`:`);continue}else if(s===`%`){if(!u(a,r,n))break;u=o}else{a.push(s);continue}}return a.length&&(u===o?n.zone=a.join(``):l?r.push(a.join(``)):r.push(i(a))),n.address=r.join(``),n}function l(e){if(u(e,`:`)<2)return{host:e,isIPV6:!1};let t=c(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function u(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function d(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}else{n.push(t);break}}else if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function f(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function p(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=l(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:a,recomposeAuthority:p,normalizeComponentEncoding:f,removeDotSegments:d,isIPv4:r,isUUID:n,normalizeIPv6:l,stringArrayToHexStripped:i}})),Rf=n(((e,t)=>{let{isUUID:n}=Lf(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=S(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=S(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},y={scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},b={scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0},x={http:h,https:g,ws:_,wss:v,urn:y,"urn:uuid":b};Object.setPrototypeOf(x,null);function S(e){return e&&(x[e]||x[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:x,isValidSchemeName:a,getSchemeHandler:S}})),zf=n(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=Lf(),{SCHEMES:c,getSchemeHandler:l}=Rf();function u(e,t){return typeof e==`string`?e=m(g(e,t),t):typeof e==`object`&&(e=g(m(e,t),t)),e}function d(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=f(g(e,r),g(t,r),r,!0);return r.skipEscape=!0,m(i,r)}function f(e,t,n,i){let a={};return i||(e=g(m(e,n),n),t=g(m(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path=`/`+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:a.path=t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,t.query===void 0?a.query=e.query:a.query=t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function p(e,t,n){return typeof e==`string`?(e=unescape(e),e=m(a(g(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=m(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=m(a(g(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=m(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function m(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),o=[],s=l(a.scheme||n.scheme);s&&s.serialize&&s.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&o.push(n.scheme,`:`);let c=i(n);if(c!==void 0&&(a.reference!==`suffix`&&o.push(`//`),o.push(c),n.path&&n.path[0]!==`/`&&o.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!s||!s.absolutePath)&&(e=r(e)),c===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),o.push(e)}return n.query!==void 0&&o.push(`?`,n.query),n.fragment!==void 0&&o.push(`#`,n.fragment),o.join(``)}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let c=e.match(h);if(c){if(i.scheme=c[1],i.userinfo=c[3],i.host=c[4],i.port=parseInt(c[5],10),i.path=c[6]||``,i.query=c[7],i.fragment=c[8],isNaN(i.port)&&(i.port=c[5]),i.host)if(o(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0;i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?i.reference=`same-document`:i.scheme===void 0?i.reference=`relative`:i.fragment===void 0?i.reference=`absolute`:i.reference=`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=l(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&s(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let _={SCHEMES:c,normalize:u,resolve:d,resolveComponent:f,equal:p,serialize:m,parse:g};t.exports=_,t.exports.default=_,t.exports.fastUri=_})),Bf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=zf();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),Vf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Mf();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var n=W();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return n.CodeGen}});let r=Nf(),i=Pf(),a=Sf(),o=Ff(),s=W(),c=jf(),l=wf(),u=G(),d=If(),f=Bf(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=w(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=ne.call(this),e.formats&&ee.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&te.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(ie.call(this,n,t),!t)return(0,u.eachItem)(n,e=>T.call(this,e)),this;oe.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>T.call(this,e,r):e=>r.type.forEach(t=>T.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=ce(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function ee(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function te(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function ne(){let e={...this.opts};for(let t of m)delete e[t];return e}let C={log(){},warn(){},error(){}};function w(e){if(e===!1)return C;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let re=/^[a-z_$][a-z0-9_$:-]*$/i;function ie(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!re.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function T(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?ae.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function ae(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function oe(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=ce(t)),e.validateSchema=this.compile(t,!0))}let se={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function ce(e){return{anyOf:[e,se]}}})),Hf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),Uf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=Pf(),n=Ef(),r=W(),i=yf(),a=Ff(),o=G(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0)if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}if(l.items!==!0)if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}e.callRef=l,e.default=s})),Wf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Hf(),n=Uf();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),Gf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),Kf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),qf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),Jf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G(),r=qf();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),Yf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ef(),n=G(),r=W();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),Xf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),Zf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ef(),n=W(),r=G();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),Qf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),$f=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=kf();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),ep=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=wf(),n=W(),r=G(),i=$f();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),tp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G(),r=$f();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),np=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G(),r=$f();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),rp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gf(),n=Kf(),r=Jf(),i=Yf(),a=Xf(),o=Zf(),s=Qf(),c=ep(),l=tp(),u=np();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),ip=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=W(),n=G(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),ap=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=W(),n=G(),r=Ef(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),op=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=ap();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),sp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G(),r=Ef(),i=ip();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),cp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),lp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=W(),n=G(),r=Ef();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
|
|
34
37
|
missingProperty: ${i},
|
|
35
38
|
depsCount: ${n},
|
|
36
|
-
deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),cp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G(),n=K();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),lp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=wf(),n=G(),r=_f(),i=K();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),up=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Af(),n=wf(),r=K(),i=lp();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),dp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=wf(),n=G(),r=K(),i=K();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),fp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=K();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),pp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:wf().validateUnion,error:{message:`must match a schema in anyOf`}}})),mp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G(),n=K();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),hp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=K();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),gp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G(),n=K(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),_p=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=K();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),vp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=np(),n=ip(),r=rp(),i=ap(),a=op(),o=sp(),s=cp(),c=lp(),l=up(),u=dp(),d=fp(),f=pp(),p=mp(),m=hp(),h=gp(),g=_p();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),yp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),bp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[yp().default]})),xp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),Sp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Hf(),n=tp(),r=vp(),i=bp(),a=xp();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Cp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),wp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G(),n=Cp(),r=Nf(),i=Mf(),a=K();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),Tp=n(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),Ep=n(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=zf(),r=Sp(),i=wp(),a=Tp(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=c;var l=Af();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=G();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=jf();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Mf();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),Dp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:T,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let ee=/[^\\]\\Z/;function T(e){if(ee.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Op=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=Ep(),n=G(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),kp=n(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=Dp(),r=Op(),i=G(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=s})),Ap=t(Ep(),1),jp=t(kp(),1);function Mp(){let e=new Ap.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,jp.default)(e),e}var Np=class{constructor(e){this._ajv=e??Mp()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},Pp=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},Fu,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},qu,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function Fp(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Ip(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Lp=class extends ff{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Su.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Np,this.setRequestHandler(ol,e=>this._oninitialize(e)),this.setNotificationHandler(ll,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(wu,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Su.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Pp(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=mf(this._capabilities,e)}setRequestHandler(e,t){let n=_c(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(pc(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=hc(bu,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new H(V.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=hc(yl,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new H(V.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=hc(vu,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new H(V.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){Ip(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Fp(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:wc.includes(t)?t:Cc,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},Yc)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},Iu,t):this.request({method:`sampling/createMessage`,params:e},Fu,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},qu,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},qu,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new H(V.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof H?e:new H(V.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},rd,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const Rp=Symbol.for(`mcp.completable`);function zp(e){return!!e&&typeof e==`object`&&Rp in e}function Bp(e){return e[Rp]?.complete}var Vp;(function(e){e.Completable=`McpCompletable`})(Vp||={});const Hp=/^[A-Za-z0-9._-]{1,128}$/;function Up(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Hp.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Wp(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function Gp(e){let t=Up(e);return Wp(e,t.warnings),t.isValid}var Kp=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},qp=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Lp(e,t)}get experimental(){return this._experimental||={tasks:new Kp(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(em(gu)),this.server.assertCanSetRequestHandler(em(bu)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(gu,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=vc(t.inputSchema);return e?lf(e,{strictUnions:!0,pipeStrategy:`input`}):Jp})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=vc(t.outputSchema);e&&(n.outputSchema=lf(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(bu,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new H(V.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new H(V.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new H(V.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof H&&e.code===V.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await gc(vc(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=yc(`error`in r?r.error:`Unknown error`);throw new H(V.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new H(V.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await gc(vc(e.outputSchema),t.structuredContent);if(!r.success){let e=yc(`error`in r?r.error:`Unknown error`);throw new H(V.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new H(V.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(em(Zu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Zu,async e=>{switch(e.params.ref.type){case`ref/prompt`:return Qu(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return $u(e),this.handleResourceCompletion(e,e.params.ref);default:throw new H(V.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new H(V.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return nm;let r=_c(n.argsSchema)?.[e.params.argument.name];if(!zp(r))return nm;let i=Bp(r);return i?tm(await i(e.params.argument.value,e.params.context)):nm}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return nm;throw new H(V.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?tm(await r(e.params.argument.value,e.params.context)):nm}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(em(Ll)),this.server.assertCanSetRequestHandler(em(zl)),this.server.assertCanSetRequestHandler(em(Ul)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ll,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(zl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Ul,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new H(V.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new H(V.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(em(eu)),this.server.assertCanSetRequestHandler(em(ru)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(eu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?$p(t.argsSchema):void 0}))})),this.server.setRequestHandler(ru,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new H(V.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await gc(vc(n.argsSchema),e.params.arguments);if(!r.success){let t=yc(`error`in r?r.error:`Unknown error`);throw new H(V.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:mc(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=mc(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>zp(e instanceof m?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Gp(e);let l={title:t,description:n,inputSchema:Qp(r),outputSchema:Qp(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&Gp(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=mc(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=mc(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(Zp(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!Zp(t[0])&&(i=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const Jp={type:`object`,properties:{}};function Yp(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function Xp(e){return`_def`in e||`_zod`in e||Yp(e)}function Zp(e){return typeof e!=`object`||!e||Xp(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Yp)}function Qp(e){if(e){if(Zp(e))return mc(e);if(!Xp(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function $p(e){let t=_c(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:bc(t),required:!xc(t)})):[]}function em(e){let t=_c(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Sc(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function tm(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const nm={completion:{values:[],hasMore:!1}};var rm=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
37
|
-
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),
|
|
38
|
-
`}var
|
|
39
|
-
`).length};let n=e===`command`?240:120;return t.length<=n?t:{type:`string`,length:t.length,preview:`${t.slice(0,n)}...`}}function
|
|
39
|
+
deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),up=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),dp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ef(),n=W(),r=yf(),i=G();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),fp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Mf(),n=Ef(),r=G(),i=dp();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),pp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ef(),n=W(),r=G(),i=G();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),mp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),hp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Ef().validateUnion,error:{message:`must match a schema in anyOf`}}})),gp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),_p=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),vp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),yp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),bp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=ip(),n=op(),r=ap(),i=sp(),a=cp(),o=lp(),s=up(),c=dp(),l=fp(),u=pp(),d=mp(),f=hp(),p=gp(),m=_p(),h=vp(),g=yp();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),xp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),Sp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[xp().default]})),Cp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),wp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Wf(),n=rp(),r=bp(),i=Sp(),a=Cp();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Tp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),Ep=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=Tp(),r=Ff(),i=Pf(),a=G();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),Dp=n(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),Op=n(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Vf(),r=wp(),i=Ep(),a=Dp(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=c;var l=Mf();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=W();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Nf();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Pf();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),kp=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:C,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:ee},float:{type:`number`,validate:te},double:{type:`number`,validate:te},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function ee(e){return Number.isInteger(e)}function te(){return!0}let ne=/[^\\]\\Z/;function C(e){if(ne.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Ap=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=Op(),n=W(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),jp=n(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=kp(),r=Ap(),i=W(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=s})),Mp=t(Op(),1),Np=t(jp(),1);function Pp(){let e=new Mp.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Np.default)(e),e}var Fp=class{constructor(e){this._ajv=e??Pp()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},Ip=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},Lu,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},Yu,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function Lp(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Rp(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var zp=class extends mf{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(wu.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Fp,this.setRequestHandler(cl,e=>this._oninitialize(e)),this.setNotificationHandler(dl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Eu,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=wu.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Ip(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=gf(this._capabilities,e)}setRequestHandler(e,t){let n=yc(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(hc(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=_c(Su,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new V(B.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=_c(xl,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new V(B.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=_c(bu,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new V(B.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){Rp(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Lp(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Ec.includes(t)?t:Tc,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},Zc)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},Ru,t):this.request({method:`sampling/createMessage`,params:e},Lu,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},Yu,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},Yu,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new V(B.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof V?e:new V(B.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},ad,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const Bp=Symbol.for(`mcp.completable`);function Vp(e){return!!e&&typeof e==`object`&&Bp in e}function Hp(e){return e[Bp]?.complete}var Up;(function(e){e.Completable=`McpCompletable`})(Up||={});const Wp=/^[A-Za-z0-9._-]{1,128}$/;function Gp(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Wp.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Kp(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function qp(e){let t=Gp(e);return Kp(e,t.warnings),t.isValid}var Jp=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},Yp=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new zp(e,t)}get experimental(){return this._experimental||={tasks:new Jp(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(nm(vu)),this.server.assertCanSetRequestHandler(nm(Su)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(vu,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=bc(t.inputSchema);return e?df(e,{strictUnions:!0,pipeStrategy:`input`}):Xp})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=bc(t.outputSchema);e&&(n.outputSchema=df(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Su,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new V(B.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new V(B.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new V(B.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new V(B.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof V&&e.code===B.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await vc(bc(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=xc(`error`in r?r.error:`Unknown error`);throw new V(B.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new V(B.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await vc(bc(e.outputSchema),t.structuredContent);if(!r.success){let e=xc(`error`in r?r.error:`Unknown error`);throw new V(B.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new V(B.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(nm($u)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler($u,async e=>{switch(e.params.ref.type){case`ref/prompt`:return ed(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return td(e),this.handleResourceCompletion(e,e.params.ref);default:throw new V(B.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new V(B.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new V(B.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return im;let r=yc(n.argsSchema)?.[e.params.argument.name];if(!Vp(r))return im;let i=Hp(r);return i?rm(await i(e.params.argument.value,e.params.context)):im}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return im;throw new V(B.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?rm(await r(e.params.argument.value,e.params.context)):im}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(nm(zl)),this.server.assertCanSetRequestHandler(nm(Vl)),this.server.assertCanSetRequestHandler(nm(Gl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(zl,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(Vl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Gl,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new V(B.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new V(B.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(nm(nu)),this.server.assertCanSetRequestHandler(nm(au)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(nu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?tm(t.argsSchema):void 0}))})),this.server.setRequestHandler(au,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new V(B.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new V(B.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await vc(bc(n.argsSchema),e.params.arguments);if(!r.success){let t=xc(`error`in r?r.error:`Unknown error`);throw new V(B.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:gc(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=gc(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>Vp(e instanceof _?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){qp(e);let l={title:t,description:n,inputSchema:em(r),outputSchema:em(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&qp(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=gc(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=gc(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if($p(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!$p(t[0])&&(i=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const Xp={type:`object`,properties:{}};function Zp(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function Qp(e){return`_def`in e||`_zod`in e||Zp(e)}function $p(e){return typeof e!=`object`||!e||Qp(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Zp)}function em(e){if(e){if($p(e))return gc(e);if(!Qp(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function tm(e){let t=yc(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:Sc(t),required:!Cc(t)})):[]}function nm(e){let t=yc(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=wc(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function rm(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const im={completion:{values:[],hasMore:!1}};var am=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
40
|
+
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),om(t)}clear(){this._buffer=void 0}};function om(e){return Xc.parse(JSON.parse(e))}function sm(e){return JSON.stringify(e)+`
|
|
41
|
+
`}var cm=class{constructor(e=zn.stdin,t=zn.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new am,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=sm(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};const lm=new Un;var um=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??Yn().slice(0,12),this.corrId=Yn().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,n={}){let r=t?{error:t instanceof Error?t.message:String(t),...n}:n;this.emit(`error`,e,r)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,n){let r={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...n},i=`${JSON.stringify(r)}\n`;process.stderr.write(i);let a=process.env.OK_LOG_FILE;if(a)try{On(a,i)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function dm(e=`mcp`){return new um(e)}function fm(e,t){return lm.run(e,t)}function pm(){return lm.getStore()}const mm=new Set([`find`,`markdown`,`replace`]),hm=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],gm=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function _m(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vm(e){return _m(e)&&`requestId`in e}function ym(e,t){if(mm.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
|
|
42
|
+
`).length};let n=e===`command`?240:120;return t.length<=n?t:{type:`string`,length:t.length,preview:`${t.slice(0,n)}...`}}function bm(e,t){if(t===null)return null;if(typeof t==`string`)return ym(e,t);if(typeof t==`number`||typeof t==`boolean`)return t;if(Array.isArray(t))return{type:`array`,length:t.length};if(_m(t)){let e=Object.keys(t).sort();return{type:`object`,keyCount:e.length,keys:e.slice(0,12)}}if(t!==void 0)return{type:typeof t}}function xm(e,t){return _m(t)?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,bm(e,t)])):bm(e,t)}function Sm(e){let t={structuredKeys:Object.keys(e).sort()};for(let n of gm)n in e&&(t[n]=e[n]);for(let n of hm){let r=e[n];Array.isArray(r)&&(t[`${n}Count`]=r.length)}return`previewUrl`in e&&(t.previewUrl=e.previewUrl??null),`previewUrlSource`in e&&(t.previewUrlSource=e.previewUrlSource),typeof e.stdout==`string`&&(t.stdoutChars=e.stdout.length),Array.isArray(e.warnings)&&(t.warningsCount=e.warnings.length),_m(e.warning)&&(t.warning=!0,`previewUrl`in e.warning&&(t.warningPreviewUrl=e.warning.previewUrl??null)),_m(e.ui)&&(t.uiBaseUrl=typeof e.ui.baseUrl==`string`||e.ui.baseUrl===null?e.ui.baseUrl:void 0,t.uiPort=typeof e.ui.port==`number`||e.ui.port===null?e.ui.port:void 0),t}function Cm(e){if(!_m(e))return{resultType:typeof e};let t={isError:e.isError===!0};return Array.isArray(e.content)&&(t.contentItems=e.content.length,t.contentTextChars=e.content.reduce((e,t)=>_m(t)&&typeof t.text==`string`?e+t.text.length:e,0)),_m(e.structuredContent)&&Object.assign(t,Sm(e.structuredContent)),t}function wm(e){return{connectionId:e.connectionId.slice(0,8),displayName:e.displayName,...e.clientInfo?.name?{clientName:e.clientInfo.name}:{},...e.label?{label:e.label}:{}}}function Tm(e){let t=e.at(-1);return vm(t)?{toolArgs:e.length>1?e[0]:void 0,extra:t}:{toolArgs:e[0],extra:void 0}}function Em(e,t,n){let r=n.logger;return r?async(...i)=>{let a=r.child(),o=Date.now(),{toolArgs:s,extra:c}=Tm(i);a.info(`tool start`,{tool:e,...c?.requestId===void 0?{}:{requestId:c.requestId},...c?.sessionId?{transportSessionId:c.sessionId}:{},...n.identityRef?.current?{agent:wm(n.identityRef.current)}:{},...s===void 0?{}:{args:xm(e,s)}});try{let n=await fm(a,async()=>await t(...i));return a.info(`tool finish`,{tool:e,...c?.requestId===void 0?{}:{requestId:c.requestId},durationMs:Date.now()-o,result:Cm(n)}),n}catch(t){throw a.error(`tool error`,t,{tool:e,...c?.requestId===void 0?{}:{requestId:c.requestId},durationMs:Date.now()-o}),t}}:t}function Dm(e,t){if(!t.logger)return e;let n=e.tool.bind(e),r=Object.create(e);return r.tool=((...e)=>{let r=String(e[0]),i=e.at(-1);if(typeof i!=`function`)return n(...e);let a=[...e];return a[a.length-1]=Em(r,i,t),n(...a)}),r}const Om="Absolute host path to resolve the request against. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.",km=u().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`);function K(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}function q(e,t,n){return{content:[{type:`text`,text:e}],structuredContent:t,...n?{isError:!0}:{}}}const Am="Error: Hocuspocus server is not running. Start it with `open-knowledge start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.",jm={ingest:`raw-sources layer (preserve external material, no analysis)`,research:`wiki layer, provisional (synthesize findings that can still change)`,consolidate:`wiki layer, canonical (promote stabilized research to source-of-truth)`},Mm={ingest:"user shares a URL or file they want preserved, or `research` needs raw sources",research:"`ingest` has captured the relevant sources (or the user points at one)",consolidate:"`research` has produced a provisional article AND a decision has actually been made"},Nm={ingest:"often `research` on the same topic — or just stop; raw preservation is frequently enough on its own",research:"usually stop (research lives as provisional indefinitely) or `consolidate` once a decision lands",consolidate:"update 2–3 neighbor docs to link the new canonical article; research articles it supersedes gain a `superseded_by` pointer"};function Pm(e){return`## Where this fits
|
|
40
43
|
|
|
41
44
|
Open Knowledge accretes a persistent wiki through three workflow tools, mapped to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f):
|
|
42
45
|
|
|
@@ -46,18 +49,18 @@ Open Knowledge accretes a persistent wiki through three workflow tools, mapped t
|
|
|
46
49
|
|
|
47
50
|
(Project-level folder structure + \`config.yml\` scaffolding is handled by the \`ok seed\` CLI, not by an MCP tool.)
|
|
48
51
|
|
|
49
|
-
**This tool operates in the ${
|
|
52
|
+
**This tool operates in the ${jm[e]}.**
|
|
50
53
|
|
|
51
|
-
- **Before this:** ${
|
|
52
|
-
- **After this:** ${
|
|
54
|
+
- **Before this:** ${Mm[e]}
|
|
55
|
+
- **After this:** ${Nm[e]}
|
|
53
56
|
|
|
54
57
|
Karpathy's insight: "The tedious part of maintaining a knowledge base is not the reading or the thinking — it's the bookkeeping." Humans abandon wikis because maintenance costs exceed perceived value. These tools exist so an agent can do the bookkeeping (fetching, summarizing, cross-linking, superseding) without fatigue. Follow the steps below faithfully — skipping the cross-linking, supersedes chains, or raw-source preservation is what turns a useful wiki back into an abandoned one.
|
|
55
58
|
|
|
56
|
-
`}async function
|
|
59
|
+
`}async function Fm(e,t){return typeof e==`function`?await e(t):e}async function Im(e,t){return typeof e==`function`?await e(t):e}async function Lm(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}try{let e=await Im(t,r);return{ok:!0,cwd:r,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function Rm(e,t,n,r){let i=await Lm(e,t,r);if(!i.ok)return i;let{cwd:a,config:o}=i;try{return{ok:!0,cwd:a,config:o,url:await Fm(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function zm(e){let t=e.toLowerCase();return t.endsWith(`.md`)?{ok:!0,docName:e.slice(0,-3)}:t.endsWith(`.mdx`)?{ok:!0,docName:e.slice(0,-4)}:t.endsWith(`.markdown`)?{ok:!1,error:`Error: docName "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`}:{ok:!0,docName:e}}async function Bm(e,t){let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await n.json()}catch{return{ok:!1,error:`Server returned HTTP ${n.status} with non-JSON body`}}}async function Vm(e,t,n){let r;try{r=await fetch(`${e}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:n?JSON.stringify(n):void 0,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await r.json()}catch{return{ok:!1,error:`Server returned HTTP ${r.status} with non-JSON body`}}}function Hm(e,t){return`${Pm(`consolidate`)}Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
|
|
57
60
|
|
|
58
61
|
Topic: ${e}
|
|
59
62
|
|
|
60
|
-
The content directory for this project is **\`${t}\`** (from \`${
|
|
63
|
+
The content directory for this project is **\`${t}\`** (from \`${T}/config.yml\`).
|
|
61
64
|
|
|
62
65
|
## STOP gate: has a decision actually been made?
|
|
63
66
|
|
|
@@ -200,48 +203,48 @@ superseded_by: <path-to-new-canonical-article>.md
|
|
|
200
203
|
- **Don't delete research articles** — they are the trail; keep them with a \`superseded_by\` marker
|
|
201
204
|
- **Don't rewrite research prose verbatim** — canonical articles have a different voice (direct, decided) than research (exploratory, provisional)
|
|
202
205
|
- **Don't skip the supersedes / superseded_by links** — the audit trail matters for future readers
|
|
203
|
-
`}const
|
|
204
|
-
`);function
|
|
205
|
-
`);function
|
|
206
|
-
`);if(!u&&!f&&!p&&!m)return
|
|
207
|
-
`)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!
|
|
208
|
-
`)){if(!n)continue;let e=n.indexOf(`:`);if(e<0)continue;let r=
|
|
209
|
-
`)){let e=rh(n);e&&nh(e)&&t.push(e)}return t}function uh(e){return ah(ih(e)).filter(nh)}function dh(e){return ah(ih(e)).length>0}function fh(e){let t=[],n=e.matchAll(th);for(let e of n)t.push(rh(e[0]));return t}function ph(e,t){let n=null;for(let e=t.length-1;e>=0;e--){let r=t[e];if(eh.has(r.command)){n=r;break}if((r.command===`head`||r.command===`tail`)&&dh(r)){n=r;break}}let r;if(!n)r=fh(e);else{switch(n.command){case`cat`:r=oh(n);break;case`ls`:r=sh(e,n);break;case`grep`:r=ch(e);break;case`find`:r=lh(e);break;case`head`:case`tail`:r=uh(n);break;default:r=fh(e)}r.length===0&&(r=fh(e))}let i=new Set,a=[];for(let e of r){let t=rh(e);!t||i.has(t)||(i.add(t),a.push(t))}return a}var mh=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-B9QCpaZR.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-CAQOzqfy.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-uTOF6Zpa.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-B0la1Q-P.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-CRMB4_AE.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-C13HY1h7.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-ewCHfbB3.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-fjvVauiI.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-BUZu7KNi.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-1iTO8NY5.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-DiYK6FgR.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-BC2VVHCa.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-DNkGMjtD.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-DRVZBAvY.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-DyNkF3aY.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-Bk22kVUG.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-DkOBrQlr.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-Dqepjl-k.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-3AIAIJVR-C9A_aSMK.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-3AIAIJVR-C9A_aSMK.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-3AIAIJVR-C9A_aSMK.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-FOQSCCX3-Cssz8GNh.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-VFTTATXJ-DO49xc40.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-POPGKRAI-DigGXYmO.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-Dmp_2ZoH.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-Cn_JDmUJ.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-DRcwK9Gt.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-BIRZEN2Y.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-C3M5_YM6.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-DrrobhxR.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-q2MQLs41.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-IRiMqQcZ.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-CAfX9d8n.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-BWwDphsm.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-BOmSL08U.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-g6FhPS64.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-Cu9ifXuc.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-fFssyAvW.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-B6C3-ghI.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-Ftqr8Jad.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-TPUOAIUQ-DaW1-9Vm.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-DlZHEU5f.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-2cTXnmQf.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-DZnTMKSh.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-B5uda2-L.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR--4eujSrM.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR--4eujSrM.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-TirEebNy.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-TirEebNy.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-DUTsR2Sf.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-dHdg4qaj.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-BaLssNp9.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-BaLssNp9.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-B5oRhK00.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-BA1gxmDh.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-BA1gxmDh.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-ODXZBPLY-Uj_VahOC.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-B4GnvJtR.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-Yo3lE_58.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-DRxppxbV.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-CS7jDpXp.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-Cpzi9cz-.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-BtzQ0nVf.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-D9r6kc_Z.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-5T3UU5KE-D5OdgUlD.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-DAG8dmoX.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-4uBt63v6.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-_uaXSgBK.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-ZIGAJ4YS-zZfB3nws.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-Ux5cbjMV.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-D5WzpTIY.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-DxZJ58G5.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-DczI7HKk.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-zmNkhqtV.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-Bn1LP0m_.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-PasvdXXR.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-CL228lzk.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-CL228lzk.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-CL228lzk.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(mh.push({name:`tar`,load:async()=>(await import(`./tar-ANUBEFJY-1lwT6ndQ.mjs`)).tarCommand}),mh.push({name:`yq`,load:async()=>(await import(`./yq-MJMAR36V-pRBq87Ya.mjs`)).yqCommand}),mh.push({name:`xan`,load:async()=>(await import(`./xan-BXDXYEIB-_Vtao535.mjs`)).xanCommand}),mh.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-56UMWEY3-D1Xq8d4g.mjs`)).sqlite3Command}));var hh=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(hh.push({name:`python3`,load:async()=>(await import(`./python3-AUFTPCU6-MeZyx8_A.mjs`)).python3Command}),hh.push({name:`python`,load:async()=>(await import(`./python3-AUFTPCU6-MeZyx8_A.mjs`)).pythonCommand}));var gh=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(gh.push({name:`js-exec`,load:async()=>(await import(`./js-exec-M6UR76J5-DSk5_wnx.mjs`)).jsExecCommand}),gh.push({name:`node`,load:async()=>(await import(`./js-exec-M6UR76J5-DSk5_wnx.mjs`)).nodeStubCommand}));var _h=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-Kn_Na_aU.mjs`)).curlCommand}],vh=new Map;function yh(e){return{name:e.name,async execute(t,n){let r=vh.get(e.name);if(r||(r=await an.runTrustedAsync(()=>e.load()),vh.set(e.name,r)),n.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:r}=await import(`./flag-coverage-QT4N2Z44-B8zntJyb.mjs`);r(n.coverage,e.name,t)}return r.execute(t,n)}}}function bh(e){return(e?mh.filter(t=>e.includes(t.name)):mh).map(yh)}function xh(){return _h.map(yh)}function Sh(){return hh.map(yh)}function Ch(){return gh.map(yh)}function wh(e){return`load`in e&&typeof e.load==`function`}function Th(e){let t=null;return{name:e.name,trusted:!0,async execute(n,r){return t||=await e.load(),t.execute(n,r)}}}var Eh=new TextEncoder;function Dh(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&`content`in e}var Oh=class{data=new Map;constructor(e){if(this.data.set(`/`,{type:`directory`,mode:493,mtime:new Date}),e)for(let[t,n]of Object.entries(e))typeof n==`function`?this.writeFileLazy(t,n):Dh(n)?this.writeFileSync(t,n.content,void 0,{mode:n.mode,mtime:n.mtime}):this.writeFileSync(t,n)}ensureParentDirs(e){let t=Wt(e);t!==`/`&&(this.data.has(t)||(this.ensureParentDirs(t),this.data.set(t,{type:`directory`,mode:493,mtime:new Date})))}writeFileSync(e,t,n,r){A(e,`write`);let i=Kt(e);this.ensureParentDirs(i);let a=en(t,$t(n));this.data.set(i,{type:`file`,content:a,mode:r?.mode??420,mtime:r?.mtime??new Date})}writeFileLazy(e,t,n){A(e,`write`);let r=Kt(e);this.ensureParentDirs(r),this.data.set(r,{type:`file`,lazy:t,mode:n?.mode??420,mtime:n?.mtime??new Date})}async materializeLazy(e,t){let n=await t.lazy(),r={type:`file`,content:typeof n==`string`?Eh.encode(n):n,mode:t.mode,mtime:t.mtime};return this.data.set(e,r),r}async readFile(e,t){return tn(await this.readFileBuffer(e),$t(t))}async readFileBuffer(e){A(e,`open`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(n.type!==`file`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(`lazy`in n){let e=await this.materializeLazy(t,n);return e.content instanceof Uint8Array?e.content:Eh.encode(e.content)}return n.content instanceof Uint8Array?n.content:Eh.encode(n.content)}async writeFile(e,t,n){this.writeFileSync(e,t,n)}async appendFile(e,t,n){A(e,`append`);let r=Kt(e),i=this.data.get(r);if(i&&i.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let a=en(t,$t(n));if(i?.type===`file`){let e=i;`lazy`in e&&(e=await this.materializeLazy(r,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:Eh.encode(`content`in e?e.content:``),n=new Uint8Array(t.length+a.length);n.set(t),n.set(a,t.length),this.data.set(r,{type:`file`,content:n,mode:e.mode,mtime:new Date})}else this.writeFileSync(e,t,n)}async exists(e){if(e.includes(`\0`))return!1;try{let t=this.resolvePathWithSymlinks(e);return this.data.has(t)}catch{return!1}}async stat(e){A(e,`stat`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, stat '${e}'`);n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:Eh.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}async lstat(e){A(e,`lstat`);let t=this.resolveIntermediateSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);if(n.type===`symlink`)return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:Eh.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}resolveIntermediateSymlinks(e){let t=Kt(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`);if(n.length<=1)return t;let r=``,i=new Set;for(let t=0;t<n.length-1;t++){let a=n[t];r=`${r}/${a}`;let o=this.data.get(r),s=0;for(;o&&o.type===`symlink`&&s<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);i.add(r),r=Qt(r,o.target),o=this.data.get(r),s++}if(s>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${r}/${n[n.length-1]}`}resolvePathWithSymlinks(e){let t=Kt(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`),r=``,i=new Set;for(let t of n){r=`${r}/${t}`;let n=this.data.get(r),a=0;for(;n&&n.type===`symlink`&&a<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);i.add(r),r=Qt(r,n.target),n=this.data.get(r),a++}if(a>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return r}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){A(e,`mkdir`);let n=Kt(e);if(this.data.has(n)){if(this.data.get(n)?.type===`file`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(!t?.recursive)throw Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let r=Wt(n);if(r!==`/`&&!this.data.has(r))if(t?.recursive)this.mkdirSync(r,{recursive:!0});else throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(n,{type:`directory`,mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){A(e,`scandir`);let t=Kt(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Set;for(;n&&n.type===`symlink`;){if(r.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);r.add(t),t=Qt(t,n.target),n=this.data.get(t)}if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.type!==`directory`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);let i=t===`/`?`/`:`${t}/`,a=new Map;for(let[e,n]of this.data.entries())if(e!==t&&e.startsWith(i)){let t=e.slice(i.length),r=t.split(`/`)[0];r&&!t.includes(`/`,r.length)&&!a.has(r)&&a.set(r,{name:r,isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`})}return Array.from(a.values()).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}async rm(e,t){A(e,`rm`);let n=Kt(e),r=this.data.get(n);if(!r){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(r.type===`directory`){let r=await this.readdir(n);if(r.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of r){let r=qt(n,e);await this.rm(r,t)}}}this.data.delete(n)}async cp(e,t,n){A(e,`cp`),A(t,`cp`);let r=Kt(e),i=Kt(t),a=this.data.get(r);if(!a)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(a.type===`file`)if(this.ensureParentDirs(i),`content`in a){let e=a.content instanceof Uint8Array?new Uint8Array(a.content):a.content;this.data.set(i,{...a,content:e})}else this.data.set(i,{...a});else if(a.type===`symlink`)this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type===`directory`){if(!n?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(i,{recursive:!0});let t=await this.readdir(r);for(let e of t){let t=qt(r,e),a=qt(i,e);await this.cp(t,a,n)}}}async mv(e,t){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,t){return Gt(e,t)}async chmod(e,t){A(e,`chmod`);let n=Kt(e),r=this.data.get(n);if(!r)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);r.mode=t}async symlink(e,t){A(t,`symlink`);let n=Kt(t);if(this.data.has(n))throw Error(`EEXIST: file already exists, symlink '${t}'`);this.ensureParentDirs(n),this.data.set(n,{type:`symlink`,target:e,mode:511,mtime:new Date})}async link(e,t){A(e,`link`),A(t,`link`);let n=Kt(e),r=Kt(t),i=this.data.get(n);if(!i)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(i.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(r))throw Error(`EEXIST: file already exists, link '${t}'`);let a=i;`lazy`in a&&(a=await this.materializeLazy(n,a)),this.ensureParentDirs(r),this.data.set(r,{type:`file`,content:a.content,mode:a.mode,mtime:a.mtime})}async readlink(e){A(e,`readlink`);let t=Kt(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.type!==`symlink`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);return n.target}async realpath(e){A(e,`realpath`);let t=this.resolvePathWithSymlinks(e);if(!this.data.has(t))throw Error(`ENOENT: no such file or directory, realpath '${e}'`);return t}async utimes(e,t,n){A(e,`utimes`);let r=Kt(e),i=this.resolvePathWithSymlinks(r),a=this.data.get(i);if(!a)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);a.mtime=n}};function kh(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function Ah(e,t){e.mkdirSync(`/bin`,{recursive:!0}),e.mkdirSync(`/usr/bin`,{recursive:!0}),t&&(e.mkdirSync(`/home/user`,{recursive:!0}),e.mkdirSync(`/tmp`,{recursive:!0}))}function jh(e){e.mkdirSync(`/dev`,{recursive:!0}),e.writeFileSync(`/dev/null`,``),e.writeFileSync(`/dev/zero`,new Uint8Array),e.writeFileSync(`/dev/stdin`,``),e.writeFileSync(`/dev/stdout`,``),e.writeFileSync(`/dev/stderr`,``)}function Mh(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${vt}
|
|
206
|
+
`}const Um=[`Promote research into a canonical article inside the project content directory. Canonical, not provisional — the output is the source of truth for future agents.`,``,`**Use when:**`,`- A team has made a decision after research and wants the outcome committed as canonical knowledge`,`- Compacting several provisional research notes into one authoritative article`,`- A developer asks to "consolidate" or "finalize" knowledge on a topic`,``,`**Triggers on:**`,`- "consolidate", "finalize", "promote to canonical", "make this official"`,`- User says the team has decided and wants the outcome written as canonical`,`- Research has stabilized and a destination article is needed`].join(`
|
|
207
|
+
`);function Wm(e,t){e.tool(`consolidate`,Um,{topic:u().describe(`The topic to consolidate into a canonical article`),cwd:u().optional().describe(Om)},async e=>{let n=await Lm(t.resolveCwd,t.config,e.cwd);return n.ok?q(Hm(e.topic,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}function Gm(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function Km(e){return e.endsWith(`/`)?e.slice(0,-1):e}function qm(e){try{return new URL(e),!0}catch{return!1}}async function Jm(e,t,n){let r=n??await t.resolveCwd(),i=await Im(t.config,r),a=ve(i,r);return Qm(e,{config:i,lockDir:_e(a),contentDir:a})}function Ym(e){try{let t=Ee(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`,port:t.port}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while building ui block: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null,port:null}}async function Xm(e,t){let n=t??await e.resolveCwd(),r=await Im(e.config,n),i=ve(r,n),a={config:r,lockDir:_e(i),contentDir:i};return{resolve:e=>Qm(e,a),ui:Ym(a)}}function Zm(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function Qm(e,t){let n=`/#/${Gm(e)}`;if(process.env.OK_ELECTRON_PROTOCOL_HOST===`1`&&t.contentDir)try{let n=Fn(t.contentDir);return{url:`openknowledge://open?project=${encodeURIComponent(n)}&doc=${encodeURIComponent(e)}`,source:`electron-protocol`}}catch(e){process.stderr.write(`[preview-url] realpathSync failed for ${t.contentDir}, falling through to http sources: ${e instanceof Error?e.message:String(e)}\n`)}let r=process.env.OPEN_KNOWLEDGE_PREVIEW_BASE_URL;if(r&&qm(r))return{url:`${Km(r)}${n}`,source:`env`};try{let e=Ee(t.lockDir);if(e&&e.port>0)return{url:`http://localhost:${e.port}${n}`,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}, falling through to config: ${e instanceof Error?e.message:String(e)}\n`)}let i=t.config.preview?.baseUrl;return i&&qm(i)?{url:`${Km(i)}${n}`,source:`config`}:null}const $m=[`[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer.`,`The patch is applied through Hocuspocus and propagated to all connected editors in real-time.`,"Use `offset` when you need to patch an exact occurrence; omit it to preserve first-match behavior.",``,"**When rewriting prose, add `[[wiki-links]]` aggressively.** If the replacement mentions other documents or entities that should have their own page, link them as `[[Page Name]]`. Over-linking is the goal; underlinked documents lose their value in backlink-driven navigation.",``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `find` — Text to find (exact match)","- `replace` — Replacement text","- `offset` (optional) — Exact occurrence to patch, as a JavaScript string offset in the current markdown. If the document changed and the text no longer matches there, the server returns a stale-target error; re-run `suggest_links` to get fresh offsets.",'- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Changed 1 line"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
|
|
208
|
+
`);function eh(e,t){e.tool(`edit_document`,$m,{docName:u().describe(`Document name to edit`),find:u().describe(`Text to find (exact match)`),replace:u().describe(`Replacement text`),offset:m().int().min(0).optional().describe(`Exact occurrence to patch, as a JavaScript string offset in the current markdown`),summary:km,cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n;if(!a)return K(Am,!0);let o=zm(e.docName);if(!o.ok)return K(o.error,!0);let s=t.identityRef?.current,c=await Vm(a,`/api/agent-patch`,{docName:o.docName,find:e.find,replace:e.replace,offset:e.offset,...e.summary===void 0?{}:{summary:e.summary},...s?{agentId:s.connectionId,agentName:s.displayName,clientName:s.clientInfo?.name,colorSeed:s.colorSeed}:{}});if(!c.ok)return K(`Error: ${c.error}`,!0);let l=_e(ve(i,r)),u=Qm(o.docName,{config:i,lockDir:l}),d=typeof c.subscriberCount==`number`?c.subscriberCount:void 0,f=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,p=d===0,m=c.summary&&typeof c.summary==`object`?c.summary:void 0,h=typeof m?.hint==`string`?m.hint:void 0,g=[`Edit applied successfully.`];u&&g.push(`Preview: ${u.url}`),f&&g.push(u?`Open ${u.url} in your preview browser.`:`No preview attached. Start the UI.`),h&&g.push(h);let _=g.join(`
|
|
209
|
+
`);if(!u&&!f&&!p&&!m)return K(_);let v={};return u&&(v.previewUrl=u.url,v.previewUrlSource=u.source),f&&(v.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:u?.url??null}),m&&(v.summary=m),q(_,v)})}const th=new Set([`cat`,`ls`,`grep`,`find`]),nh=/\b[\w./-]+\.(md|mdx)\b/g;function rh(e){return/\.(md|mdx)$/.test(e)}function ih(e){let t=e.trim();return t?(t=t.replace(/\/+/g,`/`),t.startsWith(`./`)&&(t=t.slice(2)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t):``}function ah(e){return e.args.slice(1)}function oh(e){return e.filter(e=>!e.startsWith(`-`))}function sh(e){return oh(ah(e)).filter(rh)}function ch(e,t){let n=oh(ah(t)),r=n.length>0?n[n.length-1]:``,i=r&&r!==`.`?ih(r):``,a=[];i&&a.push(i);for(let t of e.split(`
|
|
210
|
+
`)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!rh(e))continue;let n=i?`${i}/${e}`:e;a.push(n)}return a}function lh(e){let t=[];for(let n of e.split(`
|
|
211
|
+
`)){if(!n)continue;let e=n.indexOf(`:`);if(e<0)continue;let r=ih(n.slice(0,e));rh(r)&&t.push(r)}return t}function uh(e){let t=[];for(let n of e.split(`
|
|
212
|
+
`)){let e=ih(n);e&&rh(e)&&t.push(e)}return t}function dh(e){return oh(ah(e)).filter(rh)}function fh(e){return oh(ah(e)).length>0}function ph(e){let t=[],n=e.matchAll(nh);for(let e of n)t.push(ih(e[0]));return t}function mh(e,t){let n=null;for(let e=t.length-1;e>=0;e--){let r=t[e];if(th.has(r.command)){n=r;break}if((r.command===`head`||r.command===`tail`)&&fh(r)){n=r;break}}let r;if(!n)r=ph(e);else{switch(n.command){case`cat`:r=sh(n);break;case`ls`:r=ch(e,n);break;case`grep`:r=lh(e);break;case`find`:r=uh(e);break;case`head`:case`tail`:r=dh(n);break;default:r=ph(e)}r.length===0&&(r=ph(e))}let i=new Set,a=[];for(let e of r){let t=ih(e);!t||i.has(t)||(i.add(t),a.push(t))}return a}var hh=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-B9QCpaZR.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-CAQOzqfy.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-uTOF6Zpa.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-B0la1Q-P.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-CRMB4_AE.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-C13HY1h7.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-ewCHfbB3.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-fjvVauiI.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-BUZu7KNi.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-1iTO8NY5.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-DiYK6FgR.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-BC2VVHCa.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-DNkGMjtD.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-DRVZBAvY.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-DyNkF3aY.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-Bk22kVUG.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-DkOBrQlr.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-Dqepjl-k.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-3AIAIJVR-C9A_aSMK.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-3AIAIJVR-C9A_aSMK.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-3AIAIJVR-C9A_aSMK.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-FOQSCCX3-Cssz8GNh.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-VFTTATXJ-DO49xc40.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-POPGKRAI-DigGXYmO.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-Dmp_2ZoH.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-Cn_JDmUJ.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-DRcwK9Gt.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-BIRZEN2Y.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-C3M5_YM6.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-DrrobhxR.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-q2MQLs41.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-IRiMqQcZ.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-CAfX9d8n.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-BWwDphsm.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-BOmSL08U.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-g6FhPS64.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-Cu9ifXuc.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-fFssyAvW.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-B6C3-ghI.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-Ftqr8Jad.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-TPUOAIUQ-DaW1-9Vm.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-DlZHEU5f.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-2cTXnmQf.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-DZnTMKSh.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-B5uda2-L.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR--4eujSrM.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR--4eujSrM.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-TirEebNy.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-TirEebNy.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-DUTsR2Sf.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-dHdg4qaj.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-BaLssNp9.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-BaLssNp9.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-B5oRhK00.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-BA1gxmDh.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-BA1gxmDh.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-ODXZBPLY-Uj_VahOC.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-B4GnvJtR.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-Yo3lE_58.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-DRxppxbV.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-CS7jDpXp.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-Cpzi9cz-.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-BtzQ0nVf.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-D9r6kc_Z.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-5T3UU5KE-D5OdgUlD.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-DAG8dmoX.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-4uBt63v6.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-_uaXSgBK.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-ZIGAJ4YS-zZfB3nws.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-Ux5cbjMV.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-D5WzpTIY.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-DxZJ58G5.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-DczI7HKk.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-zmNkhqtV.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-Bn1LP0m_.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-PasvdXXR.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-CL228lzk.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-CL228lzk.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-CL228lzk.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(hh.push({name:`tar`,load:async()=>(await import(`./tar-ANUBEFJY-1lwT6ndQ.mjs`)).tarCommand}),hh.push({name:`yq`,load:async()=>(await import(`./yq-MJMAR36V-pRBq87Ya.mjs`)).yqCommand}),hh.push({name:`xan`,load:async()=>(await import(`./xan-BXDXYEIB-_Vtao535.mjs`)).xanCommand}),hh.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-56UMWEY3-D1Xq8d4g.mjs`)).sqlite3Command}));var gh=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(gh.push({name:`python3`,load:async()=>(await import(`./python3-AUFTPCU6-MeZyx8_A.mjs`)).python3Command}),gh.push({name:`python`,load:async()=>(await import(`./python3-AUFTPCU6-MeZyx8_A.mjs`)).pythonCommand}));var _h=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(_h.push({name:`js-exec`,load:async()=>(await import(`./js-exec-M6UR76J5-DSk5_wnx.mjs`)).jsExecCommand}),_h.push({name:`node`,load:async()=>(await import(`./js-exec-M6UR76J5-DSk5_wnx.mjs`)).nodeStubCommand}));var vh=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-Kn_Na_aU.mjs`)).curlCommand}],yh=new Map;function bh(e){return{name:e.name,async execute(t,n){let r=yh.get(e.name);if(r||(r=await sn.runTrustedAsync(()=>e.load()),yh.set(e.name,r)),n.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:r}=await import(`./flag-coverage-QT4N2Z44-B8zntJyb.mjs`);r(n.coverage,e.name,t)}return r.execute(t,n)}}}function xh(e){return(e?hh.filter(t=>e.includes(t.name)):hh).map(bh)}function Sh(){return vh.map(bh)}function Ch(){return gh.map(bh)}function wh(){return _h.map(bh)}function Th(e){return`load`in e&&typeof e.load==`function`}function Eh(e){let t=null;return{name:e.name,trusted:!0,async execute(n,r){return t||=await e.load(),t.execute(n,r)}}}var Dh=new TextEncoder;function Oh(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&`content`in e}var kh=class{data=new Map;constructor(e){if(this.data.set(`/`,{type:`directory`,mode:493,mtime:new Date}),e)for(let[t,n]of Object.entries(e))typeof n==`function`?this.writeFileLazy(t,n):Oh(n)?this.writeFileSync(t,n.content,void 0,{mode:n.mode,mtime:n.mtime}):this.writeFileSync(t,n)}ensureParentDirs(e){let t=qt(e);t!==`/`&&(this.data.has(t)||(this.ensureParentDirs(t),this.data.set(t,{type:`directory`,mode:493,mtime:new Date})))}writeFileSync(e,t,n,r){O(e,`write`);let i=D(e);this.ensureParentDirs(i);let a=nn(t,tn(n));this.data.set(i,{type:`file`,content:a,mode:r?.mode??420,mtime:r?.mtime??new Date})}writeFileLazy(e,t,n){O(e,`write`);let r=D(e);this.ensureParentDirs(r),this.data.set(r,{type:`file`,lazy:t,mode:n?.mode??420,mtime:n?.mtime??new Date})}async materializeLazy(e,t){let n=await t.lazy(),r={type:`file`,content:typeof n==`string`?Dh.encode(n):n,mode:t.mode,mtime:t.mtime};return this.data.set(e,r),r}async readFile(e,t){return rn(await this.readFileBuffer(e),tn(t))}async readFileBuffer(e){O(e,`open`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(n.type!==`file`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(`lazy`in n){let e=await this.materializeLazy(t,n);return e.content instanceof Uint8Array?e.content:Dh.encode(e.content)}return n.content instanceof Uint8Array?n.content:Dh.encode(n.content)}async writeFile(e,t,n){this.writeFileSync(e,t,n)}async appendFile(e,t,n){O(e,`append`);let r=D(e),i=this.data.get(r);if(i&&i.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let a=nn(t,tn(n));if(i?.type===`file`){let e=i;`lazy`in e&&(e=await this.materializeLazy(r,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:Dh.encode(`content`in e?e.content:``),n=new Uint8Array(t.length+a.length);n.set(t),n.set(a,t.length),this.data.set(r,{type:`file`,content:n,mode:e.mode,mtime:new Date})}else this.writeFileSync(e,t,n)}async exists(e){if(e.includes(`\0`))return!1;try{let t=this.resolvePathWithSymlinks(e);return this.data.has(t)}catch{return!1}}async stat(e){O(e,`stat`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, stat '${e}'`);n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:Dh.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}async lstat(e){O(e,`lstat`);let t=this.resolveIntermediateSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);if(n.type===`symlink`)return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:Dh.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}resolveIntermediateSymlinks(e){let t=D(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`);if(n.length<=1)return t;let r=``,i=new Set;for(let t=0;t<n.length-1;t++){let a=n[t];r=`${r}/${a}`;let o=this.data.get(r),s=0;for(;o&&o.type===`symlink`&&s<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);i.add(r),r=en(r,o.target),o=this.data.get(r),s++}if(s>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${r}/${n[n.length-1]}`}resolvePathWithSymlinks(e){let t=D(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`),r=``,i=new Set;for(let t of n){r=`${r}/${t}`;let n=this.data.get(r),a=0;for(;n&&n.type===`symlink`&&a<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);i.add(r),r=en(r,n.target),n=this.data.get(r),a++}if(a>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return r}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){O(e,`mkdir`);let n=D(e);if(this.data.has(n)){if(this.data.get(n)?.type===`file`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(!t?.recursive)throw Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let r=qt(n);if(r!==`/`&&!this.data.has(r))if(t?.recursive)this.mkdirSync(r,{recursive:!0});else throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(n,{type:`directory`,mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){O(e,`scandir`);let t=D(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Set;for(;n&&n.type===`symlink`;){if(r.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);r.add(t),t=en(t,n.target),n=this.data.get(t)}if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.type!==`directory`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);let i=t===`/`?`/`:`${t}/`,a=new Map;for(let[e,n]of this.data.entries())if(e!==t&&e.startsWith(i)){let t=e.slice(i.length),r=t.split(`/`)[0];r&&!t.includes(`/`,r.length)&&!a.has(r)&&a.set(r,{name:r,isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`})}return Array.from(a.values()).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}async rm(e,t){O(e,`rm`);let n=D(e),r=this.data.get(n);if(!r){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(r.type===`directory`){let r=await this.readdir(n);if(r.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of r){let r=Yt(n,e);await this.rm(r,t)}}}this.data.delete(n)}async cp(e,t,n){O(e,`cp`),O(t,`cp`);let r=D(e),i=D(t),a=this.data.get(r);if(!a)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(a.type===`file`)if(this.ensureParentDirs(i),`content`in a){let e=a.content instanceof Uint8Array?new Uint8Array(a.content):a.content;this.data.set(i,{...a,content:e})}else this.data.set(i,{...a});else if(a.type===`symlink`)this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type===`directory`){if(!n?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(i,{recursive:!0});let t=await this.readdir(r);for(let e of t){let t=Yt(r,e),a=Yt(i,e);await this.cp(t,a,n)}}}async mv(e,t){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,t){return Jt(e,t)}async chmod(e,t){O(e,`chmod`);let n=D(e),r=this.data.get(n);if(!r)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);r.mode=t}async symlink(e,t){O(t,`symlink`);let n=D(t);if(this.data.has(n))throw Error(`EEXIST: file already exists, symlink '${t}'`);this.ensureParentDirs(n),this.data.set(n,{type:`symlink`,target:e,mode:511,mtime:new Date})}async link(e,t){O(e,`link`),O(t,`link`);let n=D(e),r=D(t),i=this.data.get(n);if(!i)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(i.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(r))throw Error(`EEXIST: file already exists, link '${t}'`);let a=i;`lazy`in a&&(a=await this.materializeLazy(n,a)),this.ensureParentDirs(r),this.data.set(r,{type:`file`,content:a.content,mode:a.mode,mtime:a.mtime})}async readlink(e){O(e,`readlink`);let t=D(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.type!==`symlink`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);return n.target}async realpath(e){O(e,`realpath`);let t=this.resolvePathWithSymlinks(e);if(!this.data.has(t))throw Error(`ENOENT: no such file or directory, realpath '${e}'`);return t}async utimes(e,t,n){O(e,`utimes`);let r=D(e),i=this.resolvePathWithSymlinks(r),a=this.data.get(i);if(!a)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);a.mtime=n}};function Ah(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function jh(e,t){e.mkdirSync(`/bin`,{recursive:!0}),e.mkdirSync(`/usr/bin`,{recursive:!0}),t&&(e.mkdirSync(`/home/user`,{recursive:!0}),e.mkdirSync(`/tmp`,{recursive:!0}))}function Mh(e){e.mkdirSync(`/dev`,{recursive:!0}),e.writeFileSync(`/dev/null`,``),e.writeFileSync(`/dev/zero`,new Uint8Array),e.writeFileSync(`/dev/stdin`,``),e.writeFileSync(`/dev/stdout`,``),e.writeFileSync(`/dev/stderr`,``)}function Nh(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${xt}
|
|
210
213
|
`),e.writeFileSync(`/proc/self/exe`,`/bin/bash`),e.writeFileSync(`/proc/self/cmdline`,`bash\0`),e.writeFileSync(`/proc/self/comm`,`bash
|
|
211
|
-
`),e.writeFileLazy?e.writeFileLazy(`/proc/self/status`,()=>
|
|
212
|
-
`);let n=1;if(t.length>0){let e=Number.parseInt(t[0],10);if(Number.isNaN(e)||e<1)throw new
|
|
213
|
-
`);n=e}throw new
|
|
214
|
+
`),e.writeFileLazy?e.writeFileLazy(`/proc/self/status`,()=>ct(t)):e.writeFileSync(`/proc/self/status`,ct(t)),e.writeFileSync(`/proc/self/fd/0`,`/dev/stdin`),e.writeFileSync(`/proc/self/fd/1`,`/dev/stdout`),e.writeFileSync(`/proc/self/fd/2`,`/dev/stderr`)}function Ph(e,t,n={pid:1,ppid:0,uid:1e3,gid:1e3}){Ah(e)&&(jh(e,t),Mh(e),Nh(e,n))}var Fh=[`allexport`,`errexit`,`noglob`,`noclobber`,`noexec`,`nounset`,`pipefail`,`posix`,`verbose`,`xtrace`],Ih=[`braceexpand`,`hashall`,`interactive-comments`];function Lh(e){let t=[],n=[...Ih.map(e=>({name:e,enabled:!0})),...Fh.map(t=>({name:t,enabled:e[t]}))].sort((e,t)=>e.name.localeCompare(t.name));for(let e of n)e.enabled&&t.push(e.name);return t.join(`:`)}function Rh(e){e.state.env.set(`SHELLOPTS`,Lh(e.state.options))}var zh=[`dotglob`,`expand_aliases`,`extglob`,`failglob`,`globskipdots`,`globstar`,`lastpipe`,`nocaseglob`,`nocasematch`,`nullglob`,`xpg_echo`];function Bh(e){let t=[];for(let n of zh)e[n]&&t.push(n);return t.join(`:`)}function Vh(e){e.state.env.set(`BASHOPTS`,Bh(e.state.shoptOptions))}var Hh=`BASH_ALIAS_`;function Uh(e){return e.parts.length===1?e.parts[0].type===`Literal`:!1}function Wh(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type===`Literal`?t.value:null}function Gh(e,t){return e.env.get(`${Hh}${t}`)}function Kh(e,t,n){if(!t.name||!Uh(t.name))return t;let r=Wh(t.name);if(!r)return t;let i=Gh(e,r);if(!i||n.has(r))return t;try{n.add(r);let a=new Vt,o=i,s=i.endsWith(` `);if(!s)for(let e of t.args){let t=Jh(e);o+=` ${t}`}let c;try{c=a.parse(o)}catch(e){if(e instanceof Rt)throw e;return t}if(c.statements.length!==1||c.statements[0].pipelines.length!==1||c.statements[0].pipelines[0].commands.length!==1)return qh(t,i);let l=c.statements[0].pipelines[0].commands[0];if(l.type!==`SimpleCommand`)return qh(t,i);let u={...l,assignments:[...t.assignments,...l.assignments],redirections:[...l.redirections,...t.redirections],line:t.line};if(s&&t.args.length>0&&(u={...u,args:[...u.args,...t.args]},u.args.length>0)){let t=u.args[0];if(Uh(t)){let r=Wh(t);if(r&&Gh(e,r)){let r={type:`SimpleCommand`,name:t,args:u.args.slice(1),assignments:[],redirections:[]},i=Kh(e,r,n);i!==r&&(u={...u,name:i.name,args:[...i.args]})}}}return u}catch(e){throw n.delete(r),e}}function qh(e,t){let n=t;for(let t of e.args){let e=Jh(t);n+=` ${e}`}let r=new Vt;return{type:`SimpleCommand`,name:r.parseWordFromString(`eval`,!1,!1),args:[r.parseWordFromString(`'${n.replace(/'/g,`'\\''`)}'`,!1,!1)],assignments:e.assignments,redirections:e.redirections,line:e.line}}function Jh(e){let t=``;for(let n of e.parts)switch(n.type){case`Literal`:t+=n.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,`\\$1`);break;case`SingleQuoted`:t+=`'${n.value}'`;break;case`DoubleQuoted`:t+=`"${n.parts.map(e=>e.type===`Literal`?e.value:`$${e.type}`).join(``)}"`;break;case`ParameterExpansion`:t+=`\${${n.parameter}}`;break;case`CommandSubstitution`:t+=`$(...)`;break;case`ArithmeticExpansion`:t+=`$((${n.expression}))`;break;case`Glob`:t+=n.pattern;break;default:break}return t}async function Yh(e,t){let n=t.parts.map(e=>e.type===`Literal`?e.value:`\0`).join(``),r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!r||!n.endsWith(`)`))return null;let i=r[1],a=[],o=!1,s=``,c=!1;for(let n of t.parts)if(n.type===`Literal`){let e=n.value;if(!o){let t=e.indexOf(`=(`);t!==-1&&(o=!0,e=e.slice(t+2))}if(o){e.endsWith(`)`)&&(e=e.slice(0,-1));let t=e.split(/(\s+)/);for(let e of t)/^\s+$/.test(e)?(s||c)&&(a.push(s),s=``,c=!1):e&&(s+=e)}}else if(o)if(n.type===`BraceExpansion`)if(/^\[.+\]=/.test(s))s+=kt({type:`Word`,parts:[n]});else{(s||c)&&(a.push(s),s=``,c=!1);let t=await Gt(e,{type:`Word`,parts:[n]});a.push(...t.values)}else{(n.type===`SingleQuoted`||n.type===`DoubleQuoted`||n.type===`Escaped`)&&(c=!0);let t=await E(e,{type:`Word`,parts:[n]});s+=t}return(s||c)&&a.push(s),`${i}=(${a.map(e=>/^\[.+\]=/.test(e)?e:e===``?`''`:/[\s"'\\$`!*?[\]{}|&;<>()]/.test(e)&&!e.startsWith(`'`)&&!e.startsWith(`"`)?`'${e.replace(/'/g,`'\\''`)}'`:e).join(` `)})`}async function Xh(e,t){let n=-1,r=-1,i=!1;for(let e=0;e<t.parts.length;e++){let a=t.parts[e];if(a.type===`Literal`){let t=a.value.indexOf(`+=`);if(t!==-1){let o=a.value.slice(0,t);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){n=e,r=t,i=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(o)){n=e,r=t,i=!0;break}}let o=a.value.indexOf(`=`);if(o!==-1&&(o===0||a.value[o-1]!==`+`)){let t=a.value.slice(0,o);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(t)){n=e,r=o;break}}}}if(n===-1)return null;let a=t.parts.slice(0,n),o=t.parts[n];if(o.type!==`Literal`)return null;let s=i?2:1,c=o.value.slice(0,r),l=o.value.slice(r+s),u=t.parts.slice(n+1),d=``;for(let t of a)d+=await E(e,{type:`Word`,parts:[t]});d+=c;let f={type:`Word`,parts:l===``?u:[{type:`Literal`,value:l},...u]},p=f.parts.length>0?await E(e,f):``;return`${d}${i?`+=`:`=`}${p}`}var Zh=[`tar`,`yq`,`xan`,`sqlite3`,`python3`,`python`];function Qh(e){return Zh.includes(e)}var J=Object.freeze({stdout:``,stderr:``,exitCode:0});function Y(e=``){return{stdout:e,stderr:``,exitCode:0}}function X(e,t=1){return{stdout:``,stderr:e,exitCode:t}}function Z(e,t,n){return{stdout:e,stderr:t,exitCode:n}}function $h(e){return{stdout:``,stderr:``,exitCode:e?0:1}}function eg(e,t,n=``,r=``){throw new Xe(e,t,n,r)}function tg(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new Xe(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,`file_descriptors`)}function ng(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new rt;return J}if(t.length>1)throw new et(1,``,`bash: break: too many arguments
|
|
215
|
+
`);let n=1;if(t.length>0){let e=Number.parseInt(t[0],10);if(Number.isNaN(e)||e<1)throw new et(128,``,`bash: break: ${t[0]}: numeric argument required
|
|
216
|
+
`);n=e}throw new Ge(n)}async function rg(e,t){let n,r=!1,i=!1,a=0;for(;a<t.length;)if(t[a]===`--`){a++;break}else if(t[a]===`-L`)i=!1,a++;else if(t[a]===`-P`)i=!0,a++;else if(t[a].startsWith(`-`)&&t[a]!==`-`)a++;else break;let o=t.slice(a);if(o.length===0||o[0]===`~`?n=e.state.env.get(`HOME`)||`/`:o[0]===`-`?(n=e.state.previousDir,r=!0):n=o[0],!n.startsWith(`/`)&&!n.startsWith(`./`)&&!n.startsWith(`../`)&&n!==`.`&&n!==`..`){let t=e.state.env.get(`CDPATH`);if(t){let i=t.split(`:`).filter(e=>e);for(let t of i){let i=t.startsWith(`/`)?`${t}/${n}`:`${e.state.cwd}/${t}/${n}`;try{if((await e.fs.stat(i)).isDirectory){n=i,r=!0;break}}catch{}}}}let s=(n.startsWith(`/`)?n:`${e.state.cwd}/${n}`).split(`/`).filter(e=>e&&e!==`.`),c=``;for(let t of s)if(t===`..`)c=c.split(`/`).slice(0,-1).join(`/`)||`/`;else{c=c?`${c}/${t}`:`/${t}`;try{if(!(await e.fs.stat(c)).isDirectory)return X(`bash: cd: ${n}: Not a directory
|
|
214
217
|
`)}catch{return X(`bash: cd: ${n}: No such file or directory
|
|
215
218
|
`)}}let l=c||`/`;if(i)try{l=await e.fs.realpath(l)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=l,e.state.env.set(`PWD`,e.state.cwd),e.state.env.set(`OLDPWD`,e.state.previousDir),Y(r?`${l}
|
|
216
|
-
`:``)}function
|
|
217
|
-
`,!1}return e.state.env.has(`${t}_${i}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?
|
|
218
|
-
`,2):
|
|
219
|
-
`,2):Z(``,``,1)}if(t.length===3){let n=t[0],r=t[1],i=t[2];if(
|
|
220
|
-
`,2)
|
|
221
|
-
`)&&!r&&!i){o&&=(t.push(n),n=``,!1);continue}n+=s,o=!0}return o&&t.push(n),t}function
|
|
219
|
+
`:``)}function ig(e,t){return e.fs.resolvePath(e.state.cwd,t)}var ag=[`-e`,`-a`,`-f`,`-d`,`-r`,`-w`,`-x`,`-s`,`-L`,`-h`,`-k`,`-g`,`-u`,`-G`,`-O`,`-b`,`-c`,`-p`,`-S`,`-t`,`-N`];function og(e){return ag.includes(e)}async function sg(e,t,n){let r=ig(e,n);switch(t){case`-e`:case`-a`:return e.fs.exists(r);case`-f`:return await e.fs.exists(r)?(await e.fs.stat(r)).isFile:!1;case`-d`:return await e.fs.exists(r)?(await e.fs.stat(r)).isDirectory:!1;case`-r`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&256)!=0:!1;case`-w`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&128)!=0:!1;case`-x`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&64)!=0:!1;case`-s`:return await e.fs.exists(r)?(await e.fs.stat(r)).size>0:!1;case`-L`:case`-h`:try{return(await e.fs.lstat(r)).isSymbolicLink}catch{return!1}case`-k`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&512)!=0:!1;case`-g`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&1024)!=0:!1;case`-u`:return await e.fs.exists(r)?((await e.fs.stat(r)).mode&2048)!=0:!1;case`-G`:case`-O`:return e.fs.exists(r);case`-b`:return!1;case`-c`:return[`/dev/null`,`/dev/zero`,`/dev/random`,`/dev/urandom`,`/dev/tty`,`/dev/stdin`,`/dev/stdout`,`/dev/stderr`].includes(r);case`-p`:return!1;case`-S`:return!1;case`-t`:return!1;case`-N`:return e.fs.exists(r);default:return!1}}var cg=[`-nt`,`-ot`,`-ef`];function lg(e){return cg.includes(e)}async function ug(e,t,n,r){let i=ig(e,n),a=ig(e,r);switch(t){case`-nt`:try{let t=await e.fs.stat(i),n=await e.fs.stat(a);return t.mtime>n.mtime}catch{return!1}case`-ot`:try{let t=await e.fs.stat(i),n=await e.fs.stat(a);return t.mtime<n.mtime}catch{return!1}case`-ef`:try{return!await e.fs.exists(i)||!await e.fs.exists(a)?!1:e.fs.resolvePath(e.state.cwd,i)===e.fs.resolvePath(e.state.cwd,a)}catch{return!1}default:return!1}}var dg=new Set([`-eq`,`-ne`,`-lt`,`-le`,`-gt`,`-ge`]);function fg(e){return dg.has(e)}function pg(e,t,n){switch(e){case`-eq`:return t===n;case`-ne`:return t!==n;case`-lt`:return t<n;case`-le`:return t<=n;case`-gt`:return t>n;case`-ge`:return t>=n}}function mg(e){return e===`=`||e===`==`||e===`!=`}function hg(e,t,n,r=!1,i=!1,a=!1){if(r){let r=Dg(t,n,i,a);return e===`!=`?!r:r}if(i){let r=t.toLowerCase()===n.toLowerCase();return e===`!=`?!r:r}let o=t===n;return e===`!=`?!o:o}var gg=new Set([`-z`,`-n`]);function _g(e){return gg.has(e)}function vg(e,t){switch(e){case`-z`:return t===``;case`-n`:return t!==``}}async function yg(e,t){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let t=n[1],r=n[2];if(e.state.associativeArrays?.has(t)){let n=r;return(n.startsWith(`'`)&&n.endsWith(`'`)||n.startsWith(`"`)&&n.endsWith(`"`))&&(n=n.slice(1,-1)),n=n.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(t,n)=>e.state.env.get(n)||``),e.state.env.has(`${t}_${n}`)}let i;try{i=await It(e,Tt(new Vt,r).expression)}catch{if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{let t=e.state.env.get(r);i=t?Number.parseInt(t,10):0}}if(i<0){let n=gt(e,t),r=e.state.currentLine;if(n.length===0||(i=Math.max(...n)+1+i,i<0))return e.state.expansionStderr=(e.state.expansionStderr||``)+`bash: line ${r}: ${t}: bad array subscript
|
|
220
|
+
`,!1}return e.state.env.has(`${t}_${i}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?ot(e,t).length>0:gt(e,t).length>0}async function bg(e,t){switch(t.type){case`CondBinary`:{let n=await E(e,t.left),r=t.right.parts.length>0&&t.right.parts.every(e=>e.type===`SingleQuoted`||e.type===`DoubleQuoted`||e.type===`Escaped`&&t.operator!==`=~`),i;if(i=t.operator===`=~`?r?ut(await E(e,t.right)):await Ot(e,t.right):mg(t.operator)&&!r?await bt(e,t.right):await E(e,t.right),mg(t.operator)){let a=e.state.shoptOptions.nocasematch;return hg(t.operator,n,i,!r,a,!0)}if(fg(t.operator))return pg(t.operator,await Ng(e,n),await Ng(e,i));if(lg(t.operator))return ug(e,t.operator,n,i);switch(t.operator){case`=~`:try{let t=e.state.shoptOptions.nocasematch,r=We(Lg(i),t?`i`:``).match(n);if(Lt(e,`BASH_REMATCH`),r)for(let t=0;t<r.length;t++)e.state.env.set(`BASH_REMATCH_${t}`,r[t]||``);return r!==null}catch{throw Error(`syntax error in regular expression`)}case`<`:return n<i;case`>`:return n>i;default:return!1}}case`CondUnary`:{let n=await E(e,t.operand);return og(t.operator)?sg(e,t.operator,n):_g(t.operator)?vg(t.operator,n):t.operator===`-v`?await yg(e,n):t.operator===`-o`?Mg(e,n):!1}case`CondNot`:return e.state.shoptOptions.extglob&&t.operand.type===`CondGroup`&&t.operand.expression.type===`CondWord`?`!(${await E(e,t.operand.expression.word)})`!=``:!await bg(e,t.operand);case`CondAnd`:return await bg(e,t.left)?await bg(e,t.right):!1;case`CondOr`:return await bg(e,t.left)?!0:await bg(e,t.right);case`CondGroup`:return await bg(e,t.expression);case`CondWord`:return await E(e,t.word)!==``;default:return!1}}async function xg(e,t){if(t.length===0)return Z(``,``,1);if(t.length===1)return $h(!!t[0]);if(t.length===2){let n=t[0],r=t[1];return n===`(`?X(`test: '(' without matching ')'
|
|
221
|
+
`,2):og(n)?$h(await sg(e,n,r)):_g(n)?$h(vg(n,r)):n===`!`?$h(!r):n===`-v`?$h(await yg(e,r)):n===`-o`?$h(Mg(e,r)):n===`=`||n===`==`||n===`!=`||n===`<`||n===`>`||n===`-eq`||n===`-ne`||n===`-lt`||n===`-le`||n===`-gt`||n===`-ge`||n===`-nt`||n===`-ot`||n===`-ef`?X(`test: ${n}: unary operator expected
|
|
222
|
+
`,2):Z(``,``,1)}if(t.length===3){let n=t[0],r=t[1],i=t[2];if(mg(r))return $h(hg(r,n,i));if(fg(r)){let e=Ig(n),t=Ig(i);return!e.valid||!t.valid?Z(``,``,2):$h(pg(r,e.value,t.value))}if(lg(r))return $h(await ug(e,r,n,i));switch(r){case`-a`:return $h(n!==``&&i!==``);case`-o`:return $h(n!==``||i!==``);case`>`:return $h(n>i);case`<`:return $h(n<i)}if(n===`!`){let t=await xg(e,[r,i]);return Z(``,t.stderr,t.exitCode===0?1:t.exitCode===1?0:t.exitCode)}if(n===`(`&&i===`)`)return $h(r!==``)}if(t.length===4){if(t[0]===`!`){let n=await xg(e,t.slice(1));return Z(``,n.stderr,n.exitCode===0?1:n.exitCode===1?0:n.exitCode)}if(t[0]===`(`&&t[3]===`)`)return xg(e,[t[1],t[2]])}let n=await Sg(e,t,0);return n.pos<t.length?X(`test: too many arguments
|
|
223
|
+
`,2):$h(n.value)}async function Sg(e,t,n){return Cg(e,t,n)}async function Cg(e,t,n){let{value:r,pos:i}=await wg(e,t,n);for(;t[i]===`-o`;){let n=await wg(e,t,i+1);r||=n.value,i=n.pos}return{value:r,pos:i}}async function wg(e,t,n){let{value:r,pos:i}=await Tg(e,t,n);for(;t[i]===`-a`;){let n=await Tg(e,t,i+1);r&&=n.value,i=n.pos}return{value:r,pos:i}}async function Tg(e,t,n){if(t[n]===`!`){let{value:r,pos:i}=await Tg(e,t,n+1);return{value:!r,pos:i}}return Eg(e,t,n)}async function Eg(e,t,n){let r=t[n];if(r===`(`){let{value:r,pos:i}=await Sg(e,t,n+1);return{value:r,pos:t[i]===`)`?i+1:i}}let i=t[n+1];if(mg(i))return{value:hg(i,r,t[n+2]??``),pos:n+3};if(fg(i)){let e=Ig(r),a=Ig(t[n+2]??`0`);return!e.valid||!a.valid?{value:!1,pos:n+3}:{value:pg(i,e.value,a.value),pos:n+3}}return lg(i)?{value:await ug(e,i,r,t[n+2]??``),pos:n+3}:og(r)?{value:await sg(e,r,t[n+1]??``),pos:n+2}:_g(r)?{value:vg(r,t[n+1]??``),pos:n+2}:r===`-v`?{value:await yg(e,t[n+1]??``),pos:n+2}:r===`-o`?{value:Mg(e,t[n+1]??``),pos:n+2}:{value:r!==void 0&&r!==``,pos:n+1}}function Dg(e,t,n=!1,r=!1){return We(`^${Og(t,r)}$`,n?`is`:`s`).test(e)}function Og(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(t&&(i===`@`||i===`*`||i===`+`||i===`?`||i===`!`)&&r+1<e.length&&e[r+1]===`(`){let a=kg(e,r+1);if(a!==-1){let o=Ag(e.slice(r+2,a)),s=o.map(e=>Og(e,t)),c=s.length>0?s.join(`|`):`(?:)`;if(i===`@`)n+=`(?:${c})`;else if(i===`*`)n+=`(?:${c})*`;else if(i===`+`)n+=`(?:${c})+`;else if(i===`?`)n+=`(?:${c})?`;else if(i===`!`)if(a<e.length-1){let e=o.map(e=>jg(e,t));if(e.every(e=>e!==null)&&e.every(t=>t===e[0])&&e[0]!==null){let t=e[0];if(t===0)n+=`(?:.+)`;else{let e=[];t>0&&e.push(`.{0,${t-1}}`),e.push(`.{${t+1},}`),e.push(`(?!(?:${c})).{${t}}`),n+=`(?:${e.join(`|`)})`}}else n+=`(?:(?!(?:${c})).)*?`}else n+=`(?!(?:${c})$).*`;r=a;continue}}if(i===`\\`)if(r+1<e.length){let t=e[r+1];/[\\^$.|+(){}[\]*?]/.test(t)?n+=`\\${t}`:n+=t,r++}else n+=`\\\\`;else if(i===`*`)n+=`.*`;else if(i===`?`)n+=`.`;else if(i===`[`){let t=e.indexOf(`]`,r+1);t===-1?n+=`\\[`:(n+=e.slice(r,t+1),r=t)}else /[\\^$.|+(){}]/.test(i)?n+=`\\${i}`:n+=i}return n}function kg(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let t=e[r];if(t===`\\`){r+=2;continue}if(t===`(`)n++;else if(t===`)`&&(n--,n===0))return r;r++}return-1}function Ag(e){let t=[],n=``,r=0,i=0;for(;i<e.length;){let a=e[i];if(a===`\\`){n+=a,i+1<e.length?(n+=e[i+1],i+=2):i++;continue}a===`(`?(r++,n+=a):a===`)`?(r--,n+=a):a===`|`&&r===0?(t.push(n),n=``):n+=a,i++}return t.push(n),t}function jg(e,t){let n=0,r=0;for(;r<e.length;){let i=e[r];if(t&&(i===`@`||i===`*`||i===`+`||i===`?`||i===`!`)&&r+1<e.length&&e[r+1]===`(`){let a=kg(e,r+1);if(a!==-1){if(i===`@`){let i=Ag(e.slice(r+2,a)).map(e=>jg(e,t));if(i.every(e=>e!==null)&&i.every(e=>e===i[0])){n+=i[0],r=a+1;continue}return null}return null}}if(i===`*`)return null;if(i===`?`){n+=1,r++;continue}if(i===`[`){let t=e.indexOf(`]`,r+1);if(t!==-1){n+=1,r=t+1;continue}n+=1,r++;continue}if(i===`\\`){n+=1,r+=2;continue}n+=1,r++}return n}function Mg(e,t){let n=new Map([[`errexit`,()=>e.state.options.errexit===!0],[`nounset`,()=>e.state.options.nounset===!0],[`pipefail`,()=>e.state.options.pipefail===!0],[`xtrace`,()=>e.state.options.xtrace===!0],[`e`,()=>e.state.options.errexit===!0],[`u`,()=>e.state.options.nounset===!0],[`x`,()=>e.state.options.xtrace===!0]]).get(t);return n?n():!1}async function Ng(e,t){if(t=t.trim(),t===``)return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(t))return Fg(t);try{return await It(e,Tt(new Vt,t).expression)}catch{return Fg(t)}}function Pg(e,t){let n=0;for(let r of e){let e;if(r>=`0`&&r<=`9`)e=r.charCodeAt(0)-48;else if(r>=`a`&&r<=`z`)e=r.charCodeAt(0)-97+10;else if(r>=`A`&&r<=`Z`)e=r.charCodeAt(0)-65+36;else if(r===`@`)e=62;else if(r===`_`)e=63;else return NaN;if(e>=t)return NaN;n=n*t+e}return n}function Fg(e){if(e=e.trim(),e===``)return 0;let t=!1;e.startsWith(`-`)?(t=!0,e=e.slice(1)):e.startsWith(`+`)&&(e=e.slice(1));let n,r=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let e=Number.parseInt(r[1],10);n=e>=2&&e<=64?Pg(r[2],e):0}else n=/^0[xX][0-9a-fA-F]+$/.test(e)?Number.parseInt(e,16):/^0[0-7]+$/.test(e)?Number.parseInt(e,8):Number.parseInt(e,10);return Number.isNaN(n)&&(n=0),t?-n:n}function Ig(e){if(e=e.trim(),e===``)return{value:0,valid:!0};let t=!1;if(e.startsWith(`-`)?(t=!0,e=e.slice(1)):e.startsWith(`+`)&&(e=e.slice(1)),!/^\d+$/.test(e))return{value:0,valid:!1};let n=Number.parseInt(e,10);return Number.isNaN(n)?{value:0,valid:!1}:{value:t?-n:n,valid:!0}}function Lg(e){let t=``,n=0;for(;n<e.length;)if(e[n]===`\\`&&n+1<e.length)t+=e[n]+e[n+1],n+=2;else if(e[n]===`[`){let r=Rg(e,n);t+=r.converted,n=r.endIndex}else t+=e[n],n++;return t}function Rg(e,t){let n=t+1,r=`[`;n<e.length&&(e[n]===`^`||e[n]===`!`)&&(r+=`^`,n++);let i=!1;n<e.length&&e[n]===`]`&&(i=!0,n++);let a=!1;n<e.length&&e[n]===`[`&&n+1<e.length&&e[n+1]!==`:`&&(a=!0,n++);let o=``,s=!1;for(;n<e.length;){let t=e[n];if(t===`]`){s=!0,n++;break}if(t===`[`&&n+1<e.length&&e[n+1]===`:`){let t=e.indexOf(`:]`,n+2);if(t!==-1){let r=e.slice(n+2,t);o+=zg(r),n=t+2;continue}}if(t===`[`&&n+1<e.length){let t=e[n+1];if(t===`.`||t===`=`){let r=`${t}]`,i=e.indexOf(r,n+2);if(i!==-1){let t=e.slice(n+2,i);o+=t,n=i+2;continue}}}if(t===`\\`&&n+1<e.length){o+=t+e[n+1],n+=2;continue}o+=t,n++}return s?(i&&(r+=`\\]`),a&&(r+=`\\[`),r+=o,r+=`]`,{converted:r,endIndex:n}):{converted:`\\[`,endIndex:t+1}}function zg(e){return new Map([[`alnum`,`a-zA-Z0-9`],[`alpha`,`a-zA-Z`],[`ascii`,`\\x00-\\x7F`],[`blank`,` \\t`],[`cntrl`,`\\x00-\\x1F\\x7F`],[`digit`,`0-9`],[`graph`,`!-~`],[`lower`,`a-z`],[`print`,` -~`],[`punct`,"!-/:-@\\[-`{-~"],[`space`,` \\t\\n\\r\\f\\v`],[`upper`,`A-Z`],[`word`,`a-zA-Z0-9_`],[`xdigit`,`0-9A-Fa-f`]]).get(e)??``}function Bg(e){let t=[],n=``,r=!1,i=!1,a=!1,o=!1;for(let s of e){if(a){n+=s,a=!1,o=!0;continue}if(s===`\\`){a=!0;continue}if(s===`'`&&!i){r||(o=!0),r=!r;continue}if(s===`"`&&!r){i||(o=!0),i=!i;continue}if((s===` `||s===` `||s===`
|
|
224
|
+
`)&&!r&&!i){o&&=(t.push(n),n=``,!1);continue}n+=s,o=!0}return o&&t.push(n),t}function Vg(e){let t=[],n=0;for(;n<e.length;){for(;n<e.length&&/\s/.test(e[n]);)n++;if(n>=e.length)break;if(e[n]!==`[`){n++;continue}n++;let r=``;if(e[n]===`'`||e[n]===`"`){let t=e[n];for(n++;n<e.length&&e[n]!==t;)r+=e[n],n++;e[n]===t&&n++}else for(;n<e.length&&e[n]!==`]`&&e[n]!==`=`;)r+=e[n],n++;for(;n<e.length&&e[n]!==`]`;)n++;if(e[n]===`]`&&n++,e[n]!==`=`)continue;n++;let i=``;if(e[n]===`'`||e[n]===`"`){let t=e[n];for(n++;n<e.length&&e[n]!==t;)e[n]===`\\`&&n+1<e.length&&n++,i+=e[n],n++;e[n]===t&&n++}else for(;n<e.length&&!/\s/.test(e[n]);)i+=e[n],n++;t.push([r,i])}return t}function Hg(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:Bg(t[2])};let n=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(n)return{name:n[1],isArray:!1,arrayIndex:n[2],value:n[3]};if(e.includes(`=`)){let t=e.indexOf(`=`);return{name:e.slice(0,t),isArray:!1,value:e.slice(t+1)}}return{name:e,isArray:!1}}async function Ug(e,t){try{return await It(e,Tt(new Vt,t).expression)}catch{let e=parseInt(t,10);return Number.isNaN(e)?0:e}}async function Wg(e,t,n={}){let{name:r,isArray:i,arrayElements:a,value:o,arrayIndex:s}=t,{makeReadonly:c=!1,checkReadonly:l=!0}=n;if(l){let t=lt(e,r);if(t)return t}if(i&&a){for(let t=0;t<a.length;t++)e.state.env.set(`${r}_${t}`,a[t]);e.state.env.set(`${r}__length`,String(a.length))}else if(s!==void 0&&o!==void 0){let t=await Ug(e,s);e.state.env.set(`${r}_${t}`,o),t>=parseInt(e.state.env.get(`${r}__length`)??`0`,10)&&e.state.env.set(`${r}__length`,String(t+1))}else o!==void 0&&e.state.env.set(r,o);return c&&vt(e,r),null}function Gg(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function Kg(e,t){return e.state.localVarDepth?.get(t)}function qg(e,t){e.state.localVarDepth?.delete(t)}function Jg(e,t,n){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:n,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function Yg(e,t){let n=e.state.localVarStack?.get(t);if(!(!n||n.length===0))return n.pop()}function Xg(e,t){if(e.state.localVarStack)for(let[n,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(n)}}var Zg=new Set([`:`,`.`,`break`,`continue`,`eval`,`exec`,`exit`,`export`,`readonly`,`return`,`set`,`shift`,`trap`,`unset`]);function Qg(e){return Zg.has(e)}var $g=new Set([`if`,`then`,`else`,`elif`,`fi`,`case`,`esac`,`for`,`select`,`while`,`until`,`do`,`done`,`in`,`function`,`{`,`}`,`time`,`[[`,`]]`,`!`]),e_=new Set(`:,true,false,cd,export,unset,exit,local,set,break,continue,return,eval,shift,getopts,compgen,complete,compopt,pushd,popd,dirs,source,.,read,mapfile,readarray,declare,typeset,readonly,let,command,shopt,exec,test,[,echo,printf,pwd,alias,unalias,type,hash,ulimit,umask,trap,times,wait,kill,jobs,fg,bg,disown,suspend,fc,history,help,enable,builtin,caller`.split(`,`));async function t_(e,t,n,r){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${n}: Is a directory
|
|
222
225
|
`;if(r.checkNoclobber&&e.state.options.noclobber&&!r.isClobber&&n!==`/dev/null`)return`bash: ${n}: cannot overwrite existing file
|
|
223
|
-
`}catch{}return null}function
|
|
224
|
-
`};n.set(r,await
|
|
225
|
-
`);else if(n.operator===`<`||n.operator===`<>`)try{let n=e.fs.resolvePath(e.state.cwd,r),i=await e.fs.readFile(n);
|
|
226
|
-
`,1)}}}return null}async function
|
|
226
|
+
`}catch{}return null}function n_(e){let t=Math.min(e.length,8192);for(let n=0;n<t;n++)if(e.charCodeAt(n)>127)return`utf8`;return`binary`}function r_(e){if(!e.startsWith(`__rw__:`))return null;let t=e.slice(7),n=t.indexOf(`:`);if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let i=n+1,a=t.slice(i,i+r),o=i+r+1,s=t.slice(o),c=s.indexOf(`:`);if(c===-1)return null;let l=Number.parseInt(s.slice(0,c),10);return Number.isNaN(l)||l<0?null:{path:a,position:l,content:s.slice(c+1)}}async function i_(e,t){let n=new Map;for(let r=0;r<t.length;r++){let i=t[r];if(i.target.type!==`HereDoc`)if(i.operator===`>&`||i.operator===`<&`){if(Ft(e,i.target))return{targets:n,error:`bash: $@: ambiguous redirect
|
|
227
|
+
`};n.set(r,await E(e,i.target))}else{let t=await Mt(e,i.target);if(`error`in t)return{targets:n,error:t.error};n.set(r,t.target)}}return{targets:n}}function a_(e){e.state.nextFd===void 0&&(e.state.nextFd=10);let t=e.state.nextFd,n=e.limits.maxFileDescriptors;if(t>=n)throw Error(`bash: cannot allocate file descriptor: too many open files (max ${n})`);return e.state.nextFd++,t}async function o_(e,t){for(let n of t){if(!n.fdVariable)continue;if(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),(n.operator===`>&`||n.operator===`<&`)&&n.target.type===`Word`&&await E(e,n.target)===`-`){let t=e.state.env.get(n.fdVariable);if(t!==void 0){let n=Number.parseInt(t,10);Number.isNaN(n)||e.state.fileDescriptors.delete(n)}continue}let t=a_(e);if(e.state.env.set(n.fdVariable,String(t)),n.target.type===`Word`){let r=await E(e,n.target);if(n.operator===`>&`||n.operator===`<&`){let n=Number.parseInt(r,10);if(!Number.isNaN(n)){let r=e.state.fileDescriptors.get(n);r!==void 0&&(tg(e),e.state.fileDescriptors.set(t,r));continue}}if(n.operator===`>`||n.operator===`>>`||n.operator===`>|`||n.operator===`&>`||n.operator===`&>>`){let i=e.fs.resolvePath(e.state.cwd,r);(n.operator===`>`||n.operator===`>|`||n.operator===`&>`)&&await e.fs.writeFile(i,``,`binary`),tg(e),e.state.fileDescriptors.set(t,`__file__:${i}`)}else if(n.operator===`<<<`)tg(e),e.state.fileDescriptors.set(t,`${r}
|
|
228
|
+
`);else if(n.operator===`<`||n.operator===`<>`)try{let n=e.fs.resolvePath(e.state.cwd,r),i=await e.fs.readFile(n);tg(e),e.state.fileDescriptors.set(t,i)}catch{return Z(``,`bash: ${r}: No such file or directory
|
|
229
|
+
`,1)}}}return null}async function s_(e,t){for(let n of t){if(n.target.type===`HereDoc`)continue;let t=n.operator===`>&`;if(n.operator!==`>`&&n.operator!==`>|`&&n.operator!==`&>`&&!t)continue;let r;if(t){if(r=await E(e,n.target),r===`-`||!Number.isNaN(Number.parseInt(r,10))||n.fd!=null)continue}else{let t=await Mt(e,n.target);if(`error`in t)return Z(``,t.error,1);r=t.target}let i=e.fs.resolvePath(e.state.cwd,r),a=n.operator===`>|`;if(i.includes(`\0`))return Z(``,`bash: ${r}: No such file or directory
|
|
227
230
|
`,1);try{let t=await e.fs.stat(i);if(t.isDirectory)return Z(``,`bash: ${r}: Is a directory
|
|
228
231
|
`,1);if(e.state.options.noclobber&&!a&&!t.isDirectory&&r!==`/dev/null`)return Z(``,`bash: ${r}: cannot overwrite existing file
|
|
229
232
|
`,1)}catch{}if(r!==`/dev/null`&&r!==`/dev/stdout`&&r!==`/dev/stderr`&&r!==`/dev/full`&&await e.fs.writeFile(i,``,`binary`),r===`/dev/full`)return Z(``,`bash: /dev/full: No space left on device
|
|
230
|
-
`,1)}return null}async function
|
|
231
|
-
`,o=1,i=``;continue}l=await
|
|
233
|
+
`,1)}return null}async function c_(e,t,n,r){let{stdout:i,stderr:a,exitCode:o}=t,s=t.stdoutEncoding===`binary`?()=>`binary`:e=>n_(e);for(let t=0;t<n.length;t++){let c=n[t];if(c.target.type===`HereDoc`)continue;let l,u=r?.get(t);if(u!==void 0)l=u;else if(c.operator===`>&`||c.operator===`<&`){if(Ft(e,c.target)){a+=`bash: $@: ambiguous redirect
|
|
234
|
+
`,o=1,i=``;continue}l=await E(e,c.target)}else{let t=await Mt(e,c.target);if(`error`in t){a+=t.error,o=1,i=``;continue}l=t.target}if(!c.fdVariable){if(l.includes(`\0`)){a+=`bash: ${l.replace(/\0/g,``)}: No such file or directory
|
|
232
235
|
`,o=1,i=``;continue}switch(c.operator){case`>`:case`>|`:{let t=c.fd??1,n=c.operator===`>|`;if(t===1){if(l===`/dev/stdout`)break;if(l===`/dev/stderr`){a+=i,i=``;break}if(l===`/dev/full`){a+=`bash: echo: write error: No space left on device
|
|
233
|
-
`,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),r=await
|
|
234
|
-
`,o=1;break}if(l===`/dev/null`)a=``;else{let t=e.fs.resolvePath(e.state.cwd,l),r=await
|
|
235
|
-
`,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await
|
|
236
|
-
`,o=1;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await
|
|
237
|
-
`,o=1):(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,n),r>=3&&e.state.fileDescriptors?.delete(r))}break}if(l===`2`||l===`&2`)t===1&&(a+=i,i=``);else if(l===`1`||l===`&1`)i+=a,a=``;else{let n=Number.parseInt(l,10);if(Number.isNaN(n)){if(c.operator===`>&`){let n=e.fs.resolvePath(e.state.cwd,l),r=await
|
|
236
|
+
`,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),r=await t_(e,t,l,{checkNoclobber:!0,isClobber:n});if(r){a+=r,o=1,i=``;break}await e.fs.writeFile(t,i,s(i)),i=``}else if(t===2){if(l===`/dev/stderr`)break;if(l===`/dev/stdout`){i+=a,a=``;break}if(l===`/dev/full`){a+=`bash: echo: write error: No space left on device
|
|
237
|
+
`,o=1;break}if(l===`/dev/null`)a=``;else{let t=e.fs.resolvePath(e.state.cwd,l),r=await t_(e,t,l,{checkNoclobber:!0,isClobber:n});if(r){a+=r,o=1;break}await e.fs.writeFile(t,a,n_(a)),a=``}}break}case`>>`:{let t=c.fd??1;if(t===1){if(l===`/dev/stdout`)break;if(l===`/dev/stderr`){a+=i,i=``;break}if(l===`/dev/full`){a+=`bash: echo: write error: No space left on device
|
|
238
|
+
`,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await t_(e,t,l,{});if(n){a+=n,o=1,i=``;break}await e.fs.appendFile(t,i,s(i)),i=``}else if(t===2){if(l===`/dev/stderr`)break;if(l===`/dev/stdout`){i+=a,a=``;break}if(l===`/dev/full`){a+=`bash: echo: write error: No space left on device
|
|
239
|
+
`,o=1;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await t_(e,t,l,{});if(n){a+=n,o=1;break}await e.fs.appendFile(t,a,n_(a)),a=``}break}case`>&`:case`<&`:{let t=c.fd??1;if(l===`-`)break;if(l.endsWith(`-`)){let n=l.slice(0,-1),r=Number.parseInt(n,10);if(!Number.isNaN(r)){let n=e.state.fileDescriptors?.get(r);n===void 0?r===1||r===2?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,`__dupout__:${r}`)):r===0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,`__dupin__:${r}`)):r>=3&&(a+=`bash: ${r}: Bad file descriptor
|
|
240
|
+
`,o=1):(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,n),r>=3&&e.state.fileDescriptors?.delete(r))}break}if(l===`2`||l===`&2`)t===1&&(a+=i,i=``);else if(l===`1`||l===`&1`)i+=a,a=``;else{let n=Number.parseInt(l,10);if(Number.isNaN(n)){if(c.operator===`>&`){let n=e.fs.resolvePath(e.state.cwd,l),r=await t_(e,n,l,{checkNoclobber:!0});if(r){a=r,o=1,i=``;break}if(c.fd==null){let t=i+a;await e.fs.writeFile(n,t,s(t)),i=``,a=``}else t===1?(await e.fs.writeFile(n,i,s(i)),i=``):t===2&&(await e.fs.writeFile(n,a,n_(a)),a=``)}}else{let r=e.state.fileDescriptors?.get(n);if(r?.startsWith(`__file__:`)){let n=r.slice(9);t===1?(await e.fs.appendFile(n,i,s(i)),i=``):t===2&&(await e.fs.appendFile(n,a,n_(a)),a=``)}else if(r?.startsWith(`__rw__:`)){let n=r_(r);n&&(t===1?(await e.fs.appendFile(n.path,i,s(i)),i=``):t===2&&(await e.fs.appendFile(n.path,a,n_(a)),a=``))}else if(r?.startsWith(`__dupout__:`)){let n=Number.parseInt(r.slice(11),10);if(n!==1)if(n===2)t===1&&(a+=i,i=``);else{let r=e.state.fileDescriptors?.get(n);if(r?.startsWith(`__file__:`)){let n=r.slice(9);t===1?(await e.fs.appendFile(n,i,s(i)),i=``):t===2&&(await e.fs.appendFile(n,a,n_(a)),a=``)}}}else (r?.startsWith(`__dupin__:`)||n>=3)&&(a+=`bash: ${n}: Bad file descriptor
|
|
238
241
|
`,o=1,i=``)}}break}case`&>`:{if(l===`/dev/full`){a=`bash: echo: write error: No space left on device
|
|
239
|
-
`,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await
|
|
240
|
-
`,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await
|
|
241
|
-
`);let n={...t,sourceFile:t.sourceFile??e.state.currentSource??`main`};return e.state.functions.set(t.name,n),J}async function
|
|
242
|
+
`,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await t_(e,t,l,{checkNoclobber:!0});if(n){a=n,o=1,i=``;break}let r=i+a;await e.fs.writeFile(t,r,s(r)),i=``,a=``;break}case`&>>`:{if(l===`/dev/full`){a=`bash: echo: write error: No space left on device
|
|
243
|
+
`,o=1,i=``;break}let t=e.fs.resolvePath(e.state.cwd,l),n=await t_(e,t,l,{});if(n){a=n,o=1,i=``;break}let r=i+a;await e.fs.appendFile(t,r,s(r)),i=``,a=``;break}}}}let c=e.state.fileDescriptors?.get(1);if(c){if(c===`__dupout__:2`)a+=i,i=``;else if(c.startsWith(`__file__:`)){let t=c.slice(9);await e.fs.appendFile(t,i,s(i)),i=``}else if(c.startsWith(`__file_append__:`)){let t=c.slice(16);await e.fs.appendFile(t,i,s(i)),i=``}}let l=e.state.fileDescriptors?.get(2);if(l){if(l===`__dupout__:1`)i+=a,a=``;else if(l.startsWith(`__file__:`)){let t=l.slice(9);await e.fs.appendFile(t,a,n_(a)),a=``}else if(l.startsWith(`__file_append__:`)){let t=l.slice(16);await e.fs.appendFile(t,a,n_(a)),a=``}}return Z(i,a,o)}function l_(e,t){if(e.state.options.posix&&Zg.has(t.name))throw new et(2,``,`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
|
|
244
|
+
`);let n={...t,sourceFile:t.sourceFile??e.state.currentSource??`main`};return e.state.functions.set(t.name,n),J}async function u_(e,t){let n=``;for(let r of t)if((r.operator===`<<`||r.operator===`<<-`)&&r.target.type===`HereDoc`){let t=r.target,i=await E(e,t.content);t.stripTabs&&(i=i.split(`
|
|
242
245
|
`).map(e=>e.replace(/^\t+/,``)).join(`
|
|
243
|
-
`)),(r.fd??0)===0&&(n=i)}else if(r.operator===`<<<`&&r.target.type===`Word`)n=`${await
|
|
244
|
-
`;else if(r.operator===`<`&&r.target.type===`Word`){let t=await
|
|
246
|
+
`)),(r.fd??0)===0&&(n=i)}else if(r.operator===`<<<`&&r.target.type===`Word`)n=`${await E(e,r.target)}
|
|
247
|
+
`;else if(r.operator===`<`&&r.target.type===`Word`){let t=await E(e,r.target),i=e.fs.resolvePath(e.state.cwd,t);try{n=await e.fs.readFile(i)}catch{}}return n}async function d_(e,t,n,r=``,i){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,eg(`${t.name}: maximum recursion depth (${e.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,`recursion`)),e.state.funcNameStack||(e.state.funcNameStack=[]),e.state.callLineStack||(e.state.callLineStack=[]),e.state.sourceStack||(e.state.sourceStack=[]),e.state.funcNameStack.unshift(t.name),e.state.callLineStack.unshift(i??e.state.currentLine),e.state.sourceStack.unshift(t.sourceFile??`main`),e.state.localScopes.push(new Map),e.state.localExportedVars||(e.state.localExportedVars=[]),e.state.localExportedVars.push(new Set);let a=new Map;for(let t=0;t<n.length;t++)a.set(String(t+1),e.state.env.get(String(t+1))),e.state.env.set(String(t+1),n[t]);a.set(`@`,e.state.env.get(`@`)),a.set(`#`,e.state.env.get(`#`)),e.state.env.set(`@`,n.join(` `)),e.state.env.set(`#`,String(n.length));let o=()=>{let t=e.state.localScopes.length-1,n=e.state.localScopes.pop();if(n)for(let[t,r]of n)r===void 0?e.state.env.delete(t):e.state.env.set(t,r);if(Xg(e,t),e.state.fullyUnsetLocals)for(let[n,r]of e.state.fullyUnsetLocals.entries())r===t&&e.state.fullyUnsetLocals.delete(n);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let t=e.state.localExportedVars.pop();if(t)for(let n of t)e.state.exportedVars?.delete(n)}for(let[t,n]of a)n===void 0?e.state.env.delete(t):e.state.env.set(t,n);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},{targets:s,error:c}=await i_(e,t.redirections);if(c)return o(),Z(``,c,1);try{let n=await u_(e,t.redirections),i=r||n,a=await e.executeCommand(t.body,i);return o(),c_(e,a,t.redirections,s)}catch(n){if(o(),n instanceof Ze)return c_(e,Z(n.stdout,n.stderr,n.exitCode),t.redirections,s);throw n}}var f_=[`!`,`[[`,`]]`,`case`,`do`,`done`,`elif`,`else`,`esac`,`fi`,`for`,`function`,`if`,`in`,`then`,`time`,`until`,`while`,`{`,`}`],p_=`.,:,[,alias,bg,bind,break,builtin,caller,cd,command,compgen,complete,compopt,continue,declare,dirs,disown,echo,enable,eval,exec,exit,export,false,fc,fg,getopts,hash,help,history,jobs,kill,let,local,logout,mapfile,popd,printf,pushd,pwd,read,readarray,readonly,return,set,shift,shopt,source,suspend,test,times,trap,true,type,typeset,ulimit,umask,unalias,unset,wait`.split(`,`),m_=`autocd.assoc_expand_once.cdable_vars.cdspell.checkhash.checkjobs.checkwinsize.cmdhist.compat31.compat32.compat40.compat41.compat42.compat43.compat44.complete_fullquote.direxpand.dirspell.dotglob.execfail.expand_aliases.extdebug.extglob.extquote.failglob.force_fignore.globasciiranges.globstar.gnu_errfmt.histappend.histreedit.histverify.hostcomplete.huponexit.inherit_errexit.interactive_comments.lastpipe.lithist.localvar_inherit.localvar_unset.login_shell.mailwarn.no_empty_cmd_completion.nocaseglob.nocasematch.nullglob.progcomp.progcomp_alias.promptvars.restricted_shell.shift_verbose.sourcepath.xpg_echo`.split(`.`),h_=p_;async function g_(e,t){let n=[],r=null,i=``,a=``,o=null,s=!1,c=!1,l=!1,u=null,d=null,f=null,p=[],m=[`alias`,`arrayvar`,`binding`,`builtin`,`command`,`directory`,`disabled`,`enabled`,`export`,`file`,`function`,`group`,`helptopic`,`hostname`,`job`,`keyword`,`running`,`service`,`setopt`,`shopt`,`signal`,`stopped`,`user`,`variable`];for(let e=0;e<t.length;e++){let o=t[e];if(o===`-v`)n.push(`variable`);else if(o===`-e`)n.push(`export`);else if(o===`-f`)n.push(`file`);else if(o===`-d`)n.push(`directory`);else if(o===`-k`)n.push(`keyword`);else if(o===`-A`){if(e++,e>=t.length)return X(`compgen: -A: option requires an argument
|
|
245
248
|
`,2);let r=t[e];if(!m.includes(r))return X(`compgen: ${r}: invalid action name
|
|
246
249
|
`,2);n.push(r)}else if(o===`-W`){if(e++,e>=t.length)return X(`compgen: -W: option requires an argument
|
|
247
250
|
`,2);r=t[e]}else if(o===`-P`){if(e++,e>=t.length)return X(`compgen: -P: option requires an argument
|
|
@@ -252,96 +255,96 @@ superseded_by: <path-to-new-canonical-article>.md
|
|
|
252
255
|
`,2);d=t[e]}else if(o===`-C`){if(e++,e>=t.length)return X(`compgen: -C: option requires an argument
|
|
253
256
|
`,2);f=t[e]}else if(o===`-X`){if(e++,e>=t.length)return X(`compgen: -X: option requires an argument
|
|
254
257
|
`,2);u=t[e]}else if(o===`-G`){if(e++,e>=t.length)return X(`compgen: -G: option requires an argument
|
|
255
|
-
`,2)}else if(o===`--`){p.push(...t.slice(e+1));break}else o.startsWith(`-`)||p.push(o)}o=p[0]??null;let h=[];if(c){let t=await
|
|
258
|
+
`,2)}else if(o===`--`){p.push(...t.slice(e+1));break}else o.startsWith(`-`)||p.push(o)}o=p[0]??null;let h=[];if(c){let t=await T_(e,o);h.push(...t)}if(l){let t=await E_(e,o);h.push(...t)}for(let t of n)if(t===`variable`){let t=__(e,o);h.push(...t)}else if(t===`export`){let t=v_(e,o);h.push(...t)}else if(t===`function`){let t=y_(e,o);h.push(...t)}else if(t===`builtin`){let e=b_(o);h.push(...e)}else if(t===`keyword`){let e=x_(o);h.push(...e)}else if(t===`alias`){let t=S_(e,o);h.push(...t)}else if(t===`shopt`){let e=C_(o);h.push(...e)}else if(t===`helptopic`){let e=w_(o);h.push(...e)}else if(t===`directory`){let t=await T_(e,o);h.push(...t)}else if(t===`file`){let t=await E_(e,o);h.push(...t)}else if(t===`user`){let e=D_(o);h.push(...e)}else if(t===`command`){let t=await O_(e,o);h.push(...t)}if(r!==null)try{let t=A_(e,await k_(e,r));for(let e of t)(o===null||e.startsWith(o))&&h.push(e)}catch{return Z(``,``,1)}if(s){let t=await T_(e,o);for(let e of t)h.includes(e)||h.push(e)}let g=``;if(d!==null){let t=e.state.functions.get(d);if(t){let n=new Map;n.set(`COMP_WORDS__length`,e.state.env.get(`COMP_WORDS__length`)),e.state.env.set(`COMP_WORDS__length`,`0`),n.set(`COMP_CWORD`,e.state.env.get(`COMP_CWORD`)),e.state.env.set(`COMP_CWORD`,`-1`),n.set(`COMP_LINE`,e.state.env.get(`COMP_LINE`)),e.state.env.set(`COMP_LINE`,``),n.set(`COMP_POINT`,e.state.env.get(`COMP_POINT`)),e.state.env.set(`COMP_POINT`,`0`);let r=new Map;for(let t of e.state.env.keys())(t===`COMPREPLY`||t.startsWith(`COMPREPLY_`)||t===`COMPREPLY__length`)&&(r.set(t,e.state.env.get(t)),e.state.env.delete(t));let i=[`compgen`,p[0]??``,``];try{let a=await d_(e,t,i,``);if(a.exitCode!==0)return j_(e,n),j_(e,r),Z(``,a.stderr,1);g=a.stdout;let o=M_(e);h.push(...o)}catch{return j_(e,n),j_(e,r),Z(``,``,1)}j_(e,n),j_(e,r)}}if(f!==null)try{let t=_t(f),n=await e.executeScript(t);if(n.exitCode!==0)return Z(``,n.stderr,n.exitCode);if(n.stdout){let e=n.stdout.split(`
|
|
256
259
|
`);for(let t of e)t.length>0&&h.push(t)}}catch(e){if(e.name===`ParseException`)return X(`compgen: -C: ${e.message}
|
|
257
|
-
`,2);throw e}let _=h;if(u!==null){let e=u.startsWith(`!`),t=e?u.slice(1):u;_=h.filter(n=>{let r=
|
|
260
|
+
`,2);throw e}let _=h;if(u!==null){let e=u.startsWith(`!`),t=e?u.slice(1):u;_=h.filter(n=>{let r=Dg(n,t,!1,!0);return e?r:!r})}if(_.length===0&&o!==null)return Z(g,``,1);let v=_.map(e=>`${i}${e}${a}`).join(`
|
|
258
261
|
`);return Y(g+(v?`${v}
|
|
259
|
-
`:``))}function
|
|
260
|
-
`;if(n.length===0)return[t];let r=new Set(n.split(``)),i=[],a=``,o=0;for(;o<t.length;){let e=t[o];if(e===`\\`&&o+1<t.length){let e=t[o+1];a+=e,o+=2}else r.has(e)?(a.length>0&&(i.push(a),a=``),o++):(a+=e,o++)}return a.length>0&&i.push(a),i}function
|
|
262
|
+
`:``))}function __(e,t){let n=new Set;for(let t of e.state.env.keys()){if(t.includes(`_`)&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(t)||t.endsWith(`__length`))continue;let r=t.split(`_`)[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?n.add(t):r&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&e.state.env.has(`${r}__length`)&&n.add(r)}let r=Array.from(n);return t!==null&&(r=r.filter(e=>e.startsWith(t))),r.sort()}function v_(e,t){let n=e.state.exportedVars??new Set,r=Array.from(n);return t!==null&&(r=r.filter(e=>e.startsWith(t))),r=r.filter(t=>t.includes(`_`)&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(t)||t.endsWith(`__length`)?!1:e.state.env.has(t)),r.sort()}function y_(e,t){let n=Array.from(e.state.functions.keys());return t!==null&&(n=n.filter(e=>e.startsWith(t))),n.sort()}function b_(e){let t=[...p_];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}function x_(e){let t=[...f_];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}function S_(e,t){let n=[];for(let t of e.state.env.keys())if(t.startsWith(`BASH_ALIAS_`)){let e=t.slice(11);n.push(e)}let r=n;return t!==null&&(r=r.filter(e=>e.startsWith(t))),r.sort()}function C_(e){let t=[...m_];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}function w_(e){let t=[...h_];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}async function T_(e,t){let n=[];try{let r=e.state.cwd,i=t??``;if(t){let n=t.lastIndexOf(`/`);if(n!==-1){let a=t.slice(0,n)||`/`;i=t.slice(n+1),r=a.startsWith(`/`)?a:`${e.state.cwd}/${a}`}}let a=await e.fs.readdir(r);for(let o of a){let a=`${r}/${o}`;try{if((await e.fs.stat(a)).isDirectory&&(!i||o.startsWith(i)))if(t?.includes(`/`)){let e=t.lastIndexOf(`/`),r=t.slice(0,e+1);n.push(r+o)}else n.push(o)}catch{}}}catch{}return n.sort()}async function E_(e,t){let n=[];try{let r=e.state.cwd,i=t??``;if(t){let n=t.lastIndexOf(`/`);if(n!==-1){let a=t.slice(0,n)||`/`;i=t.slice(n+1),r=a.startsWith(`/`)?a:`${e.state.cwd}/${a}`}}let a=await e.fs.readdir(r);for(let e of a)if(!i||e.startsWith(i))if(t?.includes(`/`)){let r=t.lastIndexOf(`/`),i=t.slice(0,r+1);n.push(i+e)}else n.push(e)}catch{}return n.sort()}function D_(e){return[`root`,`nobody`]}async function O_(e,t){let n=new Set;for(let e of p_)n.add(e);for(let t of e.state.functions.keys())n.add(t);for(let t of e.state.env.keys())t.startsWith(`BASH_ALIAS_`)&&n.add(t.slice(11));for(let e of f_)n.add(e);let r=e.state.env.get(`PATH`)??`/usr/bin:/bin`;for(let t of r.split(`:`))if(t)try{let r=await e.fs.readdir(t);for(let e of r)n.add(e)}catch{}let i=Array.from(n);return t!==null&&(i=i.filter(e=>e.startsWith(t))),i.sort()}async function k_(e,t){return await E(e,new Vt().parseWordFromString(t,!1,!1))}function A_(e,t){let n=e.state.env.get(`IFS`)??`
|
|
263
|
+
`;if(n.length===0)return[t];let r=new Set(n.split(``)),i=[],a=``,o=0;for(;o<t.length;){let e=t[o];if(e===`\\`&&o+1<t.length){let e=t[o+1];a+=e,o+=2}else r.has(e)?(a.length>0&&(i.push(a),a=``),o++):(a+=e,o++)}return a.length>0&&i.push(a),i}function j_(e,t){for(let[n,r]of t)r===void 0?e.state.env.delete(n):e.state.env.set(n,r)}function M_(e){let t=[];if(e.state.env.get(`COMPREPLY__length`)!==void 0){let n=Et(e,`COMPREPLY`);for(let[,e]of n)t.push(e)}else{let n=e.state.env.get(`COMPREPLY`);n!==void 0&&t.push(n)}return t}var N_=[`bashdefault`,`default`,`dirnames`,`filenames`,`noquote`,`nosort`,`nospace`,`plusdirs`];function P_(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,i=!1,a,o,s,c=[],l=[],u=[];for(let e=0;e<t.length;e++){let d=t[e];if(d===`-p`)n=!0;else if(d===`-r`)r=!0;else if(d===`-D`)i=!0;else if(d===`-W`){if(e++,e>=t.length)return X(`complete: -W: option requires an argument
|
|
261
264
|
`,2);a=t[e]}else if(d===`-F`){if(e++,e>=t.length)return X(`complete: -F: option requires an argument
|
|
262
265
|
`,2);o=t[e]}else if(d===`-o`){if(e++,e>=t.length)return X(`complete: -o: option requires an argument
|
|
263
|
-
`,2);let n=t[e];if(!
|
|
266
|
+
`,2);let n=t[e];if(!N_.includes(n))return X(`complete: ${n}: invalid option name
|
|
264
267
|
`,2);c.push(n)}else if(d===`-A`){if(e++,e>=t.length)return X(`complete: -A: option requires an argument
|
|
265
268
|
`,2);l.push(t[e])}else if(d===`-C`){if(e++,e>=t.length)return X(`complete: -C: option requires an argument
|
|
266
269
|
`,2);s=t[e]}else if(d===`-G`){if(e++,e>=t.length)return X(`complete: -G: option requires an argument
|
|
267
270
|
`,2)}else if(d===`-P`){if(e++,e>=t.length)return X(`complete: -P: option requires an argument
|
|
268
271
|
`,2)}else if(d===`-S`){if(e++,e>=t.length)return X(`complete: -S: option requires an argument
|
|
269
272
|
`,2)}else if(d===`-X`){if(e++,e>=t.length)return X(`complete: -X: option requires an argument
|
|
270
|
-
`,2)}else if(d===`--`){u.push(...t.slice(e+1));break}else d.startsWith(`-`)||u.push(d)}if(r){if(u.length===0)return e.state.completionSpecs.clear(),Y(``);for(let t of u)e.state.completionSpecs.delete(t);return Y(``)}if(n)return u.length===0?
|
|
271
|
-
`,2);if(i){let t={isDefault:!0};return a!==void 0&&(t.wordlist=a),o!==void 0&&(t.function=o),s!==void 0&&(t.command=s),c.length>0&&(t.options=c),l.length>0&&(t.actions=l),e.state.completionSpecs.set(`__default__`,t),Y(``)}for(let t of u){let n=Object.create(null);a!==void 0&&(n.wordlist=a),o!==void 0&&(n.function=o),s!==void 0&&(n.command=s),c.length>0&&(n.options=c),l.length>0&&(n.actions=l),e.state.completionSpecs.set(t,n)}return Y(``)}function
|
|
273
|
+
`,2)}else if(d===`--`){u.push(...t.slice(e+1));break}else d.startsWith(`-`)||u.push(d)}if(r){if(u.length===0)return e.state.completionSpecs.clear(),Y(``);for(let t of u)e.state.completionSpecs.delete(t);return Y(``)}if(n)return u.length===0?F_(e):F_(e,u);if(t.length===0||u.length===0&&!a&&!o&&!s&&c.length===0&&l.length===0&&!i)return F_(e);if(o&&u.length===0&&!i)return X(`complete: -F: option requires a command name
|
|
274
|
+
`,2);if(i){let t={isDefault:!0};return a!==void 0&&(t.wordlist=a),o!==void 0&&(t.function=o),s!==void 0&&(t.command=s),c.length>0&&(t.options=c),l.length>0&&(t.actions=l),e.state.completionSpecs.set(`__default__`,t),Y(``)}for(let t of u){let n=Object.create(null);a!==void 0&&(n.wordlist=a),o!==void 0&&(n.function=o),s!==void 0&&(n.command=s),c.length>0&&(n.options=c),l.length>0&&(n.actions=l),e.state.completionSpecs.set(t,n)}return Y(``)}function F_(e,t){let n=e.state.completionSpecs;if(!n||n.size===0){if(t&&t.length>0){let e=``;for(let n of t)e+=`complete: ${n}: no completion specification
|
|
272
275
|
`;return Z(``,e,1)}return Y(``)}let r=[],i=t||Array.from(n.keys());for(let e of i){if(e===`__default__`)continue;let i=n.get(e);if(!i){if(t)return Z(r.join(`
|
|
273
276
|
`)+(r.length>0?`
|
|
274
277
|
`:``),`complete: ${e}: no completion specification
|
|
275
278
|
`,1);continue}let a=`complete`;if(i.options)for(let e of i.options)a+=` -o ${e}`;if(i.actions)for(let e of i.actions)a+=` -A ${e}`;i.wordlist!==void 0&&(i.wordlist.includes(` `)||i.wordlist.includes(`'`)?a+=` -W '${i.wordlist}'`:a+=` -W ${i.wordlist}`),i.function!==void 0&&(a+=` -F ${i.function}`),i.isDefault&&(a+=` -D`),a+=` ${e}`,r.push(a)}return r.length===0?Y(``):Y(`${r.join(`
|
|
276
279
|
`)}
|
|
277
|
-
`)}var
|
|
278
|
-
`,2);let n=t[e];if(!
|
|
280
|
+
`)}var I_=[`bashdefault`,`default`,`dirnames`,`filenames`,`noquote`,`nosort`,`nospace`,`plusdirs`];function L_(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,i=[],a=[],o=[];for(let e=0;e<t.length;e++){let s=t[e];if(s===`-D`)n=!0;else if(s===`-E`)r=!0;else if(s===`-o`){if(e++,e>=t.length)return X(`compopt: -o: option requires an argument
|
|
281
|
+
`,2);let n=t[e];if(!I_.includes(n))return X(`compopt: ${n}: invalid option name
|
|
279
282
|
`,2);i.push(n)}else if(s===`+o`){if(e++,e>=t.length)return X(`compopt: +o: option requires an argument
|
|
280
|
-
`,2);let n=t[e];if(!
|
|
283
|
+
`,2);let n=t[e];if(!I_.includes(n))return X(`compopt: ${n}: invalid option name
|
|
281
284
|
`,2);a.push(n)}else if(s===`--`){o.push(...t.slice(e+1));break}else !s.startsWith(`-`)&&!s.startsWith(`+`)&&o.push(s)}if(n){let t=e.state.completionSpecs.get(`__default__`)??{isDefault:!0},n=new Set(t.options??[]);for(let e of i)n.add(e);for(let e of a)n.delete(e);return t.options=n.size>0?Array.from(n):void 0,e.state.completionSpecs.set(`__default__`,t),Y(``)}if(r){let t=e.state.completionSpecs.get(`__empty__`)??{},n=new Set(t.options??[]);for(let e of i)n.add(e);for(let e of a)n.delete(e);return t.options=n.size>0?Array.from(n):void 0,e.state.completionSpecs.set(`__empty__`,t),Y(``)}if(o.length>0){for(let t of o){let n=e.state.completionSpecs.get(t)??{},r=new Set(n.options??[]);for(let e of i)r.add(e);for(let e of a)r.delete(e);n.options=r.size>0?Array.from(r):void 0,e.state.completionSpecs.set(t,n)}return Y(``)}return X(`compopt: not currently executing completion function
|
|
282
|
-
`,1)}function
|
|
283
|
-
`);let n=1;if(t.length>0){let e=Number.parseInt(t[0],10);if(Number.isNaN(e)||e<1)throw new
|
|
284
|
-
`);n=e}throw new
|
|
285
|
-
`;else{let r=t.map(t=>`['${t}']=${
|
|
286
|
-
`}continue}let o=
|
|
285
|
+
`,1)}function R_(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new rt;return J}if(t.length>1)throw new et(1,``,`bash: continue: too many arguments
|
|
286
|
+
`);let n=1;if(t.length>0){let e=Number.parseInt(t[0],10);if(Number.isNaN(e)||e<1)throw new et(1,``,`bash: continue: ${t[0]}: numeric argument required
|
|
287
|
+
`);n=e}throw new nt(n)}function z_(e,t){let n=e.state.env.get(`HOME`)||`/home/user`;return t.split(`:`).map(e=>e===`~`?n:e===`~root`?`/root`:e.startsWith(`~/`)?n+e.slice(1):e.startsWith(`~root/`)?`/root${e.slice(5)}`:e).join(`:`)}function B_(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!0}return!1}function V_(e){let t=`$'`;for(let n=0;n<e.length;n++){let r=e[n],i=e.charCodeAt(n);i===7?t+=`\\a`:i===8?t+=`\\b`:i===9?t+=`\\t`:i===10?t+=`\\n`:i===11?t+=`\\v`:i===12?t+=`\\f`:i===13?t+=`\\r`:i===27?t+=`\\e`:i===39?t+=`\\'`:i===92?t+=`\\\\`:i<32||i===127?t+=`\\${i.toString(8).padStart(3,`0`)}`:t+=r}return t+=`'`,t}function H_(e){return B_(e)?V_(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function U_(e){return B_(e)?V_(e):`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function W_(e){return B_(e)?V_(e):`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function G_(e,t){let n=``;return e.state.integerVars?.has(t)&&(n+=`i`),e.state.lowercaseVars?.has(t)&&(n+=`l`),wt(e,t)&&(n+=`n`),e.state.readonlyVars?.has(t)&&(n+=`r`),e.state.uppercaseVars?.has(t)&&(n+=`u`),e.state.exportedVars?.has(t)&&(n+=`x`),n===``?`--`:`-${n}`}function K_(e){return e===``?`''`:/[\s'\\]/.test(e)?`'${e.replace(/'/g,`'\\''`)}'`:e}function q_(e,t){let n=``,r=``,i=!1;for(let a of t){let t=G_(e,a);if(e.state.associativeArrays?.has(a)){let t=ot(e,a);if(t.length===0)n+=`declare -A ${a}=()
|
|
288
|
+
`;else{let r=t.map(t=>`['${t}']=${K_(e.state.env.get(`${a}_${t}`)??``)}`);n+=`declare -A ${a}=(${r.join(` `)})
|
|
289
|
+
`}continue}let o=gt(e,a);if(o.length>0){let t=o.map(t=>`[${t}]=${U_(e.state.env.get(`${a}_${t}`)??``)}`);n+=`declare -a ${a}=(${t.join(` `)})
|
|
287
290
|
`;continue}if(e.state.env.has(`${a}__length`)){n+=`declare -a ${a}=()
|
|
288
|
-
`;continue}let s=e.state.env.get(a);if(s!==void 0)n+=`declare ${t} ${a}=${
|
|
291
|
+
`;continue}let s=e.state.env.get(a);if(s!==void 0)n+=`declare ${t} ${a}=${W_(s)}
|
|
289
292
|
`;else{let o=e.state.declaredVars?.has(a),s=e.state.localVarDepth?.has(a);o||s?n+=`declare ${t} ${a}
|
|
290
293
|
`:(r+=`bash: declare: ${a}: not found
|
|
291
|
-
`,i=!0)}}return Z(n,r,i?1:0)}function
|
|
292
|
-
`;else{let r=n.map(n=>`['${n}']=${
|
|
293
|
-
`}continue}if(d.length>0){let n=d.map(n=>`[${n}]=${
|
|
294
|
+
`,i=!0)}}return Z(n,r,i?1:0)}function J_(e,t){let{filterExport:n,filterReadonly:r,filterNameref:i,filterIndexedArray:a,filterAssocArray:o}=t,s=n||r||i||a||o,c=``,l=new Set;for(let t of e.state.env.keys()){if(t.startsWith(`BASH_`))continue;if(t.endsWith(`__length`)){let e=t.slice(0,-8);l.add(e);continue}let n=t.lastIndexOf(`_`);if(n>0){let r=t.slice(0,n),i=t.slice(n+1);if(/^\d+$/.test(i)||e.state.associativeArrays?.has(r)){l.add(r);continue}}l.add(t)}if(e.state.localVarDepth)for(let t of e.state.localVarDepth.keys())l.add(t);if(e.state.associativeArrays)for(let t of e.state.associativeArrays)l.add(t);let u=Array.from(l).sort();for(let t of u){let l=G_(e,t),u=e.state.associativeArrays?.has(t),d=gt(e,t),f=!u&&(d.length>0||e.state.env.has(`${t}__length`));if(s&&(o&&!u||a&&!f||n&&!e.state.exportedVars?.has(t)||r&&!e.state.readonlyVars?.has(t)||i&&!wt(e,t)))continue;if(u){let n=ot(e,t);if(n.length===0)c+=`declare -A ${t}=()
|
|
295
|
+
`;else{let r=n.map(n=>`['${n}']=${K_(e.state.env.get(`${t}_${n}`)??``)}`);c+=`declare -A ${t}=(${r.join(` `)})
|
|
296
|
+
`}continue}if(d.length>0){let n=d.map(n=>`[${n}]=${U_(e.state.env.get(`${t}_${n}`)??``)}`);c+=`declare -a ${t}=(${n.join(` `)})
|
|
294
297
|
`;continue}if(e.state.env.has(`${t}__length`)){c+=`declare -a ${t}=()
|
|
295
|
-
`;continue}let p=e.state.env.get(t);p!==void 0&&(c+=`declare ${l} ${t}=${
|
|
296
|
-
`)}return Y(c)}function
|
|
297
|
-
`;else{let i=n.map(t=>`['${t}']=${
|
|
298
|
-
`}}return Y(t)}function
|
|
299
|
-
`;else{let i=r.map(t=>`[${t}]=${
|
|
300
|
-
`}}return Y(t)}function
|
|
301
|
-
`)}return Y(t)}function
|
|
298
|
+
`;continue}let p=e.state.env.get(t);p!==void 0&&(c+=`declare ${l} ${t}=${W_(p)}
|
|
299
|
+
`)}return Y(c)}function Y_(e){let t=``,n=Array.from(e.state.associativeArrays??[]).sort();for(let r of n){let n=ot(e,r);if(n.length===0)t+=`declare -A ${r}=()
|
|
300
|
+
`;else{let i=n.map(t=>`['${t}']=${K_(e.state.env.get(`${r}_${t}`)??``)}`);t+=`declare -A ${r}=(${i.join(` `)})
|
|
301
|
+
`}}return Y(t)}function X_(e){let t=``,n=new Set;for(let t of e.state.env.keys()){if(t.startsWith(`BASH_`))continue;if(t.endsWith(`__length`)){let r=t.slice(0,-8);e.state.associativeArrays?.has(r)||n.add(r);continue}let r=t.lastIndexOf(`_`);if(r>0){let i=t.slice(0,r),a=t.slice(r+1);/^\d+$/.test(a)&&(e.state.associativeArrays?.has(i)||n.add(i))}}let r=Array.from(n).sort();for(let n of r){let r=gt(e,n);if(r.length===0)t+=`declare -a ${n}=()
|
|
302
|
+
`;else{let i=r.map(t=>`[${t}]=${U_(e.state.env.get(`${n}_${t}`)??``)}`);t+=`declare -a ${n}=(${i.join(` `)})
|
|
303
|
+
`}}return Y(t)}function Z_(e){let t=``,n=new Set;for(let t of e.state.env.keys()){if(t.startsWith(`BASH_`))continue;if(t.endsWith(`__length`)){let e=t.slice(0,-8);n.add(e);continue}let r=t.lastIndexOf(`_`);if(r>0){let i=t.slice(0,r),a=t.slice(r+1);if(/^\d+$/.test(a)||e.state.associativeArrays?.has(i)){n.add(i);continue}}n.add(t)}let r=Array.from(n).sort();for(let n of r){if(e.state.associativeArrays?.has(n)||gt(e,n).length>0||e.state.env.has(`${n}__length`))continue;let r=e.state.env.get(n);r!==void 0&&(t+=`${n}=${H_(r)}
|
|
304
|
+
`)}return Y(t)}function Q_(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function $_(e,t){return e.state.integerVars?.has(t)??!1}function ev(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function tv(e,t){return e.state.lowercaseVars?.has(t)??!1}function nv(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function rv(e,t){return e.state.uppercaseVars?.has(t)??!1}function iv(e,t,n){return tv(e,t)?n.toLowerCase():rv(e,t)?n.toUpperCase():n}async function av(e,t){try{let n=await It(e,Tt(new Vt,t).expression);return String(n)}catch{return`0`}}function ov(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let n=t[0],r=n.length;if(e[r]!==`[`)return null;let i=0,a=r+1;for(;r<e.length;r++)if(e[r]===`[`)i++;else if(e[r]===`]`&&(i--,i===0))break;if(i!==0)return null;let o=e.slice(a,r);return r++,e[r]===`=`?(r++,{name:n,indexExpr:o,value:e.slice(r)}):null}async function sv(e,t){let n=!1,r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=!1,d=!1,f=!1,p=!1,m=!1,h=!1,g=!1,_=[];for(let e=0;e<t.length;e++){let v=t[e];if(v===`-a`)n=!0;else if(v===`-A`)r=!0;else if(v===`-r`)i=!0;else if(v===`-x`)a=!0;else if(v===`-p`)o=!0;else if(v===`-n`)s=!0;else if(v===`+n`)c=!0;else if(v===`+a`)l=!0;else if(v===`+x`)u=!0;else if(v===`--`){_.push(...t.slice(e+1));break}else if(v.startsWith(`+`)){for(let e of v.slice(1))if(e===`n`)c=!0;else if(e===`a`)l=!0;else if(e===`x`)u=!0;else if(e!==`r`&&e!==`i`&&!(e===`f`||e===`F`))return Z(``,`bash: typeset: +${e}: invalid option
|
|
302
305
|
`,2)}else if(v===`-i`)d=!0;else if(v===`-l`)f=!0;else if(v===`-u`)p=!0;else if(v===`-f`)m=!0;else if(v===`-F`)h=!0;else if(v===`-g`)g=!0;else if(v.startsWith(`-`))for(let e of v.slice(1))if(e===`a`)n=!0;else if(e===`A`)r=!0;else if(e===`r`)i=!0;else if(e===`x`)a=!0;else if(e===`p`)o=!0;else if(e===`n`)s=!0;else if(e===`i`)d=!0;else if(e===`l`)f=!0;else if(e===`u`)p=!0;else if(e===`f`)m=!0;else if(e===`F`)h=!0;else if(e===`g`)g=!0;else return Z(``,`bash: typeset: -${e}: invalid option
|
|
303
|
-
`,2);else _.push(v)}let v=e.state.localScopes.length>0&&!g,y=t=>{if(!v)return;let n=e.state.localScopes[e.state.localScopes.length-1];n.has(t)||n.set(t,e.state.env.get(t))},b=t=>{if(!v)return;let n=e.state.localScopes[e.state.localScopes.length-1];n.has(t)||n.set(t,e.state.env.get(t));let r=`${t}_`;for(let t of e.state.env.keys())t.startsWith(r)&&!t.includes(`__`)&&(n.has(t)||n.set(t,e.state.env.get(t)));let i=`${t}__length`;e.state.env.has(i)&&!n.has(i)&&n.set(i,e.state.env.get(i))},x=t=>{v&&
|
|
306
|
+
`,2);else _.push(v)}let v=e.state.localScopes.length>0&&!g,y=t=>{if(!v)return;let n=e.state.localScopes[e.state.localScopes.length-1];n.has(t)||n.set(t,e.state.env.get(t))},b=t=>{if(!v)return;let n=e.state.localScopes[e.state.localScopes.length-1];n.has(t)||n.set(t,e.state.env.get(t));let r=`${t}_`;for(let t of e.state.env.keys())t.startsWith(r)&&!t.includes(`__`)&&(n.has(t)||n.set(t,e.state.env.get(t)));let i=`${t}__length`;e.state.env.has(i)&&!n.has(i)&&n.set(i,e.state.env.get(i))},x=t=>{v&&Gg(e,t)};if(h){if(_.length===0){let t=Array.from(e.state.functions.keys()).sort(),n=``;for(let e of t)n+=`declare -f ${e}
|
|
304
307
|
`;return Y(n)}let t=!0,n=``;for(let r of _)e.state.functions.has(r)?n+=`${r}
|
|
305
308
|
`:t=!1;return Z(n,``,t?0:1)}if(m){if(_.length===0){let t=``,n=Array.from(e.state.functions.keys()).sort();for(let e of n)t+=`${e} ()
|
|
306
309
|
{
|
|
307
310
|
# function body
|
|
308
311
|
}
|
|
309
|
-
`;return Y(t)}let t=!0;for(let n of _)e.state.functions.has(n)||(t=!1);return Z(``,``,t?0:1)}if(o&&_.length>0)return
|
|
310
|
-
`,
|
|
311
|
-
`,
|
|
312
|
-
`,
|
|
313
|
-
`,
|
|
314
|
-
`,
|
|
315
|
-
`,
|
|
316
|
-
`}}return Y(t)}for(let t of n){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(n){let t=n[1],r=n[2],i=
|
|
312
|
+
`;return Y(t)}let t=!0;for(let n of _)e.state.functions.has(n)||(t=!1);return Z(``,``,t?0:1)}if(o&&_.length>0)return q_(e,_);if(o&&_.length===0)return J_(e,{filterExport:a,filterReadonly:i,filterNameref:s,filterIndexedArray:n,filterAssocArray:r});if(_.length===0&&r&&!o)return Y_(e);if(_.length===0&&n&&!o)return X_(e);if(_.length===0&&!o)return Z_(e);let S=``,ee=0;for(let t of _){let o=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(o&&!l){let t=o[1],s=o[2];if(r&>(e,t).length>0){S+=`bash: declare: ${t}: cannot convert indexed to associative array
|
|
313
|
+
`,ee=1;continue}if((n||!r&&!n)&&e.state.associativeArrays?.has(t)){S+=`bash: declare: ${t}: cannot convert associative to indexed array
|
|
314
|
+
`,ee=1;continue}if(b(t),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(t)),Lt(e,t),e.state.env.delete(t),e.state.env.delete(`${t}__length`),r&&s.includes(`[`)){let n=Vg(s);for(let[r,i]of n){let n=z_(e,i);e.state.env.set(`${t}_${r}`,n)}}else if(r){let n=Bg(s);for(let r=0;r<n.length;r+=2){let i=n[r],a=r+1<n.length?z_(e,n[r+1]):``;e.state.env.set(`${t}_${i}`,a)}}else{let n=Bg(s);if(n.some(e=>/^\[[^\]]+\]=/.test(e))){let r=0;for(let i of n){let n=i.match(/^\[([^\]]+)\]=(.*)$/);if(n){let i=n[1],a=n[2],o=z_(e,a),s;if(/^-?\d+$/.test(i))s=Number.parseInt(i,10);else try{s=await It(e,Tt(new Vt,i).expression)}catch{s=0}e.state.env.set(`${t}_${s}`,o),r=s+1}else{let n=z_(e,i);e.state.env.set(`${t}_${r}`,n),r++}}}else{for(let r=0;r<n.length;r++)e.state.env.set(`${t}_${r}`,n[r]);e.state.env.set(`${t}__length`,String(n.length))}}x(t),i&&vt(e,t),a&&ht(e,t);continue}if(c&&(pt(e,t.includes(`=`)?t.slice(0,t.indexOf(`=`)):t),!t.includes(`=`))||u&&(jt(e,t.includes(`=`)?t.slice(0,t.indexOf(`=`)):t),!t.includes(`=`)))continue;let m=ov(t);if(m){let{name:t,indexExpr:n,value:r}=m,o=lt(e,t);if(o)return o;b(t);let s;try{s=await It(e,Tt(new Vt,n).expression)}catch{let e=parseInt(n,10);s=Number.isNaN(e)?0:e}e.state.env.set(`${t}_${s}`,r);let c=parseInt(e.state.env.get(`${t}__length`)??`0`,10);s>=c&&e.state.env.set(`${t}__length`,String(s+1)),x(t),i&&vt(e,t),a&&ht(e,t);continue}let h=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(h&&!l){let t=h[1],n=h[2],r=lt(e,t);if(r)return r;b(t);let o=Bg(n);if(e.state.associativeArrays?.has(t)){let r=Vg(n);for(let[n,i]of r){let r=z_(e,i);e.state.env.set(`${t}_${n}`,r)}}else{let n=gt(e,t),r=0,i=e.state.env.get(t);n.length===0&&i!==void 0?(e.state.env.set(`${t}_0`,i),e.state.env.delete(t),r=1):n.length>0&&(r=Math.max(...n)+1);for(let n=0;n<o.length;n++)e.state.env.set(`${t}_${r+n}`,z_(e,o[n]));let a=r+o.length;e.state.env.set(`${t}__length`,String(a))}x(t),i&&vt(e,t),a&&ht(e,t);continue}let g=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(g){let t=g[1],n=z_(e,g[2]),r=lt(e,t);if(r)return r;y(t),d&&Q_(e,t),f&&ev(e,t),p&&nv(e,t);let o=gt(e,t).length>0||e.state.associativeArrays?.has(t);if($_(e,t)){let r=e.state.env.get(t)??`0`,i=parseInt(r,10)||0,a=parseInt(await av(e,n),10)||0;n=String(i+a),e.state.env.set(t,n)}else if(o){n=iv(e,t,n);let r=`${t}_0`,i=e.state.env.get(r)??``;e.state.env.set(r,i+n)}else{n=iv(e,t,n);let r=e.state.env.get(t)??``;e.state.env.set(t,r+n)}x(t),i&&vt(e,t),a&&ht(e,t),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(t));continue}if(t.includes(`=`)){let n=t.indexOf(`=`),r=t.slice(0,n),o=t.slice(n+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)){S+=`bash: typeset: \`${r}': not a valid identifier
|
|
315
|
+
`,ee=1;continue}let c=lt(e,r);if(c)return c;if(y(r),s){if(o!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(o)){S+=`bash: declare: \`${o}': invalid variable name for name reference
|
|
316
|
+
`,ee=1;continue}e.state.env.set(r,o),Wt(e,r),o!==``&&mt(e,o)&&Ct(e,r),x(r),i&&vt(e,r),a&&ht(e,r);continue}if(d&&Q_(e,r),f&&ev(e,r),p&&nv(e,r),$_(e,r)&&(o=await av(e,o)),o=iv(e,r,o),wt(e,r)){let t=At(e,r);t&&t!==r?e.state.env.set(t,o):e.state.env.set(r,o)}else e.state.env.set(r,o);x(r),i&&vt(e,r),a&&ht(e,r),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(r))}else{let o=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){S+=`bash: typeset: \`${o}': not a valid identifier
|
|
317
|
+
`,ee=1;continue}if(n||r?b(o):y(o),s){Wt(e,o);let t=e.state.env.get(o);t!==void 0&&t!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(t)?Pt(e,o):t&&mt(e,t)&&Ct(e,o),x(o),i&&vt(e,o),a&&ht(e,o);continue}if(d&&Q_(e,o),f&&ev(e,o),p&&nv(e,o),r){if(gt(e,o).length>0){S+=`bash: declare: ${o}: cannot convert indexed to associative array
|
|
318
|
+
`,ee=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(o)}let c=Array.from(e.state.env.keys()).some(e=>e.startsWith(`${o}_`)&&!e.startsWith(`${o}__length`));!e.state.env.has(o)&&!c&&(n||r?e.state.env.set(`${o}__length`,`0`):(e.state.declaredVars??=new Set,e.state.declaredVars.add(o))),x(o),i&&vt(e,o),a&&ht(e,o)}}return Z(``,S,ee)}async function cv(e,t){let n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r!==`-a`&&r!==`-A`&&r!==`-p`)if(r===`--`){n.push(...t.slice(e+1));break}else r.startsWith(`-`)||n.push(r)}if(n.length===0){let t=``,n=Array.from(e.state.readonlyVars||[]).sort();for(let r of n){let n=e.state.env.get(r);if(n!==void 0){let e=n.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);t+=`declare -r ${r}="${e}"
|
|
319
|
+
`}}return Y(t)}for(let t of n){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(n){let t=n[1],r=n[2],i=lt(e,t);if(i)return i;let a=Bg(r);if(e.state.associativeArrays?.has(t)){let n=Vg(r);for(let[r,i]of n){let n=z_(e,i);e.state.env.set(`${t}_${r}`,n)}}else{let n=gt(e,t),r=0,i=e.state.env.get(t);n.length===0&&i!==void 0?(e.state.env.set(`${t}_0`,i),e.state.env.delete(t),r=1):n.length>0&&(r=Math.max(...n)+1);for(let n=0;n<a.length;n++)e.state.env.set(`${t}_${r+n}`,z_(e,a[n]));let o=r+a.length;e.state.env.set(`${t}__length`,String(o))}vt(e,t);continue}let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(r){let t=r[1],n=z_(e,r[2]),i=lt(e,t);if(i)return i;let a=e.state.env.get(t)??``;e.state.env.set(t,a+n),vt(e,t);continue}let i=Hg(t);if(i.value===void 0&&!i.isArray){vt(e,i.name);continue}let a=await Wg(e,i,{makeReadonly:!0});if(a)return a}return J}function lv(e){return e.state.directoryStack??=[],e.state.directoryStack}function uv(e,t){return t&&e===t?`~`:t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function dv(e){let t=e.split(`/`).filter(e=>e&&e!==`.`),n=[];for(let e of t)e===`..`?n.pop():n.push(e);return`/${n.join(`/`)}`}async function fv(e,t){let n=lv(e),r;for(let e=0;e<t.length;e++){let n=t[e];if(n===`--`){if(e+1<t.length){if(r!==void 0)return X(`bash: pushd: too many arguments
|
|
317
320
|
`,2);r=t[e+1],e++}}else{if(n.startsWith(`-`)&&n!==`-`)return X(`bash: pushd: ${n}: invalid option
|
|
318
321
|
`,2);if(r!==void 0)return X(`bash: pushd: too many arguments
|
|
319
322
|
`,2);r=n}}if(r===void 0){if(n.length<2)return X(`bash: pushd: no other directory
|
|
320
|
-
`,1);let e=n[0];n[0]=n[1],n[1]=e,r=n[0]}let i;if(r.startsWith(`/`))i=r;else if(r===`..`){let t=e.state.cwd.split(`/`).filter(e=>e);t.pop(),i=`/${t.join(`/`)}`}else i=r===`.`?e.state.cwd:r.startsWith(`~`)?(e.state.env.get(`HOME`)||`/`)+r.slice(1):`${e.state.cwd}/${r}`;i=
|
|
323
|
+
`,1);let e=n[0];n[0]=n[1],n[1]=e,r=n[0]}let i;if(r.startsWith(`/`))i=r;else if(r===`..`){let t=e.state.cwd.split(`/`).filter(e=>e);t.pop(),i=`/${t.join(`/`)}`}else i=r===`.`?e.state.cwd:r.startsWith(`~`)?(e.state.env.get(`HOME`)||`/`)+r.slice(1):`${e.state.cwd}/${r}`;i=dv(i);try{if(!(await e.fs.stat(i)).isDirectory)return X(`bash: pushd: ${r}: Not a directory
|
|
321
324
|
`,1)}catch{return X(`bash: pushd: ${r}: No such file or directory
|
|
322
|
-
`,1)}n.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=i,e.state.env.set(`PWD`,i),e.state.env.set(`OLDPWD`,e.state.previousDir);let a=e.state.env.get(`HOME`)||``;return Y(`${[i,...n].map(e=>
|
|
323
|
-
`)}function
|
|
325
|
+
`,1)}n.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=i,e.state.env.set(`PWD`,i),e.state.env.set(`OLDPWD`,e.state.previousDir);let a=e.state.env.get(`HOME`)||``;return Y(`${[i,...n].map(e=>uv(e,a)).join(` `)}
|
|
326
|
+
`)}function pv(e,t){let n=lv(e);for(let e of t)if(e!==`--`)return e.startsWith(`-`)&&e!==`-`?X(`bash: popd: ${e}: invalid option
|
|
324
327
|
`,2):X(`bash: popd: too many arguments
|
|
325
328
|
`,2);if(n.length===0)return X(`bash: popd: directory stack empty
|
|
326
329
|
`,1);let r=n.shift();if(!r)return X(`bash: popd: directory stack empty
|
|
327
|
-
`,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,e.state.env.set(`PWD`,r),e.state.env.set(`OLDPWD`,e.state.previousDir);let i=e.state.env.get(`HOME`)||``;return Y(`${[r,...n].map(e=>
|
|
328
|
-
`)}function
|
|
330
|
+
`,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,e.state.env.set(`PWD`,r),e.state.env.set(`OLDPWD`,e.state.previousDir);let i=e.state.env.get(`HOME`)||``;return Y(`${[r,...n].map(e=>uv(e,i)).join(` `)}
|
|
331
|
+
`)}function mv(e,t){let n=lv(e),r=!1,i=!1,a=!1,o=!1;for(let e of t)if(e!==`--`)if(e.startsWith(`-`))for(let t of e.slice(1))if(t===`c`)r=!0;else if(t===`l`)i=!0;else if(t===`p`)a=!0;else if(t===`v`)a=!0,o=!0;else return X(`bash: dirs: -${t}: invalid option
|
|
329
332
|
`,2);else return X(`bash: dirs: too many arguments
|
|
330
|
-
`,1);if(r)return e.state.directoryStack=[],J;let s=[e.state.cwd,...n],c=e.state.env.get(`HOME`)||``,l;return o?(l=s.map((e,t)=>` ${t} ${i?e:
|
|
333
|
+
`,1);if(r)return e.state.directoryStack=[],J;let s=[e.state.cwd,...n],c=e.state.env.get(`HOME`)||``,l;return o?(l=s.map((e,t)=>` ${t} ${i?e:uv(e,c)}`).join(`
|
|
331
334
|
`),l+=`
|
|
332
|
-
`):l=a?s.map(e=>i?e:
|
|
335
|
+
`):l=a?s.map(e=>i?e:uv(e,c)).join(`
|
|
333
336
|
`)+`
|
|
334
|
-
`:s.map(e=>i?e:
|
|
335
|
-
`,Y(l)}async function
|
|
337
|
+
`:s.map(e=>i?e:uv(e,c)).join(` `)+`
|
|
338
|
+
`,Y(l)}async function hv(e,t,n){let r=t;if(r.length>0){let e=r[0];if(e===`--`)r=r.slice(1);else if(e.startsWith(`-`)&&e!==`-`&&e.length>1)return X(`bash: eval: ${e}: invalid option
|
|
336
339
|
eval: usage: eval [arg ...]
|
|
337
|
-
`,2)}if(r.length===0)return J;let i=r.join(` `);if(i.trim()===``)return J;let a=e.state.groupStdin,o=n??e.state.groupStdin;o!==void 0&&(e.state.groupStdin=o);try{let t=
|
|
338
|
-
`);throw e}finally{e.state.groupStdin=a}}function
|
|
339
|
-
`,n=2):n=(i%256+256)%256}throw new
|
|
340
|
-
`}}return Y(t)}if(n){for(let t of r){let n,r;if(t.includes(`=`)){let i=t.indexOf(`=`);n=t.slice(0,i),r=
|
|
341
|
-
`,a=1;continue}if(r!==void 0)if(o){let t=e.state.env.get(n)??``;e.state.env.set(n,t+r)}else e.state.env.set(n,r);else e.state.env.has(n)||e.state.env.set(n,``);
|
|
342
|
-
`);let n=t[0],r=t[1],i=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),a=n.startsWith(`:`),o=a?n.slice(1):n,s;if(t.length>2)s=t.slice(2);else{let t=Number.parseInt(e.state.env.get(`#`)||`0`,10);s=[];for(let n=1;n<=t;n++)s.push(e.state.env.get(String(n))||``)}let c=Number.parseInt(e.state.env.get(`OPTIND`)||`1`,10);c<1&&(c=1);let l=Number.parseInt(e.state.env.get(`__GETOPTS_CHARINDEX`)||`0`,10);if(e.state.env.set(`OPTARG`,``),c>s.length)return i||e.state.env.set(r,`?`),e.state.env.set(`OPTIND`,String(s.length+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:i?2:1,stdout:``,stderr:``};let u=s[c-1];if(!u||u===`-`||!u.startsWith(`-`))return i||e.state.env.set(r,`?`),{exitCode:i?2:1,stdout:``,stderr:``};if(u===`--`)return e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),i||e.state.env.set(r,`?`),{exitCode:i?2:1,stdout:``,stderr:``};let d=l===0?1:l,f=u[d];if(!f)return e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),
|
|
340
|
+
`,2)}if(r.length===0)return J;let i=r.join(` `);if(i.trim()===``)return J;let a=e.state.groupStdin,o=n??e.state.groupStdin;o!==void 0&&(e.state.groupStdin=o);try{let t=_t(i);return await e.executeScript(t)}catch(e){if(e instanceof Ge||e instanceof nt||e instanceof Ze||e instanceof et)throw e;if(e.name===`ParseException`)return X(`bash: eval: ${e.message}
|
|
341
|
+
`);throw e}finally{e.state.groupStdin=a}}function gv(e,t){let n,r=``;if(t.length===0)n=e.state.lastExitCode;else{let e=t[0],i=Number.parseInt(e,10);e===``||Number.isNaN(i)||!/^-?\d+$/.test(e)?(r=`bash: exit: ${e}: numeric argument required
|
|
342
|
+
`,n=2):n=(i%256+256)%256}throw new et(n,``,r)}function _v(e,t){let n=!1,r=[];for(let e of t)e===`-n`?n=!0:e===`-p`||e===`--`||r.push(e);if(r.length===0&&!n){let t=``,n=e.state.exportedVars??new Set,r=Array.from(n).sort();for(let n of r){let r=e.state.env.get(n);if(r!==void 0){let e=r.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);t+=`declare -x ${n}="${e}"
|
|
343
|
+
`}}return Y(t)}if(n){for(let t of r){let n,r;if(t.includes(`=`)){let i=t.indexOf(`=`);n=t.slice(0,i),r=z_(e,t.slice(i+1)),e.state.env.set(n,r)}else n=t;jt(e,n)}return J}let i=``,a=0;for(let t of r){let n,r,o=!1,s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(s)n=s[1],r=z_(e,s[2]),o=!0;else if(t.includes(`=`)){let i=t.indexOf(`=`);n=t.slice(0,i),r=z_(e,t.slice(i+1))}else n=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)){i+=`bash: export: \`${t}': not a valid identifier
|
|
344
|
+
`,a=1;continue}if(r!==void 0)if(o){let t=e.state.env.get(n)??``;e.state.env.set(n,t+r)}else e.state.env.set(n,r);else e.state.env.has(n)||e.state.env.set(n,``);ht(e,n)}return Z(``,i,a)}function vv(e,t){if(t.length<2)return X(`bash: getopts: usage: getopts optstring name [arg ...]
|
|
345
|
+
`);let n=t[0],r=t[1],i=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),a=n.startsWith(`:`),o=a?n.slice(1):n,s;if(t.length>2)s=t.slice(2);else{let t=Number.parseInt(e.state.env.get(`#`)||`0`,10);s=[];for(let n=1;n<=t;n++)s.push(e.state.env.get(String(n))||``)}let c=Number.parseInt(e.state.env.get(`OPTIND`)||`1`,10);c<1&&(c=1);let l=Number.parseInt(e.state.env.get(`__GETOPTS_CHARINDEX`)||`0`,10);if(e.state.env.set(`OPTARG`,``),c>s.length)return i||e.state.env.set(r,`?`),e.state.env.set(`OPTIND`,String(s.length+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:i?2:1,stdout:``,stderr:``};let u=s[c-1];if(!u||u===`-`||!u.startsWith(`-`))return i||e.state.env.set(r,`?`),{exitCode:i?2:1,stdout:``,stderr:``};if(u===`--`)return e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),i||e.state.env.set(r,`?`),{exitCode:i?2:1,stdout:``,stderr:``};let d=l===0?1:l,f=u[d];if(!f)return e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),vv(e,t);let p=o.indexOf(f);if(p===-1){let t=``;return a?e.state.env.set(`OPTARG`,f):t=`bash: illegal option -- ${f}
|
|
343
346
|
`,i||e.state.env.set(r,`?`),d+1<u.length?(e.state.env.set(`__GETOPTS_CHARINDEX`,String(d+1)),e.state.env.set(`OPTIND`,String(c))):(e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`)),{exitCode:i?2:0,stdout:``,stderr:t}}if(p+1<o.length&&o[p+1]===`:`)if(d+1<u.length)e.state.env.set(`OPTARG`,u.slice(d+1)),e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`);else{if(c>=s.length){let t=``;return a?(e.state.env.set(`OPTARG`,f),i||e.state.env.set(r,`:`)):(t=`bash: option requires an argument -- ${f}
|
|
344
|
-
`,i||e.state.env.set(r,`?`)),e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:i?2:0,stdout:``,stderr:t}}e.state.env.set(`OPTARG`,s[c]),e.state.env.set(`OPTIND`,String(c+2)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`)}else d+1<u.length?(e.state.env.set(`__GETOPTS_CHARINDEX`,String(d+1)),e.state.env.set(`OPTIND`,String(c))):(e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`));return i||e.state.env.set(r,f),{exitCode:i?2:0,stdout:``,stderr:``}}async function
|
|
347
|
+
`,i||e.state.env.set(r,`?`)),e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:i?2:0,stdout:``,stderr:t}}e.state.env.set(`OPTARG`,s[c]),e.state.env.set(`OPTIND`,String(c+2)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`)}else d+1<u.length?(e.state.env.set(`__GETOPTS_CHARINDEX`,String(d+1)),e.state.env.set(`OPTIND`,String(c))):(e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`));return i||e.state.env.set(r,f),{exitCode:i?2:0,stdout:``,stderr:``}}async function yv(e,t){e.state.hashTable||(e.state.hashTable=new Map);let n=!1,r=!1,i=!1,a=!1,o=!1,s=``,c=[],l=0;for(;l<t.length;){let e=t[l];if(e===`--`){l++,c.push(...t.slice(l));break}if(e===`-r`)n=!0,l++;else if(e===`-d`)r=!0,l++;else if(e===`-l`)i=!0,l++;else if(e===`-t`)o=!0,l++;else if(e===`-p`){if(a=!0,l++,l>=t.length)return X(`bash: hash: -p: option requires an argument
|
|
345
348
|
`,1);s=t[l],l++}else if(e.startsWith(`-`)&&e.length>1){for(let t of e.slice(1))if(t===`r`)n=!0;else if(t===`d`)r=!0;else if(t===`l`)i=!0;else if(t===`t`)o=!0;else return X(t===`p`?`bash: hash: -p: option requires an argument
|
|
346
349
|
`:`bash: hash: -${t}: invalid option
|
|
347
350
|
`,1);l++}else c.push(e),l++}if(n)return e.state.hashTable.clear(),J;if(r){if(c.length===0)return X(`bash: hash: -d: option requires an argument
|
|
@@ -357,7 +360,7 @@ eval: usage: eval [arg ...]
|
|
|
357
360
|
`;for(let[,n]of e.state.hashTable)t+=` 1 ${n}
|
|
358
361
|
`}return Y(t)}let u=!1,d=``,f=(e.state.env.get(`PATH`)||`/usr/bin:/bin`).split(`:`);for(let t of c){if(t.includes(`/`)){d+=`bash: hash: ${t}: cannot use / in name
|
|
359
362
|
`,u=!0;continue}let n=!1;for(let r of f){if(!r)continue;let i=`${r}/${t}`;if(await e.fs.exists(i)){e.state.hashTable.set(t,i),n=!0;break}}n||(d+=`bash: hash: ${t}: not found
|
|
360
|
-
`,u=!0)}return u?X(d,1):J}var
|
|
363
|
+
`,u=!0)}return u?X(d,1):J}var bv=new Map([[`:`,[`: [arguments]`,`Null command.
|
|
361
364
|
No effect; the command does nothing.
|
|
362
365
|
Exit Status:
|
|
363
366
|
Always succeeds.`]],[`.`,[`. filename [arguments]`,`Execute commands from a file in the current shell.
|
|
@@ -704,33 +707,33 @@ eval: usage: eval [arg ...]
|
|
|
704
707
|
job specification, and reports its termination status.
|
|
705
708
|
Exit Status:
|
|
706
709
|
Returns the status of the last ID; fails if ID is invalid or an invalid
|
|
707
|
-
option is given.`]]]),
|
|
708
|
-
`,2)}i++}else r.push(e),i++}if(r.length===0)return
|
|
709
|
-
`,o=!0;continue}for(let e of t){let t=
|
|
710
|
+
option is given.`]]]),xv=[...bv.keys()].sort();function Sv(e,t){let n=!1,r=[],i=0;for(;i<t.length;){let e=t[i];if(e===`--`){for(i++;i<t.length;)r.push(t[i]),i++;break}if(e.startsWith(`-`)&&e.length>1){for(let t=1;t<e.length;t++){let r=e[t];if(r===`s`)n=!0;else return X(`bash: help: -${r}: invalid option
|
|
711
|
+
`,2)}i++}else r.push(e),i++}if(r.length===0)return wv();let a=``,o=!1,s=``;for(let e of r){let t=Cv(e);if(t.length===0){s+=`bash: help: no help topics match \`${e}'. Try \`help help' or \`man -k ${e}' or \`info ${e}'.
|
|
712
|
+
`,o=!0;continue}for(let e of t){let t=bv.get(e);if(!t)continue;let[r,i]=t;n?a+=`${e}: ${r}
|
|
710
713
|
`:a+=`${e}: ${r}
|
|
711
714
|
${i}
|
|
712
|
-
`}}return{exitCode:o?1:0,stdout:a,stderr:s}}function
|
|
715
|
+
`}}return{exitCode:o?1:0,stdout:a,stderr:s}}function Cv(e){let t=We(`^${e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`)}$`);return xv.filter(e=>t.test(e))}function wv(){let e=[];e.push(`just-bash shell builtins`),e.push("These shell commands are defined internally. Type `help' to see this list."),e.push("Type `help name' to find out more about the function `name'."),e.push(``);let t=xv.slice(),n=Math.ceil(t.length/2);for(let r=0;r<n;r++){let i=t[r]||``,a=t[r+n]||``,o=i.padEnd(36);e.push(a?`${o}${a}`:i)}return Y(`${e.join(`
|
|
713
716
|
`)}
|
|
714
|
-
`)}function
|
|
715
|
-
`);let n=
|
|
716
|
-
`)}return Z(``,``,r===0?1:0)}async function
|
|
717
|
+
`)}function Tv(e){let t=[],n=``,r=0;for(let i of e){for(let e of i)e===`(`?r++:e===`)`&&r--;n?n+=` ${i}`:n=i,r===0&&(t.push(n),n=``)}return n&&t.push(n),t}async function Ev(e,t){if(t.length===0)return X(`bash: let: expression expected
|
|
718
|
+
`);let n=Tv(t),r=0;for(let t of n)try{let n=_t(`(( ${t} ))`).statements[0];if(n&&n.pipelines.length>0&&n.pipelines[0].commands.length>0){let t=n.pipelines[0].commands[0];t.type===`ArithmeticCommand`&&(r=await It(e,t.expression.expression))}}catch(e){return X(`bash: let: ${t}: ${e.message}
|
|
719
|
+
`)}return Z(``,``,r===0?1:0)}async function Dv(e,t){if(e.state.localScopes.length===0)return X(`bash: local: can only be used in a function
|
|
717
720
|
`);let n=e.state.localScopes[e.state.localScopes.length-1],r=``,i=0,a=!1,o=!1,s=[];for(let e of t)if(e===`-n`)a=!0;else if(e===`-a`)o=!0;else if(e!==`-p`)if(e.startsWith(`-`)&&!e.includes(`=`))for(let t of e.slice(1))t===`n`?a=!0:t===`a`&&(o=!0);else s.push(e);if(s.length===0){let t=``,r=Array.from(n.keys()).filter(e=>!e.includes(`_`)||!e.match(/_\d+$/)).filter(e=>!e.includes(`__length`)).sort();for(let n of r){let r=e.state.env.get(n);r!==void 0&&(t+=`${n}=${r}
|
|
718
721
|
`)}return Z(t,``,0)}for(let t of s){let s,c,l=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(l){s=l[1];let o=l[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)){r+=`bash: local: \`${t}': not a valid identifier
|
|
719
|
-
`,i=1;continue}if(
|
|
720
|
-
`,i=1;continue}let p=n.has(s);if(c!==void 0){let t=e.state.env.get(s);if(e.state.tempEnvBindings){let n=e.state.accessedTempEnvVars?.has(s),r=e.state.mutatedTempEnvVars?.has(s);if(!n&&!r)for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(s)){t=r.get(s);break}}}
|
|
721
|
-
`,i=1;continue}e.state.env.set(s,c),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(s))}else{let t=e.state.tempEnvBindings?.some(e=>e.has(s));!p&&!t&&e.state.env.delete(s)}
|
|
722
|
+
`,i=1;continue}if(lt(e,s,`bash`),!n.has(s)){n.set(s,e.state.env.get(s));let t=`${s}_`;for(let r of e.state.env.keys())r.startsWith(t)&&!r.includes(`__`)&&(n.has(r)||n.set(r,e.state.env.get(r)))}let c=`${s}_`;for(let t of e.state.env.keys())t.startsWith(c)&&!t.includes(`__`)&&e.state.env.delete(t);let u=Bg(o);for(let t=0;t<u.length;t++)e.state.env.set(`${s}_${t}`,u[t]);e.state.env.set(`${s}__length`,String(u.length)),Gg(e,s),a&&Wt(e,s);continue}let u=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(u){s=u[1];let t=u[2];if(lt(e,s,`bash`),!n.has(s)){n.set(s,e.state.env.get(s));let t=`${s}_`;for(let r of e.state.env.keys())r.startsWith(t)&&!r.includes(`__`)&&(n.has(r)||n.set(r,e.state.env.get(r)));let r=`${s}__length`;e.state.env.has(r)&&!n.has(r)&&n.set(r,e.state.env.get(r))}let r=Bg(t),i=gt(e,s),o=0,c=e.state.env.get(s);i.length===0&&c!==void 0?(e.state.env.set(`${s}_0`,c),e.state.env.delete(s),o=1):i.length>0&&(o=Math.max(...i)+1);for(let t=0;t<r.length;t++)e.state.env.set(`${s}_${o+t}`,z_(e,r[t]));let l=o+r.length;e.state.env.set(`${s}__length`,String(l)),Gg(e,s),a&&Wt(e,s);continue}let d=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(d){s=d[1];let t=z_(e,d[2]);lt(e,s,`bash`),n.has(s)||n.set(s,e.state.env.get(s));let r=e.state.env.get(s)??``;e.state.env.set(s,r+t),Gg(e,s),a&&Wt(e,s);continue}let f=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(f){s=f[1];let t=f[2],r=z_(e,f[3]);if(lt(e,s,`bash`),!n.has(s)){n.set(s,e.state.env.get(s));let t=`${s}_`;for(let r of e.state.env.keys())r.startsWith(t)&&!r.includes(`__`)&&(n.has(r)||n.set(r,e.state.env.get(r)));let r=`${s}__length`;e.state.env.has(r)&&!n.has(r)&&n.set(r,e.state.env.get(r))}let i;try{i=await It(e,Tt(new Vt,t).expression)}catch{let e=parseInt(t,10);i=Number.isNaN(e)?0:e}e.state.env.set(`${s}_${i}`,r);let o=parseInt(e.state.env.get(`${s}__length`)??`0`,10);i>=o&&e.state.env.set(`${s}__length`,String(i+1)),Gg(e,s),a&&Wt(e,s);continue}if(t.includes(`=`)){let n=t.indexOf(`=`);s=t.slice(0,n),c=z_(e,t.slice(n+1))}else s=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)){r+=`bash: local: \`${t}': not a valid identifier
|
|
723
|
+
`,i=1;continue}let p=n.has(s);if(c!==void 0){let t=e.state.env.get(s);if(e.state.tempEnvBindings){let n=e.state.accessedTempEnvVars?.has(s),r=e.state.mutatedTempEnvVars?.has(s);if(!n&&!r)for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(s)){t=r.get(s);break}}}Jg(e,s,t)}if(!p){let t=e.state.env.get(s);if(e.state.tempEnvBindings)for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(s)){t=r.get(s);break}}if(n.set(s,t),o){let t=`${s}_`;for(let r of e.state.env.keys())r.startsWith(t)&&!r.includes(`__`)&&(n.has(r)||n.set(r,e.state.env.get(r)));let r=`${s}__length`;e.state.env.has(r)&&!n.has(r)&&n.set(r,e.state.env.get(r))}}if(o&&c===void 0){let t=`${s}_`;for(let n of e.state.env.keys())n.startsWith(t)&&!n.includes(`__`)&&e.state.env.delete(n);e.state.env.set(`${s}__length`,`0`)}else if(c!==void 0){if(lt(e,s,`bash`),a&&c!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(c)){r+=`bash: local: \`${c}': invalid variable name for name reference
|
|
724
|
+
`,i=1;continue}e.state.env.set(s,c),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(s))}else{let t=e.state.tempEnvBindings?.some(e=>e.has(s));!p&&!t&&e.state.env.delete(s)}Gg(e,s),a&&Wt(e,s)}return Z(``,r,i)}function Ov(e,t,n){let r=`
|
|
722
725
|
`,i=0,a=0,o=0,s=!1,c=`MAPFILE`,l=0;for(;l<t.length;){let e=t[l];e===`-d`&&l+1<t.length?(r=t[l+1]===``?`\0`:t[l+1]||`
|
|
723
726
|
`,l+=2):e===`-n`&&l+1<t.length?(i=Number.parseInt(t[l+1],10)||0,l+=2):e===`-O`&&l+1<t.length?(a=Number.parseInt(t[l+1],10)||0,l+=2):e===`-s`&&l+1<t.length?(o=Number.parseInt(t[l+1],10)||0,l+=2):e===`-t`?(s=!0,l++):e===`-u`||e===`-C`||e===`-c`?l+=2:(e.startsWith(`-`)||(c=e),l++)}let u=n;!u&&e.state.groupStdin!==void 0&&(u=e.state.groupStdin);let d=[],f=u,p=0,m=0,h=e.limits?.maxArrayElements??1e5;for(;f.length>0;){let e=f.indexOf(r);if(e===-1){if(f.length>0){if(m<o)m++;else if(i===0||p<i){if(a+p>=h)return Z(``,`mapfile: array element limit exceeded (${h})
|
|
724
727
|
`,1);let e=f,t=e.indexOf(`\0`);t!==-1&&(e=e.substring(0,t)),d.push(e),p++}}break}let t=f.substring(0,e),n=t.indexOf(`\0`);if(n!==-1&&(t=t.substring(0,n)),!s&&r!==`\0`&&(t+=r),f=f.substring(e+r.length),m<o){m++;continue}if(i>0&&p>=i)break;if(a+p>=h)return Z(``,`mapfile: array element limit exceeded (${h})
|
|
725
|
-
`,1);d.push(t),p++}a===0&&
|
|
726
|
-
`,o=-1,s=-1,c=null,l=-1,u=-1,d=[],f=0,p=!1,m=(e,n)=>{let r=1;for(;r<e.length;){let d=e[r];if(d===`r`)i=!0,r++;else if(d===`s`)r++;else{if(d===`d`)return r+1<e.length?(a=e.substring(r+1),{nextArgIndex:n+1}):n+1<t.length?(a=t[n+1],{nextArgIndex:n+2}):{nextArgIndex:n+1};if(d===`n`){if(r+1<e.length){let t=e.substring(r+1);return o=Number.parseInt(t,10),(Number.isNaN(o)||o<0)&&(p=!0,o=0),{nextArgIndex:n+1}}else if(n+1<t.length)return o=Number.parseInt(t[n+1],10),(Number.isNaN(o)||o<0)&&(p=!0,o=0),{nextArgIndex:n+2};return{nextArgIndex:n+1}}else if(d===`N`){if(r+1<e.length){let t=e.substring(r+1);return s=Number.parseInt(t,10),(Number.isNaN(s)||s<0)&&(p=!0,s=0),{nextArgIndex:n+1}}else if(n+1<t.length)return s=Number.parseInt(t[n+1],10),(Number.isNaN(s)||s<0)&&(p=!0,s=0),{nextArgIndex:n+2};return{nextArgIndex:n+1}}else{if(d===`a`)return r+1<e.length?(c=e.substring(r+1),{nextArgIndex:n+1}):n+1<t.length?(c=t[n+1],{nextArgIndex:n+2}):{nextArgIndex:n+1};if(d===`p`)return r+1<e.length?(e.substring(r+1),{nextArgIndex:n+1}):n+1<t.length?(t[n+1],{nextArgIndex:n+2}):{nextArgIndex:n+1};if(d===`u`){if(r+1<e.length){let t=e.substring(r+1);return l=Number.parseInt(t,10),Number.isNaN(l)||l<0?{nextArgIndex:-2}:{nextArgIndex:n+1}}else if(n+1<t.length)return l=Number.parseInt(t[n+1],10),Number.isNaN(l)||l<0?{nextArgIndex:-2}:{nextArgIndex:n+2};return{nextArgIndex:n+1}}else if(d===`t`){if(r+1<e.length){let t=e.substring(r+1);return u=Number.parseFloat(t),Number.isNaN(u)&&(u=0),{nextArgIndex:n+1}}else if(n+1<t.length)return u=Number.parseFloat(t[n+1]),Number.isNaN(u)&&(u=0),{nextArgIndex:n+2};return{nextArgIndex:n+1}}else if(d===`e`||d===`i`||d===`P`){if(d===`i`&&n+1<t.length)return{nextArgIndex:n+2};r++}else r++}}}return{nextArgIndex:n+1}};for(;f<t.length;){let e=t[f];if(e.startsWith(`-`)&&e.length>1&&e!==`--`){let t=m(e,f);if(t.nextArgIndex===-1)return{stdout:``,stderr:``,exitCode:2};if(t.nextArgIndex===-2)return{stdout:``,stderr:``,exitCode:1};f=t.nextArgIndex}else if(e===`--`)for(f++;f<t.length;)d.push(t[f]),f++;else d.push(e),f++}if(p)return Z(``,``,1);if(d.length===0&&c===null&&d.push(`REPLY`),u===0){if(c)
|
|
728
|
+
`,1);d.push(t),p++}a===0&&Lt(e,c);for(let t=0;t<d.length;t++)e.state.env.set(`${c}_${a+t}`,d[t]);let g=parseInt(e.state.env.get(`${c}__length`)||`0`,10),_=a+d.length;return e.state.env.set(`${c}__length`,String(Math.max(g,_))),e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=``),Z(``,``,0)}function kv(e){if(!e.startsWith(`__rw__:`))return null;let t=e.slice(7),n=t.indexOf(`:`);if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let i=n+1,a=t.slice(i,i+r),o=i+r+1,s=t.slice(o),c=s.indexOf(`:`);if(c===-1)return null;let l=Number.parseInt(s.slice(0,c),10);return Number.isNaN(l)||l<0?null:{path:a,position:l,content:s.slice(c+1)}}function Av(e,t,n){return`__rw__:${e.length}:${e}:${t}:${n}`}function jv(e,t,n,r=-1){let i=!1,a=`
|
|
729
|
+
`,o=-1,s=-1,c=null,l=-1,u=-1,d=[],f=0,p=!1,m=(e,n)=>{let r=1;for(;r<e.length;){let d=e[r];if(d===`r`)i=!0,r++;else if(d===`s`)r++;else{if(d===`d`)return r+1<e.length?(a=e.substring(r+1),{nextArgIndex:n+1}):n+1<t.length?(a=t[n+1],{nextArgIndex:n+2}):{nextArgIndex:n+1};if(d===`n`){if(r+1<e.length){let t=e.substring(r+1);return o=Number.parseInt(t,10),(Number.isNaN(o)||o<0)&&(p=!0,o=0),{nextArgIndex:n+1}}else if(n+1<t.length)return o=Number.parseInt(t[n+1],10),(Number.isNaN(o)||o<0)&&(p=!0,o=0),{nextArgIndex:n+2};return{nextArgIndex:n+1}}else if(d===`N`){if(r+1<e.length){let t=e.substring(r+1);return s=Number.parseInt(t,10),(Number.isNaN(s)||s<0)&&(p=!0,s=0),{nextArgIndex:n+1}}else if(n+1<t.length)return s=Number.parseInt(t[n+1],10),(Number.isNaN(s)||s<0)&&(p=!0,s=0),{nextArgIndex:n+2};return{nextArgIndex:n+1}}else{if(d===`a`)return r+1<e.length?(c=e.substring(r+1),{nextArgIndex:n+1}):n+1<t.length?(c=t[n+1],{nextArgIndex:n+2}):{nextArgIndex:n+1};if(d===`p`)return r+1<e.length?(e.substring(r+1),{nextArgIndex:n+1}):n+1<t.length?(t[n+1],{nextArgIndex:n+2}):{nextArgIndex:n+1};if(d===`u`){if(r+1<e.length){let t=e.substring(r+1);return l=Number.parseInt(t,10),Number.isNaN(l)||l<0?{nextArgIndex:-2}:{nextArgIndex:n+1}}else if(n+1<t.length)return l=Number.parseInt(t[n+1],10),Number.isNaN(l)||l<0?{nextArgIndex:-2}:{nextArgIndex:n+2};return{nextArgIndex:n+1}}else if(d===`t`){if(r+1<e.length){let t=e.substring(r+1);return u=Number.parseFloat(t),Number.isNaN(u)&&(u=0),{nextArgIndex:n+1}}else if(n+1<t.length)return u=Number.parseFloat(t[n+1]),Number.isNaN(u)&&(u=0),{nextArgIndex:n+2};return{nextArgIndex:n+1}}else if(d===`e`||d===`i`||d===`P`){if(d===`i`&&n+1<t.length)return{nextArgIndex:n+2};r++}else r++}}}return{nextArgIndex:n+1}};for(;f<t.length;){let e=t[f];if(e.startsWith(`-`)&&e.length>1&&e!==`--`){let t=m(e,f);if(t.nextArgIndex===-1)return{stdout:``,stderr:``,exitCode:2};if(t.nextArgIndex===-2)return{stdout:``,stderr:``,exitCode:1};f=t.nextArgIndex}else if(e===`--`)for(f++;f<t.length;)d.push(t[f]),f++;else d.push(e),f++}if(p)return Z(``,``,1);if(d.length===0&&c===null&&d.push(`REPLY`),u===0){if(c)Lt(e,c);else{for(let t of d)e.state.env.set(t,``);d.length===0&&e.state.env.set(`REPLY`,``)}return Z(``,``,0)}if(u<0&&u!==-1)return Z(``,``,1);let h=n;l>=0?h=e.state.fileDescriptors&&e.state.fileDescriptors.get(l)||``:!h&&e.state.groupStdin!==void 0&&(h=e.state.groupStdin);let g=a===``?`\0`:a,_=``,v=0,y=!0,b=t=>{if(l>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(l,h.substring(t));else if(r>=0&&e.state.fileDescriptors){let n=e.state.fileDescriptors.get(r);if(n?.startsWith(`__rw__:`)){let i=kv(n);if(i){let n=i.position+t;e.state.fileDescriptors.set(r,Av(i.path,n,i.content))}}}else e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=h.substring(t))};if(s>=0){let t=Math.min(s,h.length);_=h.substring(0,t),v=t,y=t>=s,b(v);let n=d[0]||`REPLY`;e.state.env.set(n,_);for(let t=1;t<d.length;t++)e.state.env.set(d[t],``);return Z(``,``,y?0:1)}else if(o>=0){let e=0,t=0,n=!1;for(;t<h.length&&e<o;){let r=h[t];if(r===g){v=t+1,n=!0;break}if(!i&&r===`\\`&&t+1<h.length){let n=h[t+1];if(n===g&&g===`
|
|
727
730
|
`){t+=2,v=t;continue}if(n===g){t+=2,e++,_+=n,v=t;continue}_+=n,t+=2,e++,v=t}else _+=r,t++,e++,v=t}y=e>=o||n,b(v)}else{v=0;let t=0;for(;t<h.length;){let e=h[t];if(e===g){v=t+g.length,y=!0;break}if(!i&&e===`\\`&&t+1<h.length){let n=h[t+1];if(n===`
|
|
728
|
-
`){t+=2;continue}if(n===g){_+=n,t+=2;continue}_+=e,_+=n,t+=2;continue}_+=e,t++}if(t>=h.length&&(y=!1,v=t,_.length===0&&h.length===0)){for(let t of d)e.state.env.set(t,``);return c&&
|
|
731
|
+
`){t+=2;continue}if(n===g){_+=n,t+=2;continue}_+=e,_+=n,t+=2;continue}_+=e,t++}if(t>=h.length&&(y=!1,v=t,_.length===0&&h.length===0)){for(let t of d)e.state.env.set(t,``);return c&&Lt(e,c),Z(``,``,1)}b(v)}g===`
|
|
729
732
|
`&&_.endsWith(`
|
|
730
|
-
`)&&(_=_.slice(0,-1));let x=e=>i?e:e.replace(/\\(.)/g,`$1`);if(d.length===1&&d[0]===`REPLY`)return e.state.env.set(`REPLY`,x(_)),Z(``,``,y?0:1);let S=
|
|
731
|
-
`,1);
|
|
733
|
+
`)&&(_=_.slice(0,-1));let x=e=>i?e:e.replace(/\\(.)/g,`$1`);if(d.length===1&&d[0]===`REPLY`)return e.state.env.set(`REPLY`,x(_)),Z(``,``,y?0:1);let S=Dt(e.state.env);if(c){let{words:t}=Ut(_,S,void 0,i),n=e.limits?.maxArrayElements??1e5;if(t.length>n)return Z(``,`read: array element limit exceeded (${n})
|
|
734
|
+
`,1);Lt(e,c);for(let n=0;n<t.length;n++)e.state.env.set(`${c}_${n}`,x(t[n]));return Z(``,``,y?0:1)}let ee=d.length,{words:te,wordStarts:ne}=Ut(_,S,ee,i);for(let t=0;t<d.length;t++){let n=d[t];if(t<d.length-1)e.state.env.set(n,x(te[t]??``));else if(t<ne.length){let r=_.substring(ne[t]);r=St(r,S,i),r=x(r),e.state.env.set(n,r)}else e.state.env.set(n,``)}return Z(``,``,y?0:1)}function Mv(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return X(`bash: return: can only \`return' from a function or sourced script
|
|
732
735
|
`);let n=e.state.lastExitCode;if(t.length>0){let e=t[0],r=Number.parseInt(e,10);if(e===``||Number.isNaN(r)||!/^-?\d+$/.test(e))return X(`bash: return: ${e}: numeric argument required
|
|
733
|
-
`,2);n=(r%256+256)%256}throw new
|
|
736
|
+
`,2);n=(r%256+256)%256}throw new Ze(n)}var Nv=`set: usage: set [-eux] [+eux] [-o option] [+o option]
|
|
734
737
|
Options:
|
|
735
738
|
-e Exit immediately if a command exits with non-zero status
|
|
736
739
|
+e Disable -e
|
|
@@ -746,57 +749,57 @@ Options:
|
|
|
746
749
|
+o pipefail Disable pipefail
|
|
747
750
|
-o xtrace Same as -x
|
|
748
751
|
+o xtrace Disable xtrace
|
|
749
|
-
`,
|
|
752
|
+
`,Pv=new Map([[`e`,`errexit`],[`u`,`nounset`],[`x`,`xtrace`],[`v`,`verbose`],[`f`,`noglob`],[`C`,`noclobber`],[`a`,`allexport`],[`n`,`noexec`],[`h`,null],[`b`,null],[`m`,null],[`B`,null],[`H`,null],[`P`,null],[`T`,null],[`E`,null],[`p`,null]]),Fv=new Map([[`errexit`,`errexit`],[`pipefail`,`pipefail`],[`nounset`,`nounset`],[`xtrace`,`xtrace`],[`verbose`,`verbose`],[`noclobber`,`noclobber`],[`noglob`,`noglob`],[`allexport`,`allexport`],[`noexec`,`noexec`],[`posix`,`posix`],[`vi`,`vi`],[`emacs`,`emacs`],[`notify`,null],[`monitor`,null],[`braceexpand`,null],[`histexpand`,null],[`physical`,null],[`functrace`,null],[`errtrace`,null],[`privileged`,null],[`hashall`,null],[`ignoreeof`,null],[`interactive-comments`,null],[`keyword`,null],[`onecmd`,null]]),Iv=[`errexit`,`nounset`,`pipefail`,`verbose`,`xtrace`,`posix`,`allexport`,`noclobber`,`noglob`,`noexec`,`vi`,`emacs`],Lv=[`braceexpand`,`errtrace`,`functrace`,`hashall`,`histexpand`,`history`,`ignoreeof`,`interactive-comments`,`keyword`,`monitor`,`nolog`,`notify`,`onecmd`,`physical`,`privileged`];function Rv(e,t,n){t!==null&&(n&&(t===`vi`?e.state.options.emacs=!1:t===`emacs`&&(e.state.options.vi=!1)),e.state.options[t]=n,Rh(e))}function zv(e,t){return t+1<e.length&&!e[t+1].startsWith(`-`)&&!e[t+1].startsWith(`+`)}function Bv(e,t){let n=gt(e,t);return n.length===0?`${t}=()`:`${t}=(${n.map(n=>`[${n}]=${U_(e.state.env.get(`${t}_${n}`)??``)}`).join(` `)})`}function Vv(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function Hv(e,t){let n=ot(e,t);return n.length===0?`${t}=()`:`${t}=(${n.map(n=>{let r=e.state.env.get(`${t}_${n}`)??``;return`[${Vv(n)}]=${U_(r)}`}).join(` `)} )`}function Uv(e){let t=new Set,n=e.state.associativeArrays??new Set;for(let r of e.state.env.keys()){let e=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(e){let r=e[1];n.has(r)||t.add(r)}}return t}function Wv(e){return e.state.associativeArrays??new Set}function Gv(e,t){if(t.includes(`--help`))return Y(Nv);if(t.length===0){let t=Uv(e),n=Wv(e),r=e=>{for(let t of n){let n=`${t}_`;if(e!==`${t}__length`&&e.startsWith(n)){if(e.slice(n.length).startsWith(`_length`))continue;return!0}}return!1},i=[];for(let[a,o]of e.state.env){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)||t.has(a)||n.has(a))continue;let e=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(e&&t.has(e[1]))continue;let s=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);s&&t.has(s[1])||r(a)||s&&n.has(s[1])||i.push([a,o])}let a=[];for(let[e,t]of i.sort(([e],[t])=>e<t?-1:e>t?1:0))a.push(`${e}=${H_(t)}`);for(let n of[...t].sort((e,t)=>e<t?-1:e>t?1:0))a.push(Bv(e,n));for(let t of[...n].sort((e,t)=>e<t?-1:e>t?1:0))a.push(Hv(e,t));return a.sort((e,t)=>{let n=e.split(`=`)[0],r=t.split(`=`)[0];return n<r?-1:n>r?1:0}),Y(a.length>0?`${a.join(`
|
|
750
753
|
`)}
|
|
751
|
-
`:``)}let n=0;for(;n<t.length;){let r=t[n];if((r===`-o`||r===`+o`)&&
|
|
752
|
-
${
|
|
754
|
+
`:``)}let n=0;for(;n<t.length;){let r=t[n];if((r===`-o`||r===`+o`)&&zv(t,n)){let i=t[n+1];if(!Fv.has(i)){let t=`bash: set: ${i}: invalid option name
|
|
755
|
+
${Nv}`;if(e.state.options.posix)throw new $e(1,``,t);return X(t)}Rv(e,Fv.get(i)??null,r===`-o`),n+=2;continue}if(r===`-o`){let t=Iv.map(t=>`${t.padEnd(16)}${e.state.options[t]?`on`:`off`}`),n=Lv.map(e=>`${e.padEnd(16)}off`);return Y(`${[...t,...n].sort().join(`
|
|
753
756
|
`)}
|
|
754
|
-
`)}if(r===`+o`){let t=
|
|
757
|
+
`)}if(r===`+o`){let t=Iv.map(t=>`set ${e.state.options[t]?`-o`:`+o`} ${t}`),n=Lv.map(e=>`set +o ${e}`);return Y(`${[...t,...n].sort().join(`
|
|
755
758
|
`)}
|
|
756
|
-
`)}if(r.length>1&&(r[0]===`-`||r[0]===`+`)&&r[1]!==`-`){let t=r[0]===`-`;for(let n=1;n<r.length;n++){let i=r[n];if(!
|
|
757
|
-
${
|
|
758
|
-
${
|
|
759
|
-
`;if(e.state.options.posix)throw new
|
|
760
|
-
`;if(e.state.options.posix)throw new
|
|
759
|
+
`)}if(r.length>1&&(r[0]===`-`||r[0]===`+`)&&r[1]!==`-`){let t=r[0]===`-`;for(let n=1;n<r.length;n++){let i=r[n];if(!Pv.has(i)){let t=`bash: set: ${r[0]}${i}: invalid option
|
|
760
|
+
${Nv}`;if(e.state.options.posix)throw new $e(1,``,t);return X(t)}Rv(e,Pv.get(i)??null,t)}n++;continue}if(r===`--`)return Kv(e,t.slice(n+1)),J;if(r===`-`){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,Rh(e),n+1<t.length)return Kv(e,t.slice(n+1)),J;n++;continue}if(r===`+`){n++;continue}if(r.startsWith(`-`)||r.startsWith(`+`)){let t=`bash: set: ${r}: invalid option
|
|
761
|
+
${Nv}`;if(e.state.options.posix)throw new $e(1,``,t);return X(t)}return Kv(e,t.slice(n)),J}return J}function Kv(e,t){let n=1;for(;e.state.env.has(String(n));)e.state.env.delete(String(n)),n++;for(let n=0;n<t.length;n++)e.state.env.set(String(n+1),t[n]);e.state.env.set(`#`,String(t.length)),e.state.env.set(`@`,t.join(` `)),e.state.env.set(`*`,t.join(` `))}function qv(e,t){let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<0){let n=`bash: shift: ${t[0]}: numeric argument required
|
|
762
|
+
`;if(e.state.options.posix)throw new $e(1,``,n);return X(n)}n=r}let r=Number.parseInt(e.state.env.get(`#`)||`0`,10);if(n>r){let t=`bash: shift: shift count out of range
|
|
763
|
+
`;if(e.state.options.posix)throw new $e(1,``,t);return X(t)}if(n===0)return J;let i=[];for(let t=1;t<=r;t++)i.push(e.state.env.get(String(t))||``);let a=i.slice(n);for(let t=1;t<=r;t++)e.state.env.delete(String(t));for(let t=0;t<a.length;t++)e.state.env.set(String(t+1),a[t]);return e.state.env.set(`#`,String(a.length)),e.state.env.set(`@`,a.join(` `)),J}async function Jv(e,t){let n=t;if(n.length>0&&n[0]===`--`&&(n=n.slice(1)),n.length===0)return Z(``,`bash: source: filename argument required
|
|
761
764
|
`,2);let r=n[0],i=null;if(r.includes(`/`)){let t=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(t)}catch{}}else{let t=(e.state.env.get(`PATH`)||``).split(`:`).filter(e=>e);for(let n of t){let t=e.fs.resolvePath(e.state.cwd,`${n}/${r}`);try{if((await e.fs.stat(t)).isDirectory)continue;i=await e.fs.readFile(t);break}catch{}}if(i===null){let t=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(t)}catch{}}}if(i===null)return X(`bash: ${r}: No such file or directory
|
|
762
|
-
`);let a=new Map;if(n.length>1){for(let t=1;t<=9;t++)a.set(String(t),e.state.env.get(String(t)));a.set(`#`,e.state.env.get(`#`)),a.set(`@`,e.state.env.get(`@`));let t=n.slice(1);e.state.env.set(`#`,String(t.length)),e.state.env.set(`@`,t.join(` `));for(let n=0;n<t.length&&n<9;n++)e.state.env.set(String(n+1),t[n]);for(let n=t.length+1;n<=9;n++)e.state.env.delete(String(n))}let o=e.state.currentSource,s=()=>{if(e.state.sourceDepth--,e.state.currentSource=o,n.length>1)for(let[t,n]of a)n===void 0?e.state.env.delete(t):e.state.env.set(t,n)};if(e.state.sourceDepth++,e.state.sourceDepth>e.limits.maxSourceDepth)throw e.state.sourceDepth--,new
|
|
763
|
-
`);throw e}}function
|
|
764
|
-
`,i=1;continue}let l=await
|
|
765
|
-
`,i=1;continue}if(l===null)continue;if(l<0){let t=
|
|
765
|
+
`);let a=new Map;if(n.length>1){for(let t=1;t<=9;t++)a.set(String(t),e.state.env.get(String(t)));a.set(`#`,e.state.env.get(`#`)),a.set(`@`,e.state.env.get(`@`));let t=n.slice(1);e.state.env.set(`#`,String(t.length)),e.state.env.set(`@`,t.join(` `));for(let n=0;n<t.length&&n<9;n++)e.state.env.set(String(n+1),t[n]);for(let n=t.length+1;n<=9;n++)e.state.env.delete(String(n))}let o=e.state.currentSource,s=()=>{if(e.state.sourceDepth--,e.state.currentSource=o,n.length>1)for(let[t,n]of a)n===void 0?e.state.env.delete(t):e.state.env.set(t,n)};if(e.state.sourceDepth++,e.state.sourceDepth>e.limits.maxSourceDepth)throw e.state.sourceDepth--,new Xe(`source: maximum nesting depth (${e.limits.maxSourceDepth}) exceeded, increase executionLimits.maxSourceDepth`,`recursion`);e.state.currentSource=r;try{let t=_t(i),n=await e.executeScript(t);return s(),n}catch(e){if(s(),e instanceof et)throw e;if(e instanceof Ze)return Z(e.stdout,e.stderr,e.exitCode);if(e.name===`ParseException`)return X(`bash: ${r}: ${e.message}
|
|
766
|
+
`);throw e}}function Yv(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function Xv(e){return e.startsWith(`'`)&&e.endsWith(`'`)||e.startsWith(`"`)&&e.endsWith(`"`)}async function Zv(e,t){if(Xv(t))return null;try{return await It(e,Tt(new Vt,t).expression)}catch{let e=parseInt(t,10);return Number.isNaN(e)?0:e}}function Qv(e,t){if(e.state.localVarStack?.has(t)){let n=Yg(e,t);if(n){n.value===void 0?e.state.env.delete(t):e.state.env.set(t,n.value);let r=e.state.localVarStack?.get(t);if(!r||r.length===0)qg(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,n.scopeIndex),$v(e,t);else{let n=r[r.length-1];e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,n.scopeIndex+1)}return!0}return e.state.env.delete(t),qg(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let n=e.state.localScopes.length-1;n>=0;n--){let r=e.state.localScopes[n];if(r.has(t)){let i=r.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),r.delete(t);let a=!1;for(let r=n-1;r>=0;r--)if(e.state.localScopes[r].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,r+1),a=!0;break}return a||qg(e,t),!0}}return!1}function $v(e,t){if(!e.state.tempEnvBindings||e.state.tempEnvBindings.length===0)return!1;for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(t)){let n=r.get(t);return n===void 0?e.state.env.delete(t):e.state.env.set(t,n),r.delete(t),!0}}return!1}async function ey(e,t){if(t.startsWith(`'`)&&t.endsWith(`'`))return t.slice(1,-1);if(t.startsWith(`"`)&&t.endsWith(`"`)){let n=t.slice(1,-1);return E(e,new Vt().parseWordFromString(n,!0,!1))}return t.includes(`$`)?E(e,new Vt().parseWordFromString(t,!1,!1)):t}async function ty(e,t){let n=`both`,r=``,i=0;for(let a of t){if(a===`-v`){n=`variable`;continue}if(a===`-f`){n=`function`;continue}if(n===`function`){e.state.functions.delete(a);continue}if(n===`variable`){let t=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(t){let n=t[1],a=t[2];if(a===`@`||a===`*`){let t=Et(e,n);for(let[r]of t)e.state.env.delete(`${n}_${r}`);e.state.env.delete(n);continue}let o=e.state.associativeArrays?.has(n);if(o){let t=await ey(e,a);e.state.env.delete(`${n}_${t}`);continue}let s=Ht(e,n),c=e.state.declaredVars?.has(n);if((e.state.env.has(n)||c)&&!s&&!o){r+=`bash: unset: ${n}: not an array variable
|
|
767
|
+
`,i=1;continue}let l=await Zv(e,a);if(l===null&&s){r+=`bash: unset: ${a}: not a valid identifier
|
|
768
|
+
`,i=1;continue}if(l===null)continue;if(l<0){let t=Et(e,n),a=t.length,o=e.state.currentLine;if(a===0){r+=`bash: line ${o}: unset: [${l}]: bad array subscript
|
|
766
769
|
`,i=1;continue}let s=a+l;if(s<0){r+=`bash: line ${o}: unset: [${l}]: bad array subscript
|
|
767
|
-
`,i=1;continue}let c=t[s][0];e.state.env.delete(`${n}_${c}`);continue}e.state.env.delete(`${n}_${l}`);continue}if(!
|
|
768
|
-
`,i=1;continue}let n=a;if(
|
|
769
|
-
`,i=1;continue}let o=
|
|
770
|
-
`,i=1;continue}let c=await
|
|
771
|
-
`,i=1;continue}if(c===null)continue;if(c<0){let t=
|
|
770
|
+
`,i=1;continue}let c=t[s][0];e.state.env.delete(`${n}_${c}`);continue}e.state.env.delete(`${n}_${l}`);continue}if(!Yv(a)){r+=`bash: unset: \`${a}': not a valid identifier
|
|
771
|
+
`,i=1;continue}let n=a;if(wt(e,a)){let t=At(e,a);t&&t!==a&&(n=t)}if(st(e,n)){r+=`bash: unset: ${n}: cannot unset: readonly variable
|
|
772
|
+
`,i=1;continue}let o=Kg(e,n);if(o!==void 0&&o!==e.state.callDepth)Qv(e,n);else if(e.state.fullyUnsetLocals?.has(n))e.state.env.delete(n);else if(o!==void 0){let t=e.state.accessedTempEnvVars?.has(n),r=e.state.mutatedTempEnvVars?.has(n);if((t||r)&&e.state.localVarStack?.has(n)){let t=Yg(e,n);t?t.value===void 0?e.state.env.delete(n):e.state.env.set(n,t.value):e.state.env.delete(n)}else e.state.env.delete(n)}else $v(e,n)||e.state.env.delete(n);e.state.exportedVars?.delete(n);continue}let t=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(t){let n=t[1],a=t[2];if(a===`@`||a===`*`){let t=Et(e,n);for(let[r]of t)e.state.env.delete(`${n}_${r}`);e.state.env.delete(n);continue}let o=e.state.associativeArrays?.has(n);if(o){let t=await ey(e,a);e.state.env.delete(`${n}_${t}`);continue}let s=Ht(e,n);if(e.state.env.has(n)&&!s&&!o){r+=`bash: unset: ${n}: not an array variable
|
|
773
|
+
`,i=1;continue}let c=await Zv(e,a);if(c===null&&s){r+=`bash: unset: ${a}: not a valid identifier
|
|
774
|
+
`,i=1;continue}if(c===null)continue;if(c<0){let t=Et(e,n),a=t.length,o=e.state.currentLine;if(a===0){r+=`bash: line ${o}: unset: [${c}]: bad array subscript
|
|
772
775
|
`,i=1;continue}let s=a+c;if(s<0){r+=`bash: line ${o}: unset: [${c}]: bad array subscript
|
|
773
|
-
`,i=1;continue}let l=t[s][0];e.state.env.delete(`${n}_${l}`);continue}e.state.env.delete(`${n}_${c}`);continue}if(!
|
|
774
|
-
`,i=1;continue}let o=a;if(
|
|
775
|
-
`,i=1;continue}let s=
|
|
776
|
-
`}}}c++}else break}for(;c<t.length;)s.push(t[c]),c++;if(o)return
|
|
777
|
-
`};if(s.length===0){if(n||r){let t=[];for(let a of
|
|
776
|
+
`,i=1;continue}let l=t[s][0];e.state.env.delete(`${n}_${l}`);continue}e.state.env.delete(`${n}_${c}`);continue}if(!Yv(a)){r+=`bash: unset: \`${a}': not a valid identifier
|
|
777
|
+
`,i=1;continue}let o=a;if(wt(e,a)){let t=At(e,a);t&&t!==a&&(o=t)}if(st(e,o)){r+=`bash: unset: ${o}: cannot unset: readonly variable
|
|
778
|
+
`,i=1;continue}let s=Kg(e,o);if(s!==void 0&&s!==e.state.callDepth)Qv(e,o);else if(e.state.fullyUnsetLocals?.has(o))e.state.env.delete(o);else if(s!==void 0){let t=e.state.accessedTempEnvVars?.has(o),n=e.state.mutatedTempEnvVars?.has(o);if((t||n)&&e.state.localVarStack?.has(o)){let t=Yg(e,o);t?t.value===void 0?e.state.env.delete(o):e.state.env.set(o,t.value):e.state.env.delete(o)}else e.state.env.delete(o)}else $v(e,o)||e.state.env.delete(o);e.state.exportedVars?.delete(o),e.state.functions.delete(a)}return Z(``,r,i)}var ny=[`extglob`,`dotglob`,`nullglob`,`failglob`,`globstar`,`globskipdots`,`nocaseglob`,`nocasematch`,`expand_aliases`,`lastpipe`,`xpg_echo`],ry=`autocd.cdable_vars.cdspell.checkhash.checkjobs.checkwinsize.cmdhist.compat31.compat32.compat40.compat41.compat42.compat43.compat44.complete_fullquote.direxpand.dirspell.execfail.extdebug.extquote.force_fignore.globasciiranges.gnu_errfmt.histappend.histreedit.histverify.hostcomplete.huponexit.inherit_errexit.interactive_comments.lithist.localvar_inherit.localvar_unset.login_shell.mailwarn.no_empty_cmd_completion.progcomp.progcomp_alias.promptvars.restricted_shell.shift_verbose.sourcepath`.split(`.`);function iy(e){return ny.includes(e)}function ay(e){return ry.includes(e)}function oy(e,t){let n=!1,r=!1,i=!1,a=!1,o=!1,s=[],c=0;for(;c<t.length;){let e=t[c];if(e===`--`){c++;break}if(e.startsWith(`-`)&&e.length>1){for(let t=1;t<e.length;t++){let s=e[t];switch(s){case`s`:n=!0;break;case`u`:r=!0;break;case`p`:i=!0;break;case`q`:a=!0;break;case`o`:o=!0;break;default:return{exitCode:2,stdout:``,stderr:`shopt: -${s}: invalid option
|
|
779
|
+
`}}}c++}else break}for(;c<t.length;)s.push(t[c]),c++;if(o)return sy(e,s,n,r,i,a);if(n&&r)return{exitCode:1,stdout:``,stderr:`shopt: cannot set and unset shell options simultaneously
|
|
780
|
+
`};if(s.length===0){if(n||r){let t=[];for(let a of ny){let o=e.state.shoptOptions[a];n&&o?t.push(i?`shopt -s ${a}`:`${a} on`):r&&!o&&t.push(i?`shopt -u ${a}`:`${a} off`)}return{exitCode:0,stdout:t.length>0?`${t.join(`
|
|
778
781
|
`)}
|
|
779
|
-
`:``,stderr:``}}let t=[];for(let n of
|
|
782
|
+
`:``,stderr:``}}let t=[];for(let n of ny){let r=e.state.shoptOptions[n];t.push(i?`shopt ${r?`-s`:`-u`} ${n}`:`${n} ${r?`on`:`off`}`)}return{exitCode:0,stdout:`${t.join(`
|
|
780
783
|
`)}
|
|
781
|
-
`,stderr:``}}let l=!1,u=``,d=[];for(let t of s){if(!
|
|
782
|
-
`,l=!0;continue}if(n)
|
|
784
|
+
`,stderr:``}}let l=!1,u=``,d=[];for(let t of s){if(!iy(t)&&!ay(t)){u+=`shopt: ${t}: invalid shell option name
|
|
785
|
+
`,l=!0;continue}if(n)iy(t)&&(e.state.shoptOptions[t]=!0,Vh(e));else if(r)iy(t)&&(e.state.shoptOptions[t]=!1,Vh(e));else if(iy(t)){let n=e.state.shoptOptions[t];a?n||(l=!0):i?(d.push(`shopt ${n?`-s`:`-u`} ${t}`),n||(l=!0)):(d.push(`${t} ${n?`on`:`off`}`),n||(l=!0))}else a?l=!0:i?(d.push(`shopt -u ${t}`),l=!0):(d.push(`${t} off`),l=!0)}return{exitCode:l?1:0,stdout:d.length>0?`${d.join(`
|
|
783
786
|
`)}
|
|
784
|
-
`:``,stderr:u}}function
|
|
787
|
+
`:``,stderr:u}}function sy(e,t,n,r,i,a){let o=new Map([[`errexit`,`errexit`],[`pipefail`,`pipefail`],[`nounset`,`nounset`],[`xtrace`,`xtrace`],[`verbose`,`verbose`],[`posix`,`posix`],[`allexport`,`allexport`],[`noclobber`,`noclobber`],[`noglob`,`noglob`],[`noexec`,`noexec`],[`vi`,`vi`],[`emacs`,`emacs`]]),s=[`braceexpand`,`errtrace`,`functrace`,`hashall`,`histexpand`,`history`,`ignoreeof`,`interactive-comments`,`keyword`,`monitor`,`nolog`,`notify`,`onecmd`,`physical`,`privileged`],c=[...o.keys(),...s].sort();if(t.length===0){let t=[];for(let a of c){let c=s.includes(a),l=o.get(a),u=c||!l?!1:e.state.options[l];n&&!u||r&&u||t.push(i?`set ${u?`-o`:`+o`} ${a}`:`${a} ${u?`on`:`off`}`)}return{exitCode:0,stdout:t.length>0?`${t.join(`
|
|
785
788
|
`)}
|
|
786
789
|
`:``,stderr:``}}let l=!1,u=``,d=[];for(let c of t){let t=o.has(c),f=s.includes(c);if(!t&&!f){u+=`shopt: ${c}: invalid option name
|
|
787
|
-
`,l=!0;continue}if(f){n||r||(a?l=!0:i?(d.push(`set +o ${c}`),l=!0):(d.push(`${c} off`),l=!0));continue}let p=o.get(c);if(p)if(n)p===`vi`?e.state.options.emacs=!1:p===`emacs`&&(e.state.options.vi=!1),e.state.options[p]=!0,
|
|
790
|
+
`,l=!0;continue}if(f){n||r||(a?l=!0:i?(d.push(`set +o ${c}`),l=!0):(d.push(`${c} off`),l=!0));continue}let p=o.get(c);if(p)if(n)p===`vi`?e.state.options.emacs=!1:p===`emacs`&&(e.state.options.vi=!1),e.state.options[p]=!0,Rh(e);else if(r)e.state.options[p]=!1,Rh(e);else{let t=e.state.options[p];a?t||(l=!0):i?(d.push(`set ${t?`-o`:`+o`} ${c}`),t||(l=!0)):(d.push(`${c} ${t?`on`:`off`}`),t||(l=!0))}}return{exitCode:l?1:0,stdout:d.length>0?`${d.join(`
|
|
788
791
|
`)}
|
|
789
|
-
`:``,stderr:u}}async function
|
|
792
|
+
`:``,stderr:u}}async function cy(e,t,n){if(t.includes(`/`)){let n=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(n))return{error:`not_found`,path:n};let r=n.split(`/`).pop()||t,i=e.commands.get(r);try{let t=await e.fs.stat(n);return t.isDirectory?{error:`permission_denied`,path:n}:i?{cmd:i,path:n}:t.mode&73?{script:!0,path:n}:{error:`permission_denied`,path:n}}catch{return{error:`not_found`,path:n}}}if(!n&&e.state.hashTable){let n=e.state.hashTable.get(t);if(n)if(await e.fs.exists(n)){let r=e.commands.get(t);if(r)return{cmd:r,path:n};try{let t=await e.fs.stat(n);if(!t.isDirectory&&t.mode&73)return{script:!0,path:n}}catch{}}else e.state.hashTable.delete(t)}let r=(n??e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`);for(let n of r){if(!n)continue;let r=`${n.startsWith(`/`)?n:e.fs.resolvePath(e.state.cwd,n)}/${t}`;if(await e.fs.exists(r))try{let i=await e.fs.stat(r);if(i.isDirectory)continue;let a=(i.mode&73)!=0,o=e.commands.get(t),s=n===`/bin`||n===`/usr/bin`;if(o&&s)return{cmd:o,path:r};if(a&&(o&&!s||!o))return{script:!0,path:r}}catch{}}if(!await e.fs.exists(`/usr/bin`)){let n=e.commands.get(t);if(n)return{cmd:n,path:`/usr/bin/${t}`}}return null}async function ly(e,t){let n=[];if(t.includes(`/`)){let r=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(r))try{let i=await e.fs.stat(r);i.isDirectory||i.mode&73&&n.push(t)}catch{}return n}let r=(e.state.env.get(`PATH`)||`/usr/bin:/bin`).split(`:`);for(let i of r){if(!i)continue;let r=`${i.startsWith(`/`)?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(await e.fs.exists(r)){try{if((await e.fs.stat(r)).isDirectory)continue}catch{continue}n.push(i.startsWith(`/`)?r:`${i}/${t}`)}}return n}function uy(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function Q(e,t,n,r){return((...i)=>{mn(t,n,`${r} call`);let a=e(...i);return uy(a)?a.then(e=>(mn(t,n,`${r} post-await`),e),e=>{throw mn(t,n,`${r} post-await`),e}):(mn(t,n,`${r} return`),a)})}function dy(e,t,n){let r={readFile:Q(e.readFile.bind(e),t,n,`fs.readFile`),readFileBuffer:Q(e.readFileBuffer.bind(e),t,n,`fs.readFileBuffer`),writeFile:Q(e.writeFile.bind(e),t,n,`fs.writeFile`),appendFile:Q(e.appendFile.bind(e),t,n,`fs.appendFile`),exists:Q(e.exists.bind(e),t,n,`fs.exists`),stat:Q(e.stat.bind(e),t,n,`fs.stat`),mkdir:Q(e.mkdir.bind(e),t,n,`fs.mkdir`),readdir:Q(e.readdir.bind(e),t,n,`fs.readdir`),rm:Q(e.rm.bind(e),t,n,`fs.rm`),cp:Q(e.cp.bind(e),t,n,`fs.cp`),mv:Q(e.mv.bind(e),t,n,`fs.mv`),resolvePath:Q(e.resolvePath.bind(e),t,n,`fs.resolvePath`),getAllPaths:Q(e.getAllPaths.bind(e),t,n,`fs.getAllPaths`),chmod:Q(e.chmod.bind(e),t,n,`fs.chmod`),symlink:Q(e.symlink.bind(e),t,n,`fs.symlink`),link:Q(e.link.bind(e),t,n,`fs.link`),readlink:Q(e.readlink.bind(e),t,n,`fs.readlink`),lstat:Q(e.lstat.bind(e),t,n,`fs.lstat`),realpath:Q(e.realpath.bind(e),t,n,`fs.realpath`),utimes:Q(e.utimes.bind(e),t,n,`fs.utimes`)};return e.readdirWithFileTypes&&(r.readdirWithFileTypes=Q(e.readdirWithFileTypes.bind(e),t,n,`fs.readdirWithFileTypes`)),r}function fy(e,t){if(!e.requireDefenseContext)return e;let n=`command:${t}`,r={...e,fs:dy(e.fs,e.requireDefenseContext,n)};return e.exec&&(r.exec=Q(e.exec,e.requireDefenseContext,n,`exec`)),e.fetch&&(r.fetch=Q(e.fetch,e.requireDefenseContext,n,`fetch`)),e.sleep&&(r.sleep=Q(e.sleep,e.requireDefenseContext,n,`sleep`)),e.getRegisteredCommands&&(r.getRegisteredCommands=Q(e.getRegisteredCommands,e.requireDefenseContext,n,`getRegisteredCommands`)),r}async function py(e,t,n,r){let i=!1,a=!1,o=!1,s=!1,c=!1,l=[];for(let e of t)if(e.startsWith(`-`)&&e.length>1)for(let t of e.slice(1))t===`t`?i=!0:t===`p`?a=!0:t===`P`?o=!0:t===`a`?s=!0:t===`f`&&(c=!0);else l.push(e);let u=``,d=``,f=0,p=!1,m=!1;for(let t of l){let l=!1;if(o){if(s){let e=await r(t);if(e.length>0){for(let t of e)u+=`${t}
|
|
790
793
|
`;p=!0,l=!0}}else{let e=await n(t);e&&(u+=`${e}
|
|
791
794
|
`,p=!0,l=!0)}l||(m=!0);continue}let f=!c&&e.state.functions.has(t);if(s&&f){if(!a)if(i)u+=`function
|
|
792
|
-
`;else{let n=e.state.functions.get(t),r=n?
|
|
795
|
+
`;else{let n=e.state.functions.get(t),r=n?my(t,n):`${t} is a function
|
|
793
796
|
`;u+=r}l=!0}let h=e.state.env.get(`BASH_ALIAS_${t}`);if(!(h!==void 0&&(s||!l)&&(a||(i?u+=`alias
|
|
794
797
|
`:u+=`${t} is aliased to \`${h}'
|
|
795
|
-
`),l=!0,!s)
|
|
798
|
+
`),l=!0,!s)||$g.has(t)&&(s||!l)&&(a||(i?u+=`keyword
|
|
796
799
|
`:u+=`${t} is a shell keyword
|
|
797
800
|
`),l=!0,!s))){if(!s&&f&&!l){if(!a)if(i)u+=`function
|
|
798
|
-
`;else{let n=e.state.functions.get(t),r=n?
|
|
799
|
-
`;u+=r}l=!0;continue}if(!(
|
|
801
|
+
`;else{let n=e.state.functions.get(t),r=n?my(t,n):`${t} is a function
|
|
802
|
+
`;u+=r}l=!0;continue}if(!(e_.has(t)&&(s||!l)&&(a||(i?u+=`builtin
|
|
800
803
|
`:u+=`${t} is a shell builtin
|
|
801
804
|
`),l=!0,!s))){if(s){let e=await r(t);for(let n of e)a?u+=`${n}
|
|
802
805
|
`:i?u+=`file
|
|
@@ -805,16 +808,16 @@ ${Mv}`;if(e.state.options.posix)throw new Xe(1,``,t);return X(t)}return Gv(e,t.s
|
|
|
805
808
|
`:i?u+=`file
|
|
806
809
|
`:u+=`${t} is ${e}
|
|
807
810
|
`,p=!0,l=!0)}if(!l&&(m=!0,!i&&!a)){let n=!0;if(t.includes(`/`)){let r=e.fs.resolvePath(e.state.cwd,t);await e.fs.exists(r)&&(n=!1)}n&&(d+=`bash: type: ${t}: not found
|
|
808
|
-
`)}}}}return f=a?m&&!p?1:0:m?1:0,Z(u,d,f)}function
|
|
811
|
+
`)}}}}return f=a?m&&!p?1:0:m?1:0,Z(u,d,f)}function my(e,t){let n;return n=t.body.type===`Group`?t.body.body.map(e=>hy(e)).join(`; `):hy(t.body),`${e} is a function
|
|
809
812
|
${e} ()
|
|
810
813
|
{
|
|
811
814
|
${n}
|
|
812
815
|
}
|
|
813
|
-
`}function
|
|
816
|
+
`}function hy(e){if(Array.isArray(e))return e.map(e=>hy(e)).join(`; `);if(e.type===`Statement`){let t=[];for(let n=0;n<e.pipelines.length;n++){let r=e.pipelines[n];t.push(gy(r)),e.operators[n]&&t.push(e.operators[n])}return t.join(` `)}if(e.type===`SimpleCommand`){let t=e,n=[];t.name&&n.push(_y(t.name));for(let e of t.args)n.push(_y(e));return n.join(` `)}return e.type===`Group`?`{ ${e.body.map(e=>hy(e)).join(`; `)}; }`:`...`}function gy(e){let t=e.commands.map(e=>hy(e));return(e.negated?`! `:``)+t.join(` | `)}function _y(e){let t=``;for(let n of e.parts)n.type===`Literal`?t+=n.value:n.type===`DoubleQuoted`?t+=`"${n.parts.map(e=>vy(e)).join(``)}"`:n.type===`SingleQuoted`?t+=`'${n.value}'`:t+=vy(n);return t}function vy(e){let t=e;return t.type===`Literal`?t.value??``:t.type===`Variable`?`$${t.name}`:``}async function yy(e,t,n,r){let i=``,a=``,o=0;for(let n of t){if(!n){o=1;continue}let t=e.state.env.get(`BASH_ALIAS_${n}`);if(t!==void 0)r?i+=`${n} is an alias for "${t}"
|
|
814
817
|
`:i+=`alias ${n}='${t}'
|
|
815
|
-
`;else if(
|
|
818
|
+
`;else if($g.has(n))r?i+=`${n} is a shell keyword
|
|
816
819
|
`:i+=`${n}
|
|
817
|
-
`;else if(
|
|
820
|
+
`;else if(e_.has(n))r?i+=`${n} is a shell builtin
|
|
818
821
|
`:i+=`${n}
|
|
819
822
|
`;else if(e.state.functions.has(n))r?i+=`${n} is a function
|
|
820
823
|
`:i+=`${n}
|
|
@@ -824,114 +827,114 @@ ${e} ()
|
|
|
824
827
|
`),o=1)}else if(e.commands.has(n)){let t=(e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`),a=null;for(let r of t){if(!r)continue;let t=`${r}/${n}`;try{let n=await e.fs.stat(t);if(!n.isDirectory&&n.mode&73){a=t;break}}catch{}}a||=`/usr/bin/${n}`,r?i+=`${n} is ${a}
|
|
825
828
|
`:i+=`${a}
|
|
826
829
|
`}else r&&(a+=`${n}: not found
|
|
827
|
-
`),o=1}return Z(i,a,o)}async function
|
|
828
|
-
`,2);e=n.slice(0,-1)}return
|
|
829
|
-
`);let[,...o]=i;return r(a,o,[],n,!0,!1,-1)}async function
|
|
830
|
+
`),o=1}return Z(i,a,o)}async function by(e,t){if(t.includes(`/`)){let n=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(n)){try{let t=await e.fs.stat(n);if(t.isDirectory||!(t.mode&73))return null}catch{return null}return t}return null}let n=(e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`);for(let r of n){if(!r)continue;let n=`${r.startsWith(`/`)?r:e.fs.resolvePath(e.state.cwd,r)}/${t}`;if(await e.fs.exists(n)){try{if((await e.fs.stat(n)).isDirectory)continue}catch{continue}return`${r}/${t}`}}if(e.commands.has(t)){for(let e of n)if(e===`/usr/bin`||e===`/bin`)return`${e}/${t}`;return`/usr/bin/${t}`}return null}async function xy(e,t,n,r,i,a,o,s){let{ctx:c,runCommand:l}=e;if(c.coverage&&e_.has(t)&&c.coverage.hit(`bash:builtin:${t}`),t===`export`)return _v(c,n);if(t===`unset`)return ty(c,n);if(t===`exit`)return gv(c,n);if(t===`local`)return Dv(c,n);if(t===`set`)return Gv(c,n);if(t===`break`)return ng(c,n);if(t===`continue`)return R_(c,n);if(t===`return`)return Mv(c,n);if(t===`eval`&&c.state.options.posix)return hv(c,n,i);if(t===`shift`)return qv(c,n);if(t===`getopts`)return vv(c,n);if(t===`compgen`)return g_(c,n);if(t===`complete`)return P_(c,n);if(t===`compopt`)return L_(c,n);if(t===`pushd`)return await fv(c,n);if(t===`popd`)return pv(c,n);if(t===`dirs`)return mv(c,n);if(t===`source`||t===`.`)return Jv(c,n);if(t===`read`)return jv(c,n,i,s);if(t===`mapfile`||t===`readarray`)return Ov(c,n,i);if(t===`declare`||t===`typeset`)return sv(c,n);if(t===`readonly`)return cv(c,n);if(!a){let e=c.state.functions.get(t);if(e)return d_(c,e,n,i)}if(t===`eval`)return hv(c,n,i);if(t===`cd`)return await rg(c,n);if(t===`:`||t===`true`)return J;if(t===`false`)return $h(!1);if(t===`let`)return Ev(c,n);if(t===`command`)return Sy(e,n,i);if(t===`builtin`)return Cy(e,n,i);if(t===`shopt`)return oy(c,n);if(t===`exec`){if(n.length===0)return J;let[e,...t]=n;return l(e,t,[],i,!1,!1,-1)}if(t===`wait`)return J;if(t===`type`)return await py(c,n,e=>by(c,e),e=>ly(c,e));if(t===`hash`)return yv(c,n);if(t===`help`)return Sv(c,n);if(t===`[`||t===`test`){let e=n;if(t===`[`){if(n[n.length-1]!==`]`)return X(`[: missing \`]'
|
|
831
|
+
`,2);e=n.slice(0,-1)}return xg(c,e)}return null}async function Sy(e,t,n){let{ctx:r,runCommand:i}=e;if(t.length===0)return J;let a=!1,o=!1,s=!1,c=t;for(;c.length>0&&c[0].startsWith(`-`);){let e=c[0];if(e===`--`){c=c.slice(1);break}for(let t of e.slice(1))t===`p`?a=!0:t===`V`?o=!0:t===`v`&&(s=!0);c=c.slice(1)}if(c.length===0)return J;if(s||o)return await yy(r,c,s,o);let[l,...u]=c;return i(l,u,[],n,!0,a,-1)}async function Cy(e,t,n){let{runCommand:r}=e;if(t.length===0)return J;let i=t;if(i[0]===`--`&&(i=i.slice(1),i.length===0))return J;let a=i[0];if(!e_.has(a))return X(`bash: builtin: ${a}: not a shell builtin
|
|
832
|
+
`);let[,...o]=i;return r(a,o,[],n,!0,!1,-1)}async function wy(e,t,n,r,i){let{ctx:a,buildExportedEnv:o,executeUserScript:s}=e,c=await cy(a,t,i?`/usr/bin:/bin`:void 0);if(!c)return Qh(t)?X(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
|
|
830
833
|
`,127):X(`bash: ${t}: command not found
|
|
831
834
|
`,127);if(`error`in c)return c.error===`permission_denied`?X(`bash: ${t}: Permission denied
|
|
832
835
|
`,126):X(`bash: ${t}: No such file or directory
|
|
833
|
-
`,127);if(`script`in c)return t.includes(`/`)||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,c.path)),await s(c.path,n,r);let{cmd:l,path:u}=c;t.includes(`/`)||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,u));let d=r||a.state.groupStdin||``,f=o(),p=
|
|
834
|
-
`)}}async function
|
|
835
|
-
`,exitCode:1}}async function
|
|
836
|
-
`,exitCode:1}}return{stdout:i,stderr:a,exitCode:o}}async function
|
|
837
|
-
`);let s=[];if(t.words===null)s=(e.state.env.get(`@`)||``).split(` `).filter(Boolean);else if(t.words.length===0)s=[];else try{for(let n of t.words){let t=await
|
|
836
|
+
`,127);if(`script`in c)return t.includes(`/`)||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,c.path)),await s(c.path,n,r);let{cmd:l,path:u}=c;t.includes(`/`)||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,u));let d=r||a.state.groupStdin||``,f=o(),p=fy({fs:a.fs,cwd:a.state.cwd,env:a.state.env,exportedEnv:f,stdin:d,limits:a.limits,exec:a.execFn,fetch:a.fetch,getRegisteredCommands:()=>Array.from(a.commands.keys()),sleep:a.sleep,trace:a.trace,fileDescriptors:a.state.fileDescriptors,xpgEcho:a.state.shoptOptions.xpg_echo,coverage:a.coverage,signal:a.state.signal,requireDefenseContext:a.requireDefenseContext,jsBootstrapCode:a.jsBootstrapCode},t);try{let e=()=>pn(a.requireDefenseContext,`command`,`${t} execution`,()=>l.execute(n,p));return l.trusted?await sn.runTrustedAsync(()=>e()):await e()}catch(e){if(e instanceof Xe||e instanceof on)throw e;return X(`${t}: ${hn(gn(e))}
|
|
837
|
+
`)}}async function Ty(e,t){let n=e.state.inCondition;e.state.inCondition=!0;let r=``,i=``,a=0;try{for(let n of t){let t=await e.executeStatement(n);r+=t.stdout,i+=t.stderr,a=t.exitCode}}finally{e.state.inCondition=n}return{stdout:r,stderr:i,exitCode:a}}function Ey(e,t,n,r){if(e instanceof Ge)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:`rethrow`,stdout:t,stderr:n,error:e}):{action:`break`,stdout:t,stderr:n};if(e instanceof nt)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:`rethrow`,stdout:t,stderr:n,error:e}):{action:`continue`,stdout:t,stderr:n};if(e instanceof Ze||e instanceof tt||e instanceof et||e instanceof Xe)return e.prependOutput(t,n),{action:`rethrow`,stdout:t,stderr:n,error:e};let i=gn(e);return{action:`error`,stdout:t,stderr:`${n}${i}
|
|
838
|
+
`,exitCode:1}}async function Dy(e,t,n=``,r=``){let i=n,a=r,o=0;try{for(let n of t){let t=await e.executeStatement(n);i+=t.stdout,a+=t.stderr,o=t.exitCode}}catch(e){if(Qe(e)||e instanceof tt||e instanceof et||e instanceof Xe||e instanceof rt)throw e.prependOutput(i,a),e;return{stdout:i,stderr:`${a}${gn(e)}
|
|
839
|
+
`,exitCode:1}}return{stdout:i,stderr:a,exitCode:o}}async function Oy(e,t){let n=``,r=``;for(let i of t.clauses){let t=await Ty(e,i.condition);if(n+=t.stdout,r+=t.stderr,t.exitCode===0)return Dy(e,i.body,n,r)}return t.elseBody?Dy(e,t.elseBody,n,r):Z(n,r,0)}async function ky(e,t){let n=await s_(e,t.redirections);if(n)return n;let r=``,i=``,a=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return X(`bash: \`${t.variable}': not a valid identifier
|
|
840
|
+
`);let s=[];if(t.words===null)s=(e.state.env.get(`@`)||``).split(` `).filter(Boolean);else if(t.words.length===0)s=[];else try{for(let n of t.words){let t=await Gt(e,n);s.push(...t.values)}}catch(e){if(e instanceof Ke)return{stdout:``,stderr:e.stderr,exitCode:1};throw e}e.state.loopDepth++;try{for(let n of s){o++,o>e.limits.maxLoopIterations&&eg(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,r,i),e.state.env.set(t.variable,n);try{for(let n of t.body){let t=await e.executeStatement(n);r+=t.stdout,i+=t.stderr,a=t.exitCode}}catch(n){let a=Ey(n,r,i,e.state.loopDepth);if(r=a.stdout,i=a.stderr,a.action===`break`)break;if(a.action===`continue`)continue;if(a.action===`error`)return c_(e,Z(r,i,a.exitCode??1),t.redirections);throw a.error}}}finally{e.state.loopDepth--}return c_(e,Z(r,i,a),t.redirections)}async function Ay(e,t){let n=await s_(e,t.redirections);if(n)return n;let r=t.line;r!==void 0&&(e.state.currentLine=r);let i=``,a=``,o=0,s=0;t.init&&await It(e,t.init.expression),e.state.loopDepth++;try{for(;s++,s>e.limits.maxLoopIterations&&eg(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,i,a),!(t.condition&&(r!==void 0&&(e.state.currentLine=r),await It(e,t.condition.expression)===0));){try{for(let n of t.body){let t=await e.executeStatement(n);i+=t.stdout,a+=t.stderr,o=t.exitCode}}catch(n){let r=Ey(n,i,a,e.state.loopDepth);if(i=r.stdout,a=r.stderr,r.action===`break`)break;if(r.action===`continue`){t.update&&await It(e,t.update.expression);continue}if(r.action===`error`)return c_(e,Z(i,a,r.exitCode??1),t.redirections);throw r.error}t.update&&await It(e,t.update.expression)}}finally{e.state.loopDepth--}return c_(e,Z(i,a,o),t.redirections)}async function jy(e,t,n=``){let r=``,i=``,a=0,o=0,s=n;for(let n of t.redirections)if((n.operator===`<<`||n.operator===`<<-`)&&n.target.type===`HereDoc`){let t=n.target,r=await E(e,t.content);t.stripTabs&&(r=r.split(`
|
|
838
841
|
`).map(e=>e.replace(/^\t+/,``)).join(`
|
|
839
|
-
`)),s=r}else if(n.operator===`<<<`&&n.target.type===`Word`)s=`${await
|
|
840
|
-
`;else if(n.operator===`<`&&n.target.type===`Word`)try{let t=await
|
|
841
|
-
`)}let c=e.state.groupStdin;s&&(e.state.groupStdin=s),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations
|
|
842
|
-
`,t||
|
|
842
|
+
`)),s=r}else if(n.operator===`<<<`&&n.target.type===`Word`)s=`${await E(e,n.target)}
|
|
843
|
+
`;else if(n.operator===`<`&&n.target.type===`Word`)try{let t=await E(e,n.target),r=e.fs.resolvePath(e.state.cwd,t);s=await e.fs.readFile(r)}catch{return X(`bash: ${await E(e,n.target)}: No such file or directory
|
|
844
|
+
`)}let c=e.state.groupStdin;s&&(e.state.groupStdin=s),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&eg(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,r,i);let n=0,s=!1,c=!1,l=e.state.inCondition;e.state.inCondition=!0;try{for(let a of t.condition){let t=await e.executeStatement(a);r+=t.stdout,i+=t.stderr,n=t.exitCode}}catch(t){if(t instanceof Ge){if(r+=t.stdout,i+=t.stderr,t.levels>1&&e.state.loopDepth>1)throw t.levels--,t.stdout=r,t.stderr=i,e.state.inCondition=l,t;s=!0}else if(t instanceof nt){if(r+=t.stdout,i+=t.stderr,t.levels>1&&e.state.loopDepth>1)throw t.levels--,t.stdout=r,t.stderr=i,e.state.inCondition=l,t;c=!0}else throw e.state.inCondition=l,t}finally{e.state.inCondition=l}if(s)break;if(!c){if(n!==0)break;try{for(let n of t.body){let t=await e.executeStatement(n);r+=t.stdout,i+=t.stderr,a=t.exitCode}}catch(t){let n=Ey(t,r,i,e.state.loopDepth);if(r=n.stdout,i=n.stderr,n.action===`break`)break;if(n.action===`continue`)continue;if(n.action===`error`)return Z(r,i,n.exitCode??1);throw n.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=c}return Z(r,i,a)}async function My(e,t){let n=``,r=``,i=0,a=0;e.state.loopDepth++;try{for(;;){a++,a>e.limits.maxLoopIterations&&eg(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,n,r);let o=await Ty(e,t.condition);if(n+=o.stdout,r+=o.stderr,o.exitCode===0)break;try{for(let a of t.body){let t=await e.executeStatement(a);n+=t.stdout,r+=t.stderr,i=t.exitCode}}catch(t){let i=Ey(t,n,r,e.state.loopDepth);if(n=i.stdout,r=i.stderr,i.action===`break`)break;if(i.action===`continue`)continue;if(i.action===`error`)return Z(n,r,i.exitCode??1);throw i.error}}}finally{e.state.loopDepth--}return Z(n,r,i)}async function Ny(e,t){let n=await s_(e,t.redirections);if(n)return n;let r=``,i=``,a=0,o=await E(e,t.word),s=!1;for(let n=0;n<t.items.length;n++){let c=t.items[n],l=s;if(!s)for(let t of c.patterns){let n=await E(e,t);zt(t)&&(n=yt(n));let r=e.state.shoptOptions.nocasematch,i=e.state.shoptOptions.extglob;if(Dg(o,n,r,i)){l=!0;break}}if(l){let t=await Dy(e,c.body,r,i);if(r=t.stdout,i=t.stderr,a=t.exitCode,c.terminator===`;;`)break;s=c.terminator===`;&`}else s=!1}return c_(e,Z(r,i,a),t.redirections)}function Py(e,t){if(e.parts.length!==1)return!1;let n=e.parts[0];return n.type===`Literal`?t.includes(n.value):!1}function Fy(e){if(!e.startsWith(`__rw__:`))return null;let t=e.slice(7),n=t.indexOf(`:`);if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let i=n+1,a=t.slice(i,i+r),o=i+r+1,s=t.slice(o),c=s.indexOf(`:`);if(c===-1)return null;let l=Number.parseInt(s.slice(0,c),10);return Number.isNaN(l)||l<0?null:{path:a,position:l,content:s.slice(c+1)}}var Iy=`+ `;async function Ly(e){let t=e.state.env.get(`PS4`);if(t===void 0)return Iy;if(t===``)return``;try{return await E(e,new Vt().parseWordFromString(t,!1,!1))}catch{return e.state.expansionStderr=`${e.state.expansionStderr||``}bash: ${t}: bad substitution
|
|
845
|
+
`,t||Iy}}function Ry(e){return e.map(e=>zy(e)).join(` `)}function zy(e){if(e===``)return`''`;if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let t=/[\x00-\x1f\x7f]/.test(e),n=e.includes(`
|
|
843
846
|
`),r=e.includes(` `),i=e.includes(`\\`),a=e.includes(`'`);if(t||n||r||i){let t=``;for(let n of e){let e=n.charCodeAt(0);n===`
|
|
844
|
-
`?t+=`\\n`:n===` `?t+=`\\t`:n===`\\`?t+=`\\\\`:n===`'`?t+=`'`:n===`"`?t+=`"`:e<32||e===127?e<256?t+=`\\x${e.toString(16).padStart(2,`0`)}`:t+=`\\u${e.toString(16).padStart(4,`0`)}`:t+=n}return`$'${t}'`}return a?`"${e.replace(/([\\$`"])/g,`\\$1`)}"`:`'${e}'`}async function
|
|
845
|
-
`:``}async function
|
|
846
|
-
`:``}async function
|
|
847
|
+
`?t+=`\\n`:n===` `?t+=`\\t`:n===`\\`?t+=`\\\\`:n===`'`?t+=`'`:n===`"`?t+=`"`:e<32||e===127?e<256?t+=`\\x${e.toString(16).padStart(2,`0`)}`:t+=`\\u${e.toString(16).padStart(4,`0`)}`:t+=n}return`$'${t}'`}return a?`"${e.replace(/([\\$`"])/g,`\\$1`)}"`:`'${e}'`}async function By(e,t,n){return e.state.options.xtrace?`${await Ly(e)}${Ry([t,...n])}
|
|
848
|
+
`:``}async function Vy(e,t,n){return e.state.options.xtrace?`${await Ly(e)}${t}=${n}
|
|
849
|
+
`:``}async function Hy(e,t,n){let r=t.timed?an():0,i=``,a=J,o=0,s=[],c=``,l=t.commands.length>1,u=e.state.lastArg;for(let r=0;r<t.commands.length;r++){let u=t.commands[r],d=r===t.commands.length-1,f=r===0;l&&(e.state.lastArg=``,f||(e.state.groupStdin=void 0));let p=l&&(!d||!e.state.shoptOptions.lastpipe)?new Map(e.state.env):null,m;try{m=await n(u,i)}catch(n){if(n instanceof at)m={stdout:n.stdout,stderr:n.stderr,exitCode:1};else if(n instanceof et&&t.commands.length>1)m={stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode};else if(n instanceof tt&&t.commands.length>1)m={stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode};else throw p&&(e.state.env=p),n}p&&(e.state.env=p),s.push(m.exitCode),m.exitCode!==0&&(o=m.exitCode),d?a=m:(t.pipeStderr?.[r]??!1?i=m.stderr+m.stdout:(i=m.stdout,c+=m.stderr),a={stdout:``,stderr:``,exitCode:m.exitCode})}if(c&&(a={...a,stderr:c+a.stderr}),t.commands.length>1||t.commands.length===1&&t.commands[0].type===`SimpleCommand`){for(let t of e.state.env.keys())t.startsWith(`PIPESTATUS_`)&&e.state.env.delete(t);for(let t=0;t<s.length;t++)e.state.env.set(`PIPESTATUS_${t}`,String(s[t]));e.state.env.set(`PIPESTATUS__length`,String(s.length))}if(e.state.options.pipefail&&o!==0&&(a={...a,exitCode:o}),t.negated&&(a={...a,exitCode:a.exitCode===0?1:0}),t.timed){let e=(an()-r)/1e3,n=Math.floor(e/60),i=e%60,o;o=t.timePosix?`real ${e.toFixed(2)}
|
|
847
850
|
user 0.00
|
|
848
851
|
sys 0.00
|
|
849
852
|
`:`
|
|
850
853
|
real ${`${n}m${i.toFixed(3)}s`}
|
|
851
854
|
user 0m0.000s
|
|
852
855
|
sys 0m0.000s
|
|
853
|
-
`,a={...a,stderr:a.stderr+o}}return l&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=u),a}async function
|
|
854
|
-
`,1)};let s=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let a=await
|
|
855
|
-
`,1)};if(
|
|
856
|
-
`,1)}}if(
|
|
857
|
-
`,{continueToNext:!0,xtraceOutput:o};let r=
|
|
858
|
-
`)}async function
|
|
859
|
-
`,1)};s=t}}if(
|
|
860
|
-
`;if(t.fatal)throw new
|
|
856
|
+
`,a={...a,stderr:a.stderr+o}}return l&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=u),a}async function Uy(e,t){let n=new Map,r=``;for(let i of t.assignments){let a=i.name;if(i.array){let o=await Wy(e,t,a,i.array,i.append,n);if(o.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:o.error};if(r+=o.xtraceOutput,o.continueToNext)continue}let o=i.value?await E(e,i.value):``;if(a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:Z(``,`bash: ${a}: bad array subscript
|
|
857
|
+
`,1)};let s=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let a=await Yy(e,t,s[1],s[2],o,i.append,n);if(a.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:a.error};if(a.continueToNext)continue}let c=await Qy(e,t,a,o,i.append,n);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:c.error};r+=c.xtraceOutput,c.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:n}}async function Wy(e,t,n,r,i,a){let o=``;if(/\[.+\]$/.test(n))return{continueToNext:!1,xtraceOutput:``,error:Z(``,`bash: ${n}: cannot assign list to array member
|
|
858
|
+
`,1)};if(wt(e,n)){let t=Nt(e,n);if(t===void 0||t===``)throw new et(1,``,``);let r=At(e,n);if(r&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(r))return{continueToNext:!1,xtraceOutput:``,error:Z(``,`bash: ${n}: cannot assign list to array member
|
|
859
|
+
`,1)}}if(st(e,n)){if(t.name)return o+=`bash: ${n}: readonly variable
|
|
860
|
+
`,{continueToNext:!0,xtraceOutput:o};let r=lt(e,n);if(r)return{continueToNext:!1,xtraceOutput:``,error:r}}let s=e.state.associativeArrays?.has(n),c=Gy(r),l=()=>{let t=`${n}_`;for(let n of e.state.env.keys())n.startsWith(t)&&!n.includes(`__`)&&e.state.env.delete(n);e.state.env.delete(n)};if(s&&c?await Ky(e,t,n,r,i,l,e=>{o+=e}):c?await qy(e,n,r,i,l):await Jy(e,n,r,i,l),t.name){a.set(n,e.state.env.get(n));let t=`(${r.map(e=>kt(e)).join(` `)})`;e.state.env.set(n,t)}return{continueToNext:!0,xtraceOutput:o}}function Gy(e){return e.some(e=>{if(e.parts.length>=2){let t=e.parts[0],n=e.parts[1];if(t.type!==`Glob`||!t.pattern.startsWith(`[`))return!1;if(t.pattern===`[`&&(n.type===`DoubleQuoted`||n.type===`SingleQuoted`)){if(e.parts.length<3)return!1;let t=e.parts[2];return t.type===`Literal`?t.value.startsWith(`]=`)||t.value.startsWith(`]+=`):!1}return n.type===`Literal`?n.value.startsWith(`]`)?n.value.startsWith(`]=`)||n.value.startsWith(`]+=`):t.pattern.endsWith(`]`)?n.value.startsWith(`=`)||n.value.startsWith(`+=`):!1:!1}return!1})}async function Ky(e,t,n,r,i,a,o){let s=[];for(let t of r){let n=Bt(t);if(n){let{key:t,valueParts:r,append:i}=n,a;a=r.length>0?await E(e,{type:`Word`,parts:r}):``,a=z_(e,a),s.push({type:`keyed`,key:t,value:a,append:i})}else{let n=await E(e,t);s.push({type:`invalid`,expandedValue:n})}}i||a();for(let r of s)if(r.type===`keyed`)if(r.append){let t=e.state.env.get(`${n}_${r.key}`)??``;e.state.env.set(`${n}_${r.key}`,t+r.value)}else e.state.env.set(`${n}_${r.key}`,r.value);else o(`bash: line ${t.line??e.state.currentLine??1}: ${n}: ${r.expandedValue}: must use subscript when assigning associative array
|
|
861
|
+
`)}async function qy(e,t,n,r,i){let a=[];for(let t of n){let n=Bt(t);if(n){let{key:t,valueParts:r,append:i}=n,o;o=r.length>0?await E(e,{type:`Word`,parts:r}):``,o=z_(e,o),a.push({type:`keyed`,indexExpr:t,value:o,append:i})}else{let n=await Gt(e,t);a.push({type:`non-keyed`,values:n.values})}}r||i();let o=0;for(let n of a)if(n.type===`keyed`){let r;try{r=await It(e,Tt(new Vt,n.indexExpr).expression,!1)}catch{if(/^-?\d+$/.test(n.indexExpr))r=Number.parseInt(n.indexExpr,10);else{let t=e.state.env.get(n.indexExpr);r=t?Number.parseInt(t,10):0,Number.isNaN(r)&&(r=0)}}if(n.append){let i=e.state.env.get(`${t}_${r}`)??``;e.state.env.set(`${t}_${r}`,i+n.value)}else e.state.env.set(`${t}_${r}`,n.value);o=r+1}else for(let r of n.values)e.state.env.set(`${t}_${o++}`,r)}async function Jy(e,t,n,r,i){let a=[];for(let t of n){let n=await Gt(e,t);a.push(...n.values)}let o=0;if(r){let n=Et(e,t);if(n.length>0)o=Math.max(...n.map(([e])=>typeof e==`number`?e:0))+1;else{let n=e.state.env.get(t);n!==void 0&&(e.state.env.set(`${t}_0`,n),e.state.env.delete(t),o=1)}}else i();for(let n=0;n<a.length;n++)e.state.env.set(`${t}_${o+n}`,a[n]);r||e.state.env.set(`${t}__length`,String(a.length))}async function Yy(e,t,n,r,i,a,o){let s=n;if(wt(e,n)){let t=At(e,n);if(t&&t!==n){if(t.includes(`[`))return{continueToNext:!1,xtraceOutput:``,error:Z(``,`bash: \`${t}': not a valid identifier
|
|
862
|
+
`,1)};s=t}}if(st(e,s)){if(t.name)return{continueToNext:!0,xtraceOutput:``};let n=lt(e,s);if(n)return{continueToNext:!1,xtraceOutput:``,error:n}}let c=e.state.associativeArrays?.has(s),l;if(c)l=await Xy(e,s,r);else{let t=await Zy(e,s,r);if(t.error)return{continueToNext:!1,xtraceOutput:``,error:t.error};l=`${s}_${t.index}`}let u=a?(e.state.env.get(l)||``)+i:i;if(t.name)o.set(l,e.state.env.get(l)),e.state.env.set(l,u);else{let t=Kg(e,s);if(t!==void 0&&t===e.state.callDepth&&e.state.localScopes.length>0){let t=e.state.localScopes[e.state.localScopes.length-1];t.has(l)||t.set(l,e.state.env.get(l))}e.state.env.set(l,u)}return{continueToNext:!0,xtraceOutput:``}}async function Xy(e,t,n){let r;if(n.startsWith(`'`)&&n.endsWith(`'`))r=n.slice(1,-1);else if(n.startsWith(`"`)&&n.endsWith(`"`)){let t=n.slice(1,-1);r=await E(e,new Vt().parseWordFromString(t,!0,!1))}else r=n.includes(`$`)?await E(e,new Vt().parseWordFromString(n,!1,!1)):n;return`${t}_${r}`}async function Zy(e,t,n){let r=n;n.startsWith(`"`)&&n.endsWith(`"`)&&n.length>=2&&(r=n.slice(1,-1));let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{i=await It(e,Tt(new Vt,r).expression,!1)}catch(t){if(t instanceof Je){let r=`bash: line ${e.state.currentLine}: ${n}: ${t.message}
|
|
863
|
+
`;if(t.fatal)throw new et(1,``,r);return{index:0,error:Z(``,r,1)}}let r=e.state.env.get(n);i=r?Number.parseInt(r,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let r=Et(e,t);if(r.length===0){let r=e.state.currentLine;return{index:0,error:Z(``,`bash: line ${r}: ${t}[${n}]: bad array subscript
|
|
861
864
|
`,1)}}if(i=Math.max(...r.map(([e])=>typeof e==`number`?e:0))+1+i,i<0){let r=e.state.currentLine;return{index:0,error:Z(``,`bash: line ${r}: ${t}[${n}]: bad array subscript
|
|
862
|
-
`,1)}}}return{index:i}}async function
|
|
863
|
-
`,1)};if(t===null)return{continueToNext:!0,xtraceOutput:``};s=t;let i=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);i&&(c={arrayName:i[1],subscriptExpr:i[2]},s=i[1])}if(
|
|
864
|
-
`,{continueToNext:!0,xtraceOutput:o};let n=
|
|
865
|
-
`,1),t.redirections)}return x(),
|
|
865
|
+
`,1)}}}return{index:i}}async function Qy(e,t,n,r,i,a){let o=``,s=n,c=null;if(wt(e,n)){let t=ft(e,n,r);if(t===void 0)return{continueToNext:!1,xtraceOutput:``,error:Z(``,`bash: ${n}: circular name reference
|
|
866
|
+
`,1)};if(t===null)return{continueToNext:!0,xtraceOutput:``};s=t;let i=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);i&&(c={arrayName:i[1],subscriptExpr:i[2]},s=i[1])}if(st(e,s)){if(t.name)return o+=`bash: ${s}: readonly variable
|
|
867
|
+
`,{continueToNext:!0,xtraceOutput:o};let n=lt(e,s);if(n)return{continueToNext:!1,xtraceOutput:``,error:n}}let l;if($_(e,s))try{let t=new Vt;if(i){let n=Tt(t,`(${e.state.env.get(s)||`0`}) + (${r})`);l=String(await It(e,n.expression))}else{let n=Tt(t,r);l=String(await It(e,n.expression))}}catch{l=`0`}else{let{isArray:t}=await import(`./expansion-ENLSRCXJ-BBTiIHJS.mjs`),n=t(e,s)?`${s}_0`:s;l=i?(e.state.env.get(n)||``)+r:r}l=iv(e,s,l),o+=await Vy(e,s,l);let u=s;if(c)u=await $y(e,c);else{let{isArray:t}=await import(`./expansion-ENLSRCXJ-BBTiIHJS.mjs`);t(e,s)&&(u=`${s}_0`)}return t.name?(a.set(u,e.state.env.get(u)),e.state.env.set(u,l)):(e.state.env.set(u,l),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(s)),e.state.tempEnvBindings?.some(e=>e.has(s))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(s))),{continueToNext:!1,xtraceOutput:o}}async function $y(e,t){let{arrayName:n,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(n))return Xy(e,n,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{i=await It(e,Tt(new Vt,r).expression,!1)}catch{let t=e.state.env.get(r);i=t?Number.parseInt(t,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let t=Et(e,n);t.length>0&&(i=Math.max(...t.map(e=>e[0]))+1+i)}return`${n}_${i}`}async function eb(e,t,n,r){let i=await s_(e,t.redirections);if(i)return i;let a=new Map(e.state.env),o=e.state.cwd,s={...e.state.options},c=new Map(e.state.functions),l=e.state.localScopes,u=e.state.localVarStack,d=e.state.localVarDepth,f=e.state.fullyUnsetLocals;if(e.state.localScopes=l.map(e=>new Map(e)),u){e.state.localVarStack=new Map;for(let[t,n]of u.entries())e.state.localVarStack.set(t,n.map(e=>({...e})))}d&&(e.state.localVarDepth=new Map(d)),f&&(e.state.fullyUnsetLocals=new Map(f));let p=e.state.loopDepth,m=e.state.parentHasLoopContext;e.state.parentHasLoopContext=p>0,e.state.loopDepth=0;let h=e.state.lastArg,g=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let _=e.state.groupStdin;n&&(e.state.groupStdin=n);let v=``,y=``,b=0,x=()=>{e.state.env=a,e.state.cwd=o,e.state.options=s,e.state.functions=c,e.state.localScopes=l,e.state.localVarStack=u,e.state.localVarDepth=d,e.state.fullyUnsetLocals=f,e.state.loopDepth=p,e.state.parentHasLoopContext=m,e.state.groupStdin=_,e.state.bashPid=g,e.state.lastArg=h};try{for(let e of t.body){let t=await r(e);v+=t.stdout,y+=t.stderr,b=t.exitCode}}catch(n){if(x(),n instanceof Xe)throw n;return n instanceof rt||n instanceof Ge||n instanceof nt?(v+=n.stdout,y+=n.stderr,c_(e,Z(v,y,0),t.redirections)):n instanceof et||n instanceof Ze?(v+=n.stdout,y+=n.stderr,c_(e,Z(v,y,n.exitCode),t.redirections)):n instanceof tt?c_(e,Z(v+n.stdout,y+n.stderr,n.exitCode),t.redirections):c_(e,Z(v,`${y}${gn(n)}
|
|
868
|
+
`,1),t.redirections)}return x(),c_(e,Z(v,y,b),t.redirections)}async function tb(e,t,n,r){let i=``,a=``,o=0,s=await o_(e,t.redirections);if(s)return s;let c=n;for(let n of t.redirections)if((n.operator===`<<`||n.operator===`<<-`)&&n.target.type===`HereDoc`){let t=n.target,r=await E(e,t.content);t.stripTabs&&(r=r.split(`
|
|
866
869
|
`).map(e=>e.replace(/^\t+/,``)).join(`
|
|
867
|
-
`));let i=n.fd??0;i===0?c=r:(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),
|
|
868
|
-
`;else if(n.operator===`<`&&n.target.type===`Word`)try{let t=await
|
|
869
|
-
`,1)}let l=e.state.groupStdin;c&&(e.state.groupStdin=c);try{for(let e of t.body){let t=await r(e);i+=t.stdout,a+=t.stderr,o=t.exitCode}}catch(t){if(e.state.groupStdin=l,t instanceof
|
|
870
|
-
`,1)}return e.state.groupStdin=l,
|
|
870
|
+
`));let i=n.fd??0;i===0?c=r:(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),tg(e),e.state.fileDescriptors.set(i,r))}else if(n.operator===`<<<`&&n.target.type===`Word`)c=`${await E(e,n.target)}
|
|
871
|
+
`;else if(n.operator===`<`&&n.target.type===`Word`)try{let t=await E(e,n.target),r=e.fs.resolvePath(e.state.cwd,t);c=await e.fs.readFile(r)}catch{return Z(``,`bash: ${await E(e,n.target)}: No such file or directory
|
|
872
|
+
`,1)}let l=e.state.groupStdin;c&&(e.state.groupStdin=c);try{for(let e of t.body){let t=await r(e);i+=t.stdout,a+=t.stderr,o=t.exitCode}}catch(t){if(e.state.groupStdin=l,t instanceof Xe)throw t;if(Qe(t)||t instanceof tt||t instanceof et)throw t.prependOutput(i,a),t;return Z(i,`${a}${gn(t)}
|
|
873
|
+
`,1)}return e.state.groupStdin=l,c_(e,Z(i,a,o),t.redirections)}async function nb(e,t,n,r,i){let a;try{a=await e.fs.readFile(t)}catch{return X(`bash: ${t}: No such file or directory
|
|
871
874
|
`,127)}if(a.startsWith(`#!`)){let e=a.indexOf(`
|
|
872
|
-
`);e!==-1&&(a=a.slice(e+1))}let o=new Map(e.state.env),s=e.state.cwd,c={...e.state.options},l=e.state.loopDepth,u=e.state.parentHasLoopContext,d=e.state.lastArg,f=e.state.bashPid,p=e.state.groupStdin,m=e.state.currentSource;e.state.parentHasLoopContext=l>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,r&&(e.state.groupStdin=r),e.state.currentSource=t,e.state.env.set(`0`,t),e.state.env.set(`#`,String(n.length)),e.state.env.set(`@`,n.join(` `)),e.state.env.set(`*`,n.join(` `));for(let t=0;t<n.length&&t<9;t++)e.state.env.set(String(t+1),n[t]);for(let t=n.length+1;t<=9;t++)e.state.env.delete(String(t));let h=()=>{e.state.env=o,e.state.cwd=s,e.state.options=c,e.state.loopDepth=l,e.state.parentHasLoopContext=u,e.state.lastArg=d,e.state.bashPid=f,e.state.groupStdin=p,e.state.currentSource=m};try{let e=await i(new
|
|
873
|
-
`);throw e}}var
|
|
874
|
-
`);let r=0,i=-1,a=!1;for(let o=0;o<e.pipelines.length;o++){let s=e.pipelines[o],c=o>0?e.operators[o-1]:null;if(c===`&&`&&r!==0||c===`||`&&r===0)continue;let l=await this.executePipeline(s);t+=l.stdout,n+=l.stderr,r=l.exitCode,i=o,a=s.negated,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r))}let o=i<e.pipelines.length-1,s=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=o||a||s,this.ctx.state.options.errexit&&r!==0&&i===e.pipelines.length-1&&!a&&!this.ctx.state.inCondition&&!s)throw new
|
|
875
|
+
`);e!==-1&&(a=a.slice(e+1))}let o=new Map(e.state.env),s=e.state.cwd,c={...e.state.options},l=e.state.loopDepth,u=e.state.parentHasLoopContext,d=e.state.lastArg,f=e.state.bashPid,p=e.state.groupStdin,m=e.state.currentSource;e.state.parentHasLoopContext=l>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,r&&(e.state.groupStdin=r),e.state.currentSource=t,e.state.env.set(`0`,t),e.state.env.set(`#`,String(n.length)),e.state.env.set(`@`,n.join(` `)),e.state.env.set(`*`,n.join(` `));for(let t=0;t<n.length&&t<9;t++)e.state.env.set(String(t+1),n[t]);for(let t=n.length+1;t<=9;t++)e.state.env.delete(String(t));let h=()=>{e.state.env=o,e.state.cwd=s,e.state.options=c,e.state.loopDepth=l,e.state.parentHasLoopContext=u,e.state.lastArg=d,e.state.bashPid=f,e.state.groupStdin=p,e.state.currentSource=m};try{let e=await i(new Vt().parse(a));return h(),e}catch(e){if(h(),e instanceof et||e instanceof Xe)throw e;if(e.name===`ParseException`)return X(`bash: ${t}: ${e.message}
|
|
876
|
+
`);throw e}}var rb=class{ctx;constructor(e,t){this.ctx={state:t,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep,trace:e.trace,coverage:e.coverage,requireDefenseContext:e.requireDefenseContext??!1,jsBootstrapCode:e.jsBootstrapCode}}assertDefenseContext(e){if(!this.ctx.requireDefenseContext||sn.isInSandboxedContext())return;let t=`interpreter ${e} attempted outside defense context`;throw new on(t,{timestamp:Date.now(),type:`missing_defense_context`,message:t,path:`DefenseInDepthBox.context`,stack:Error().stack,executionId:sn.getCurrentExecutionId()})}buildExportedEnv(){let e=this.ctx.state.exportedVars,t=this.ctx.state.tempExportedVars,n=new Set;if(e)for(let t of e)n.add(t);if(t)for(let e of t)n.add(e);if(n.size===0)return Object.create(null);let r=Object.create(null);for(let e of n){let t=this.ctx.state.env.get(e);t!==void 0&&(r[e]=t)}return r}async executeScript(e){this.assertDefenseContext(`execution`);let t=``,n=``,r=0,i=this.ctx.limits.maxOutputSize,a=(e,r)=>{t.length+n.length+e.length+r.length>i&&eg(`total output size exceeded (>${i} bytes), increase executionLimits.maxOutputSize`,`output_size`),t+=e,n+=r};for(let i of e.statements)try{let e=await this.executeStatement(i);a(e.stdout,e.stderr),r=e.exitCode,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r))}catch(e){if(e instanceof et)throw e.prependOutput(t,n),e;if(e instanceof $e)return a(e.stdout,e.stderr),r=e.exitCode,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r)),{stdout:t,stderr:n,exitCode:r,env:dn(this.ctx.state.env)};if(e instanceof Xe)throw e;if(e instanceof tt)return a(e.stdout,e.stderr),r=e.exitCode,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r)),{stdout:t,stderr:n,exitCode:r,env:dn(this.ctx.state.env)};if(e instanceof Ye||e instanceof at)return a(e.stdout,e.stderr),r=1,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r)),{stdout:t,stderr:n,exitCode:r,env:dn(this.ctx.state.env)};if(e instanceof Je){a(e.stdout,e.stderr),r=1,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r));continue}if(e instanceof qe){a(e.stdout,e.stderr),r=1,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r));continue}if(e instanceof Ge||e instanceof nt){if(this.ctx.state.loopDepth>0)throw e.prependOutput(t,n),e;a(e.stdout,e.stderr);continue}throw e instanceof Ze&&e.prependOutput(t,n),e}return{stdout:t,stderr:n,exitCode:r,env:dn(this.ctx.state.env)}}async executeUserScript(e,t,n=``){return nb(this.ctx,e,t,n,e=>this.executeScript(e))}async executeStatement(e){if(this.assertDefenseContext(`statement`),this.ctx.state.signal?.aborted)throw new it;if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&eg(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,`commands`),e.deferredError)throw new Rt(e.deferredError.message,e.line??1,1);if(this.ctx.state.options.noexec)return J;this.ctx.state.errexitSafe=!1;let t=``,n=``;this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&e.sourceText&&(n+=`${e.sourceText}
|
|
877
|
+
`);let r=0,i=-1,a=!1;for(let o=0;o<e.pipelines.length;o++){let s=e.pipelines[o],c=o>0?e.operators[o-1]:null;if(c===`&&`&&r!==0||c===`||`&&r===0)continue;let l=await this.executePipeline(s);t+=l.stdout,n+=l.stderr,r=l.exitCode,i=o,a=s.negated,this.ctx.state.lastExitCode=r,this.ctx.state.env.set(`?`,String(r))}let o=i<e.pipelines.length-1,s=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=o||a||s,this.ctx.state.options.errexit&&r!==0&&i===e.pipelines.length-1&&!a&&!this.ctx.state.inCondition&&!s)throw new tt(r,t,n);return Z(t,n,r)}async executePipeline(e){return Hy(this.ctx,e,(e,t)=>this.executeCommand(e,t))}async executeCommand(e,t){switch(this.assertDefenseContext(`command`),this.ctx.coverage?.hit(`bash:cmd:${e.type}`),e.type){case`SimpleCommand`:return this.executeSimpleCommand(e,t);case`If`:return Oy(this.ctx,e);case`For`:return ky(this.ctx,e);case`CStyleFor`:return Ay(this.ctx,e);case`While`:return jy(this.ctx,e,t);case`Until`:return My(this.ctx,e);case`Case`:return Ny(this.ctx,e);case`Subshell`:return this.executeSubshell(e,t);case`Group`:return this.executeGroup(e,t);case`FunctionDef`:return l_(this.ctx,e);case`ArithmeticCommand`:return this.executeArithmeticCommand(e);case`ConditionalCommand`:return this.executeConditionalCommand(e);default:return J}}async executeSimpleCommand(e,t){try{return await this.executeSimpleCommandInner(e,t)}catch(e){if(e instanceof Ke)return X(e.stderr);throw e}}async executeSimpleCommandInner(e,t){if(e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.shoptOptions.expand_aliases&&e.name){let t=e,n=100;for(;n>0;){let e=this.expandAlias(t);if(e===t)break;t=e,n--}this.aliasExpansionStack.clear(),t!==e&&(e=t)}this.ctx.state.expansionStderr=``;let n=await Uy(this.ctx,e);if(n.error)return n.error;let r=n.tempAssignments,i=n.xtraceOutput;if(!e.name){if(e.redirections.length>0){let t=await s_(this.ctx,e.redirections);if(t)return t;let n=Z(``,i,0);return c_(this.ctx,n,e.redirections)}this.ctx.state.lastArg=``;let t=(this.ctx.state.expansionStderr||``)+i;return this.ctx.state.expansionStderr=``,Z(``,t,this.ctx.state.lastExitCode)}let a=e.name&&Py(e.name,[`local`,`declare`,`typeset`,`export`,`readonly`]),o=Array.from(r.keys());if(o.length>0&&!a){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let e of o)this.ctx.state.tempExportedVars.add(e)}let s=await o_(this.ctx,e.redirections);if(s){for(let[e,t]of r)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);return s}let c=-1;for(let n of e.redirections){if((n.operator===`<<`||n.operator===`<<-`)&&n.target.type===`HereDoc`){let e=n.target,r=await E(this.ctx,e.content);e.stripTabs&&(r=r.split(`
|
|
875
878
|
`).map(e=>e.replace(/^\t+/,``)).join(`
|
|
876
|
-
`));let i=n.fd??0;i===0?t=r:(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),
|
|
877
|
-
`;continue}if(n.operator===`<`&&n.target.type===`Word`)try{let e=await
|
|
878
|
-
`)}if(n.operator===`<&`&&n.target.type===`Word`){let e=await
|
|
879
|
-
`,127)}if(l===`exec`&&(u.length===0||u[0]===`--`)){for(let t of e.redirections){if(t.target.type===`HereDoc`||t.fdVariable)continue;let e=await
|
|
880
|
-
`)}break}case`<>`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);try{let e=await this.ctx.fs.readFile(t);
|
|
881
|
-
`);return
|
|
882
|
-
`,n);return
|
|
879
|
+
`));let i=n.fd??0;i===0?t=r:(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),tg(this.ctx),this.ctx.state.fileDescriptors.set(i,r));continue}if(n.operator===`<<<`&&n.target.type===`Word`){t=`${await E(this.ctx,n.target)}
|
|
880
|
+
`;continue}if(n.operator===`<`&&n.target.type===`Word`)try{let e=await E(this.ctx,n.target),r=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);t=await this.ctx.fs.readFile(r)}catch{let e=await E(this.ctx,n.target);for(let[e,t]of r)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);return X(`bash: ${e}: No such file or directory
|
|
881
|
+
`)}if(n.operator===`<&`&&n.target.type===`Word`){let e=await E(this.ctx,n.target),r=Number.parseInt(e,10);if(!Number.isNaN(r)&&this.ctx.state.fileDescriptors){let e=this.ctx.state.fileDescriptors.get(r);if(e!==void 0)if(e.startsWith(`__rw__:`)){let n=Fy(e);n&&(t=n.content.slice(n.position),c=r)}else e.startsWith(`__file__:`)||e.startsWith(`__file_append__:`)||(t=e)}}}let l=await E(this.ctx,e.name),u=[],d=[];if(Py(e.name,[`local`,`declare`,`typeset`,`export`,`readonly`])&&(l===`local`||l===`declare`||l===`typeset`||l===`export`||l===`readonly`))for(let t of e.args){let e=await Yh(this.ctx,t);if(e)u.push(e),d.push(!0);else{let e=await Xh(this.ctx,t);if(e!==null)u.push(e),d.push(!0);else{let e=await Gt(this.ctx,t);for(let t of e.values)u.push(t),d.push(e.quoted)}}}else for(let t of e.args){let e=await Gt(this.ctx,t);for(let t of e.values)u.push(t),d.push(e.quoted)}if(!l){if(e.name.parts.every(e=>e.type===`CommandSubstitution`||e.type===`ParameterExpansion`||e.type===`ArithmeticExpansion`)){if(u.length>0){let e=u.shift();return d.shift(),await this.runCommand(e,u,d,t,!1,!1,c)}return Z(``,``,this.ctx.state.lastExitCode)}return X(`bash: : command not found
|
|
882
|
+
`,127)}if(l===`exec`&&(u.length===0||u[0]===`--`)){for(let t of e.redirections){if(t.target.type===`HereDoc`||t.fdVariable)continue;let e=await E(this.ctx,t.target),n=t.fd??(t.operator===`<`||t.operator===`<>`?0:1);switch(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),t.operator){case`>`:case`>|`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);await this.ctx.fs.writeFile(t,``,`utf8`),tg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__file__:${t}`);break}case`>>`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);tg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__file_append__:${t}`);break}case`<`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);try{let e=await this.ctx.fs.readFile(t);tg(this.ctx),this.ctx.state.fileDescriptors.set(n,e)}catch{return X(`bash: ${e}: No such file or directory
|
|
883
|
+
`)}break}case`<>`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);try{let e=await this.ctx.fs.readFile(t);tg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__rw__:${t.length}:${t}:0:${e}`)}catch{await this.ctx.fs.writeFile(t,``,`utf8`),tg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__rw__:${t.length}:${t}:0:`)}break}case`>&`:if(e===`-`)this.ctx.state.fileDescriptors.delete(n);else if(e.endsWith(`-`)){let t=e.slice(0,-1),r=Number.parseInt(t,10);if(!Number.isNaN(r)){let e=this.ctx.state.fileDescriptors.get(r);e===void 0?this.ctx.state.fileDescriptors.set(n,`__dupout__:${r}`):this.ctx.state.fileDescriptors.set(n,e),this.ctx.state.fileDescriptors.delete(r)}}else{let t=Number.parseInt(e,10);Number.isNaN(t)||(tg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__dupout__:${t}`))}break;case`<&`:if(e===`-`)this.ctx.state.fileDescriptors.delete(n);else if(e.endsWith(`-`)){let t=e.slice(0,-1),r=Number.parseInt(t,10);if(!Number.isNaN(r)){let e=this.ctx.state.fileDescriptors.get(r);e===void 0?this.ctx.state.fileDescriptors.set(n,`__dupin__:${r}`):this.ctx.state.fileDescriptors.set(n,e),this.ctx.state.fileDescriptors.delete(r)}}else{let t=Number.parseInt(e,10);Number.isNaN(t)||(tg(this.ctx),this.ctx.state.fileDescriptors.set(n,`__dupin__:${t}`))}break}}for(let[e,t]of r)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);if(this.ctx.state.tempExportedVars)for(let e of r.keys())this.ctx.state.tempExportedVars.delete(e);return J}if(this.ctx.state.extraArgs){u.push(...this.ctx.state.extraArgs);for(let e=0;e<this.ctx.state.extraArgs.length;e++)d.push(!0);this.ctx.state.extraArgs=void 0}let f=await By(this.ctx,l,u);r.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(r)));let p,m=null;try{p=await this.runCommand(l,u,d,t,!1,!1,c)}catch(e){if(e instanceof Ge||e instanceof nt)m=e,p=J;else throw e}let h=i+f;if(h&&(p={...p,stderr:h+p.stderr}),p=await c_(this.ctx,p,e.redirections),m)throw m;if(u.length>0){let e=u[u.length-1];if((l===`declare`||l===`local`||l===`typeset`)&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(e)){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);t&&(e=t[1])}this.ctx.state.lastArg=e}else this.ctx.state.lastArg=l;let g=Qg(l)&&l!==`unset`&&l!==`eval`;if(!this.ctx.state.options.posix||!g)for(let[e,t]of r)this.ctx.state.fullyUnsetLocals?.has(e)||(t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t));if(this.ctx.state.tempExportedVars)for(let e of r.keys())this.ctx.state.tempExportedVars.delete(e);return r.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(p={...p,stderr:this.ctx.state.expansionStderr+p.stderr},this.ctx.state.expansionStderr=``),p}async runCommand(e,t,n,r,i=!1,a=!1,o=-1){let s={ctx:this.ctx,runCommand:(e,t,n,r,i,a,o)=>this.runCommand(e,t,n,r,i,a,o),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(e,t,n)=>this.executeUserScript(e,t,n)},c=await xy(s,e,t,n,r,i,a,o);return c===null?wy(s,e,t,r,a):c}aliasExpansionStack=new Set;expandAlias(e){return Kh(this.ctx.state,e,this.aliasExpansionStack)}async findCommandInPath(e){return ly(this.ctx,e)}async executeSubshell(e,t=``){return eb(this.ctx,e,t,e=>this.executeStatement(e))}async executeGroup(e,t=``){return tb(this.ctx,e,t,e=>this.executeStatement(e))}async executeArithmeticCommand(e){e.line!==void 0&&(this.ctx.state.currentLine=e.line);let t=await s_(this.ctx,e.redirections);if(t)return t;try{let t=$h(await It(this.ctx,e.expression.expression)!==0);return this.ctx.state.expansionStderr&&(t={...t,stderr:this.ctx.state.expansionStderr+t.stderr},this.ctx.state.expansionStderr=``),c_(this.ctx,t,e.redirections)}catch(t){let n=X(`bash: arithmetic expression: ${t.message}
|
|
884
|
+
`);return c_(this.ctx,n,e.redirections)}}async executeConditionalCommand(e){e.line!==void 0&&(this.ctx.state.currentLine=e.line);let t=await s_(this.ctx,e.redirections);if(t)return t;try{let t=$h(await bg(this.ctx,e.expression));return this.ctx.state.expansionStderr&&(t={...t,stderr:this.ctx.state.expansionStderr+t.stderr},this.ctx.state.expansionStderr=``),c_(this.ctx,t,e.redirections)}catch(t){let n=t instanceof Je?1:2,r=X(`bash: conditional expression: ${t.message}
|
|
885
|
+
`,n);return c_(this.ctx,r,e.redirections)}}},ib={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxBraceExpansionResults:1e4,maxOutputSize:10485760,maxFileDescriptors:1024,maxSourceDepth:100};function ab(e){return e?{maxCallDepth:e.maxCallDepth??ib.maxCallDepth,maxCommandCount:e.maxCommandCount??ib.maxCommandCount,maxLoopIterations:e.maxLoopIterations??ib.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??ib.maxAwkIterations,maxSedIterations:e.maxSedIterations??ib.maxSedIterations,maxJqIterations:e.maxJqIterations??ib.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??ib.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??ib.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??ib.maxJsTimeoutMs,maxGlobOperations:e.maxGlobOperations??ib.maxGlobOperations,maxStringLength:e.maxStringLength??ib.maxStringLength,maxArrayElements:e.maxArrayElements??ib.maxArrayElements,maxHeredocSize:e.maxHeredocSize??ib.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??ib.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??ib.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??ib.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??ib.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??ib.maxSourceDepth}:{...ib}}function ob(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function sb(e){let t=ob(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function cb(e){if(e.includes(`\\`))return!0;let t=e.toLowerCase();return t.includes(`%2f`)||t.includes(`%5c`)}function lb(e,t){return t===`/`||t===``?!0:t.endsWith(`/`)?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function ub(e,t){let n=ob(e);if(!n)return!1;let r=sb(t);return!r||n.origin!==r.origin||r.pathPrefix!==`/`&&r.pathPrefix!==``&&cb(n.pathname)?!1:lb(n.pathname,r.pathPrefix)}function db(e){return typeof e==`string`?e:e.url}function fb(e,t){return!t||t.length===0?!1:t.some(t=>ub(e,db(t)))}function pb(e){let t=mb(e);if(t===`localhost`||t.endsWith(`.localhost`))return!0;let n=gb(t);if(n)return vb(n);let r=_b(t);return r?yb(r):!1}function mb(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function hb(e){if(!e)return null;let t=10,n=e;if(n.startsWith(`0x`)||n.startsWith(`0X`)?(t=16,n=n.slice(2)):n.length>1&&n.startsWith(`0`)&&(t=8),!n||t===16&&!/^[0-9a-fA-F]+$/.test(n)||t===10&&!/^\d+$/.test(n)||t===8&&!/^[0-7]+$/.test(n))return null;let r=Number.parseInt(n,t);return!Number.isFinite(r)||r<0?null:r}function gb(e){let t=e.split(`.`);if(t.length===0||t.length>4)return null;let n=t.map(e=>hb(e));if(n.some(e=>e===null))return null;let r=n;if(t.length===1){let e=r[0];return e>4294967295?null:[e>>>24&255,e>>>16&255,e>>>8&255,e&255]}if(t.length===2){let[e,t]=r;return e>255||t>16777215?null:[e,t>>>16&255,t>>>8&255,t&255]}if(t.length===3){let[e,t,n]=r;return e>255||t>255||n>65535?null:[e,t,n>>>8&255,n&255]}let[i,a,o,s]=r;return i>255||a>255||o>255||s>255?null:[i,a,o,s]}function _b(e){let t=e,n=null;if(t.includes(`.`)){let e=t.lastIndexOf(`:`);if(e<0)return null;let r=gb(t.slice(e+1));if(!r)return null;n=r,t=t.slice(0,e)}let r=t.includes(`::`)?t.split(`::`).length-1:0;if(r>1)return null;let[i,a]=t.split(`::`),o=i?i.split(`:`).filter(Boolean):[],s=a?a.split(`:`).filter(Boolean):[],c=e=>/^[0-9a-f]{1,4}$/i.test(e)?Number.parseInt(e,16):null,l=o.map(c),u=s.map(c);if(l.some(e=>e===null)||u.some(e=>e===null))return null;let d=n?2:0,f=l.length+u.length+d,p=0;if(r===1){if(p=8-f,p<0)return null}else if(f!==8)return null;let m=[...l,...Array(p).fill(0),...u];return n&&(m.push(n[0]<<8|n[1]),m.push(n[2]<<8|n[3])),m.length===8?m:null}function vb(e){let[t,n]=e;return t===127||t===10||t===172&&n>=16&&n<=31||t===192&&n===168||t===169&&n===254||t===0||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===192&&n===0&&e[2]===0||t===192&&n===0&&e[2]===2||t===198&&n===51&&e[2]===100||t===203&&n===0&&e[2]===113||t>=240}function yb(e){return e.every(e=>e===0)||e.slice(0,7).every(e=>e===0)&&e[7]===1||(e[0]&65472)==65152||(e[0]&65024)==64512?!0:e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535?vb([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===8193&&e[1]===3512?!0:e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0?vb([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===100&&e[1]===65435&&e[2]===1?!0:e[0]===8194?vb([e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255]):!1}function bb(e){let t=[];for(let n of e){if(typeof n!=`string`&&(typeof n!=`object`||!n||!(`url`in n)||typeof n.url!=`string`)){t.push(`Invalid allow-list entry: must be a string URL or an object with a "url" string property`);continue}let e=db(n);if(!ob(e)){t.push(`Invalid URL in allow-list: "${e}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let r=new URL(e);if(r.protocol!==`http:`&&r.protocol!==`https:`){t.push(`Only http and https URLs are allowed in allow-list: "${e}"`);continue}if(!r.hostname){t.push(`Allow-list entry must include a hostname: "${e}"`);continue}if(r.pathname!==`/`&&r.pathname!==``&&cb(r.pathname)){t.push(`Allow-list entry contains ambiguous path separators: "${e}"`);continue}(r.search||r.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: "${e}"`)}return t}var xb=class extends Error{constructor(e,t){super(`Network access denied: ${t??`URL not in allow-list`}: ${e}`),this.name=`NetworkAccessDeniedError`}},Sb=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name=`TooManyRedirectsError`}},Cb=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name=`RedirectNotAllowedError`}},wb=class extends Error{constructor(e,t){super(`HTTP method '${e}' not allowed. Allowed methods: ${t.join(`, `)}`),this.name=`MethodNotAllowedError`}},Tb=class extends Error{constructor(e){super(`Response body too large (max: ${e} bytes)`),this.name=`ResponseTooLargeError`}};function Eb(e){return new Promise((t,n)=>{rr(e,{all:!0},(e,r)=>{e?n(e):t(r)})})}var Db=20,Ob=3e4,kb=10485760,Ab=[`GET`,`HEAD`],jb=new Set([`GET`,`HEAD`,`OPTIONS`]),Mb=new Set([301,302,303,307,308]);function Nb(e){let t=e.allowedUrlPrefixes??[];if(!e.dangerouslyAllowFullInternetAccess){let e=bb(t);if(e.length>0)throw Error(`Invalid network allow-list:
|
|
883
886
|
${e.join(`
|
|
884
|
-
`)}`)}let n=[];for(let e of t)typeof e==`object`&&e.transform&&e.transform.length>0&&n.push(e);function r(e){if(n.length===0)return null;let t=null;for(let r of n)if(
|
|
885
|
-
`)}function
|
|
886
|
-
${i}${n.delimiter}`}return e.operator===`<<<`?`${t}<<< ${
|
|
887
|
-
`)}function
|
|
888
|
-
${
|
|
889
|
-
${
|
|
887
|
+
`)}`)}let n=[];for(let e of t)typeof e==`object`&&e.transform&&e.transform.length>0&&n.push(e);function r(e){if(n.length===0)return null;let t=null;for(let r of n)if(ub(e,r.url)&&r.transform){t||=new Headers;for(let e of r.transform)for(let[n,r]of Object.entries(e.headers))t.set(n,r)}return t}let i=e.maxRedirects??Db,a=e.timeoutMs??Ob,o=e.maxResponseSize??kb,s=e.dangerouslyAllowFullInternetAccess?[`GET`,`HEAD`,`POST`,`PUT`,`DELETE`,`PATCH`,`OPTIONS`]:e.allowedMethods??Ab,c=e.denyPrivateRanges??(typeof process<`u`&&process.env?.NODE_ENV===`production`),l=e._dnsResolve??Eb;async function u(n){if(!e.dangerouslyAllowFullInternetAccess&&!fb(n,t))throw new xb(n);if(c)try{let e=new URL(n);if(pb(e.hostname))throw new xb(n,`private/loopback IP address blocked`);let t=e.hostname;if(/[a-zA-Z]/.test(t))try{let e=await l(t);for(let{address:t}of e)if(pb(t))throw new xb(n,`hostname resolves to private/loopback IP address`)}catch(e){if(e instanceof xb)throw e;let t=e?.code;if(!(t===`ENOTFOUND`||t===`ENODATA`))throw new xb(n,`DNS resolution failed for private IP check`)}}catch(e){if(e instanceof xb)throw e}}function d(t){if(e.dangerouslyAllowFullInternetAccess)return;let n=t.toUpperCase();if(!s.includes(n))throw new wb(n,s)}async function f(e,t={}){let n=t.method?.toUpperCase()??`GET`;await u(e),d(n);let s=e,c=0,l=t.followRedirects??!0,f=t.timeoutMs===void 0?a:Math.min(t.timeoutMs,a);for(;;){let e=new AbortController,a=ln(()=>e.abort(),f);try{let a=await sn.runTrustedAsync(()=>{let i=r(s),a={method:n,headers:Pb(t.headers,i),signal:e.signal,redirect:`manual`};return t.body&&!jb.has(n)&&(a.body=t.body),fetch(s,a)});if(Mb.has(a.status)&&l){let e=a.headers.get(`location`);if(!e)return await Fb(a,s,o);let t=new URL(e,s).href;try{await u(t)}catch{throw new Cb(t)}if(c++,c>i)throw new Sb(i);s=t;continue}return await Fb(a,s,o)}finally{cn(a)}}}return f}function Pb(e,t){if(!e&&!t)return;if(!t)return e;let n=(e instanceof Headers,new Headers(e));for(let[e,r]of t)n.set(e,r);return n}async function Fb(e,t,n){let r=Object.create(null);if(e.headers.forEach((e,t)=>{r[t.toLowerCase()]=e}),n>0){let t=e.headers.get(`content-length`);if(t){let e=parseInt(t,10);if(!Number.isNaN(e)&&e>n)throw new Tb(n)}}let i;if(n>0&&e.body){let t=e.body.getReader(),r=[],a=0;for(;;){let{done:e,value:i}=await t.read();if(e)break;if(i){if(a+=i.byteLength,a>n)throw t.cancel(),new Tb(n);r.push(i)}}i=new Uint8Array(a);let o=0;for(let e of r)i.set(e,o),o+=e.byteLength}else{let t=await e.arrayBuffer();if(n>0&&t.byteLength>n)throw new Tb(n);i=new Uint8Array(t)}return{status:e.status,statusText:e.statusText,headers:r,body:i,url:t}}function Ib(e){return Lb(e)}function Lb(e){return e.statements.map(Rb).join(`
|
|
888
|
+
`)}function Rb(e){let t=[];for(let n=0;n<e.pipelines.length;n++)t.push(zb(e.pipelines[n])),n<e.operators.length&&t.push(e.operators[n]);let n=t.join(` `);return e.background&&(n+=` &`),n}function zb(e){let t=[];e.timed&&t.push(e.timePosix?`time -p`:`time`),e.negated&&t.push(`!`);let n=[];for(let t=0;t<e.commands.length;t++)if(n.push(Bb(e.commands[t])),t<e.commands.length-1){let r=e.pipeStderr?.[t];n.push(r?`|&`:`|`)}return(t.length>0?`${t.join(` `)} `:``)+n.join(` `)}function Bb(e){switch(e.type){case`SimpleCommand`:return Vb(e);case`If`:return ix(e);case`For`:return ax(e);case`CStyleFor`:return ox(e);case`While`:return sx(e);case`Until`:return cx(e);case`Case`:return lx(e);case`Subshell`:return dx(e);case`Group`:return fx(e);case`ArithmeticCommand`:return px(e);case`ConditionalCommand`:return mx(e);case`FunctionDef`:return hx(e);default:throw Error(`Unsupported command type: ${e.type}`)}}function Vb(e){let t=[];for(let n of e.assignments)t.push(Hb(n));e.name&&t.push(Ub(e.name));for(let n of e.args)t.push(Ub(n));for(let n of e.redirections)t.push(tx(n));return t.join(` `)}function Hb(e){let t=e.append?`+=`:`=`;if(e.array){let n=e.array.map(Ub).join(` `);return`${e.name}${t}(${n})`}return e.value?`${e.name}${t}${Ub(e.value)}`:`${e.name}${t}`}function Ub(e){return e.parts.map(e=>Gb(e,!1)).join(``)}function Wb(e){return e.parts.map(e=>Gb(e,!0)).join(``)}function Gb(e,t){switch(e.type){case`Literal`:return t?qb(e.value):Kb(e.value);case`SingleQuoted`:return`'${e.value}'`;case`DoubleQuoted`:return`"${e.parts.map(e=>Gb(e,!0)).join(``)}"`;case`Escaped`:return`\\${e.value}`;case`ParameterExpansion`:return Xb(e);case`CommandSubstitution`:return e.legacy?`\`${Lb(e.body)}\``:`$(${Lb(e.body)})`;case`ArithmeticExpansion`:return`$((${$(e.expression.expression)}))`;case`ProcessSubstitution`:return e.direction===`input`?`<(${Lb(e.body)})`:`>(${Lb(e.body)})`;case`BraceExpansion`:return $b(e);case`TildeExpansion`:return e.user===null?`~`:`~${e.user}`;case`Glob`:return e.pattern;default:throw Error(`Unsupported word part type: ${e.type}`)}}function Kb(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,`\\$&`)}function qb(e){return e.replace(/[$`"\\]/g,`\\$&`)}function Jb(e,t){return e.parts.map(e=>Yb(e,t)).join(``)}function Yb(e,t){switch(e.type){case`Literal`:return t?e.value:e.value.replace(/[$`]/g,`\\$&`);case`Escaped`:return`\\${e.value}`;case`ParameterExpansion`:return Xb(e);case`CommandSubstitution`:return e.legacy?`\`${Lb(e.body)}\``:`$(${Lb(e.body)})`;case`ArithmeticExpansion`:return`$((${$(e.expression.expression)}))`;default:return Gb(e,!1)}}function Xb(e){return e.operation?`\${${Qb(e.parameter,e.operation)}}`:Zb(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function Zb(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function Qb(e,t){switch(t.type){case`Length`:return`#${e}`;case`LengthSliceError`:return`#${e}:`;case`BadSubstitution`:return t.text;case`DefaultValue`:return`${e}${t.checkEmpty?`:`:``}-${Wb(t.word)}`;case`AssignDefault`:return`${e}${t.checkEmpty?`:`:``}=${Wb(t.word)}`;case`ErrorIfUnset`:return`${e}${t.checkEmpty?`:`:``}?${t.word?Wb(t.word):``}`;case`UseAlternative`:return`${e}${t.checkEmpty?`:`:``}+${Wb(t.word)}`;case`Substring`:{let n=$(t.offset.expression);return t.length?`${e}:${n}:${$(t.length.expression)}`:`${e}:${n}`}case`PatternRemoval`:{let n=t.side===`prefix`?`#`:`%`;return`${e}${t.greedy?`${n}${n}`:n}${Wb(t.pattern)}`}case`PatternReplacement`:{let n=`/`;t.all?n=`//`:t.anchor===`start`?n=`/#`:t.anchor===`end`&&(n=`/%`);let r=t.replacement?`/${Wb(t.replacement)}`:``;return`${e}${n}${Wb(t.pattern)}${r}`}case`CaseModification`:{let n=t.direction===`upper`?`^`:`,`;return`${e}${t.all?`${n}${n}`:n}${t.pattern?Wb(t.pattern):``}`}case`Transform`:return`${e}@${t.operator}`;case`Indirection`:return t.innerOp?`!${Qb(e,t.innerOp)}`:`!${e}`;case`ArrayKeys`:return`!${t.array}[${t.star?`*`:`@`}]`;case`VarNamePrefix`:return`!${t.prefix}${t.star?`*`:`@`}`;default:throw Error(`Unsupported parameter operation type: ${t.type}`)}}function $b(e){return`{${e.items.map(ex).join(`,`)}}`}function ex(e){if(e.type===`Word`)return Ub(e.word);let t=e.startStr??String(e.start),n=e.endStr??String(e.end);return e.step===void 0?`${t}..${n}`:`${t}..${n}..${e.step}`}function tx(e){let t=e.fdVariable?`{${e.fdVariable}}`:e.fd===null?``:String(e.fd);if(e.operator===`<<`||e.operator===`<<-`){let n=e.target,r=n.quoted?`'${n.delimiter}'`:n.delimiter,i=Jb(n.content,n.quoted);return`${t}${e.operator}${r}
|
|
889
|
+
${i}${n.delimiter}`}return e.operator===`<<<`?`${t}<<< ${Ub(e.target)}`:e.operator===`&>`||e.operator===`&>>`?`${e.operator} ${Ub(e.target)}`:`${t}${e.operator} ${Ub(e.target)}`}function nx(e){return e.length===0?``:` ${e.map(tx).join(` `)}`}function rx(e){return e.map(Rb).join(`
|
|
890
|
+
`)}function ix(e){let t=[];for(let n=0;n<e.clauses.length;n++){let r=e.clauses[n],i=n===0?`if`:`elif`;t.push(`${i} ${rx(r.condition)}; then
|
|
891
|
+
${rx(r.body)}`)}return e.elseBody&&t.push(`else
|
|
892
|
+
${rx(e.elseBody)}`),`${t.join(`
|
|
890
893
|
`)}
|
|
891
|
-
fi${
|
|
892
|
-
${
|
|
893
|
-
done${
|
|
894
|
-
${
|
|
895
|
-
done${
|
|
896
|
-
${
|
|
897
|
-
done${
|
|
898
|
-
${
|
|
899
|
-
done${
|
|
900
|
-
`);return`case ${
|
|
894
|
+
fi${nx(e.redirections)}`}function ax(e){let t;if(e.words===null)t=`for ${e.variable}`;else{let n=e.words.map(Ub).join(` `);t=`for ${e.variable} in ${n}`}return`${t}; do
|
|
895
|
+
${rx(e.body)}
|
|
896
|
+
done${nx(e.redirections)}`}function ox(e){return`for ((${e.init?$(e.init.expression):``}; ${e.condition?$(e.condition.expression):``}; ${e.update?$(e.update.expression):``})); do
|
|
897
|
+
${rx(e.body)}
|
|
898
|
+
done${nx(e.redirections)}`}function sx(e){return`while ${rx(e.condition)}; do
|
|
899
|
+
${rx(e.body)}
|
|
900
|
+
done${nx(e.redirections)}`}function cx(e){return`until ${rx(e.condition)}; do
|
|
901
|
+
${rx(e.body)}
|
|
902
|
+
done${nx(e.redirections)}`}function lx(e){let t=e.items.map(ux).join(`
|
|
903
|
+
`);return`case ${Ub(e.word)} in
|
|
901
904
|
${t}
|
|
902
|
-
esac${
|
|
905
|
+
esac${nx(e.redirections)}`}function ux(e){let t=e.patterns.map(Ub).join(` | `),n=rx(e.body);return n?`${t})
|
|
903
906
|
${n}
|
|
904
907
|
${e.terminator}`:`${t})
|
|
905
|
-
${e.terminator}`}function
|
|
906
|
-
`],[`OSTYPE`,`linux-gnu`],[`MACHTYPE`,`x86_64-pc-linux-gnu`],[`HOSTTYPE`,`x86_64`],[`HOSTNAME`,`localhost`],[`PWD`,n],[`OLDPWD`,n],[`OPTIND`,`1`],...Object.entries(e.env??{})]);if(this.limits=
|
|
908
|
+
${e.terminator}`}function dx(e){return`(${rx(e.body)})${nx(e.redirections)}`}function fx(e){return`{ ${rx(e.body)}; }${nx(e.redirections)}`}function px(e){return`((${$(e.expression.expression)}))${nx(e.redirections)}`}function mx(e){return`[[ ${gx(e.expression)} ]]${nx(e.redirections)}`}function hx(e){let t=Bb(e.body);return`${e.name}() ${t}${nx(e.redirections)}`}function $(e){switch(e.type){case`ArithNumber`:return String(e.value);case`ArithVariable`:return e.hasDollarPrefix?`$${e.name}`:e.name;case`ArithSpecialVar`:return`$${e.name}`;case`ArithBinary`:return`${$(e.left)} ${e.operator} ${$(e.right)}`;case`ArithUnary`:return e.prefix?`${e.operator}${$(e.operand)}`:`${$(e.operand)}${e.operator}`;case`ArithTernary`:return`${$(e.condition)} ? ${$(e.consequent)} : ${$(e.alternate)}`;case`ArithAssignment`:return`${e.subscript?`${e.variable}[${$(e.subscript)}]`:e.stringKey===void 0?e.variable:`${e.variable}[${e.stringKey}]`} ${e.operator} ${$(e.value)}`;case`ArithDynamicAssignment`:return`${e.subscript?`${$(e.target)}[${$(e.subscript)}]`:$(e.target)} ${e.operator} ${$(e.value)}`;case`ArithDynamicElement`:return`${$(e.nameExpr)}[${$(e.subscript)}]`;case`ArithGroup`:return`(${$(e.expression)})`;case`ArithNested`:return`$((${$(e.expression)}))`;case`ArithCommandSubst`:return`$(${e.command})`;case`ArithBracedExpansion`:return`\${${e.content}}`;case`ArithArrayElement`:return e.stringKey===void 0?e.index?`${e.array}[${$(e.index)}]`:e.array:`${e.array}[${e.stringKey}]`;case`ArithDynamicBase`:return`\${${e.baseExpr}}#${e.value}`;case`ArithDynamicNumber`:return`\${${e.prefix}}${e.suffix}`;case`ArithConcat`:return e.parts.map($).join(``);case`ArithDoubleSubscript`:return`${e.array}[${$(e.index)}]`;case`ArithNumberSubscript`:return`${e.number}[${e.errorToken}]`;case`ArithSyntaxError`:return e.errorToken;case`ArithSingleQuote`:return`'${e.content}'`;default:throw Error(`Unsupported arithmetic expression type: ${e.type}`)}}function gx(e){switch(e.type){case`CondBinary`:return`${Ub(e.left)} ${e.operator} ${Ub(e.right)}`;case`CondUnary`:return`${e.operator} ${Ub(e.operand)}`;case`CondNot`:return`! ${gx(e.operand)}`;case`CondAnd`:return`${gx(e.left)} && ${gx(e.right)}`;case`CondOr`:return`${gx(e.left)} || ${gx(e.right)}`;case`CondGroup`:return`( ${gx(e.expression)} )`;case`CondWord`:return Ub(e.word);default:throw Error(`Unsupported conditional expression type: ${e.type}`)}}var _x=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;transformPlugins=[];state;constructor(e={}){let t=e.fs??new kh(e.files);this.fs=t,this.useDefaultLayout=!e.cwd&&!e.files;let n=e.cwd||(this.useDefaultLayout?`/home/user`:`/`),r=new Map([[`HOME`,this.useDefaultLayout?`/home/user`:`/`],[`PATH`,`/usr/bin:/bin`],[`IFS`,`
|
|
909
|
+
`],[`OSTYPE`,`linux-gnu`],[`MACHTYPE`,`x86_64-pc-linux-gnu`],[`HOSTTYPE`,`x86_64`],[`HOSTNAME`,`localhost`],[`PWD`,n],[`OLDPWD`,n],[`OPTIND`,`1`],...Object.entries(e.env??{})]);if(this.limits=ab({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}}),e.fetch?this.secureFetch=e.fetch:e.network&&(this.secureFetch=Nb(e.network)),this.sleepFn=e.sleep,this.traceFn=e.trace,this.logger=e.logger,this.defenseInDepthConfig=e.defenseInDepth??!0,this.coverageWriter=e.coverage,this.state={env:r,cwd:n,previousDir:`/home/user`,functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:``,startTime:Date.now(),lastBackgroundPid:0,virtualPid:e.processInfo?.pid??1,virtualPpid:e.processInfo?.ppid??0,virtualUid:e.processInfo?.uid??1e3,virtualGid:e.processInfo?.gid??1e3,bashPid:e.processInfo?.pid??1,nextVirtualPid:(e.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set([`HOME`,`PATH`,`PWD`,`OLDPWD`,...Object.keys(e.env||{})]),readonlyVars:new Set([`SHELLOPTS`,`BASHOPTS`]),hashTable:new Map},this.state.env.set(`SHELLOPTS`,Lh(this.state.options)),this.state.env.set(`BASHOPTS`,Bh(this.state.shoptOptions)),Ph(t,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),n!==`/`&&t instanceof kh)try{t.mkdirSync(n,{recursive:!0})}catch{}for(let t of xh(e.commands))this.registerCommand(t);if(e.fetch||e.network)for(let e of Sh())this.registerCommand(e);if(e.python)for(let e of Ch())this.registerCommand(e);if(e.javascript){for(let e of wh())this.registerCommand(e);let t=typeof e.javascript==`object`?e.javascript:Object.create(null);t.bootstrap&&(this.jsBootstrapCode=t.bootstrap)}if(e.customCommands)for(let t of e.customCommands)Th(t)?this.registerCommand(Eh(t)):this.registerCommand({...t,trusted:t.trusted??!0})}registerCommand(e){this.commands.set(e.name,e);let t=this.fs;if(typeof t.writeFileSync==`function`){let n=`#!/bin/bash
|
|
907
910
|
# Built-in command: ${e.name}
|
|
908
|
-
`;try{t.writeFileSync(`/bin/${e.name}`,n)}catch{}try{t.writeFileSync(`/usr/bin/${e.name}`,n)}catch{}}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug(`stdout`,{output:e.stdout}),e.stderr&&this.logger.info(`stderr`,{output:e.stderr}),this.logger.info(`exit`,{exitCode:e.exitCode})),e.stdout=
|
|
909
|
-
`,exitCode:1,env:
|
|
910
|
-
`,exitCode:1,env:
|
|
911
|
-
`,exitCode:2,env:
|
|
912
|
-
`,exitCode:2,env:
|
|
913
|
-
`,exitCode:1,env:
|
|
911
|
+
`;try{t.writeFileSync(`/bin/${e.name}`,n)}catch{}try{t.writeFileSync(`/usr/bin/${e.name}`,n)}catch{}}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug(`stdout`,{output:e.stdout}),e.stderr&&this.logger.info(`stderr`,{output:e.stderr}),this.logger.info(`exit`,{exitCode:e.exitCode})),e.stdout=bx(e.stdout),e.stderr=bx(e.stderr),e}async exec(e,t){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:``,stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
|
|
912
|
+
`,exitCode:1,env:un(this.state.env,t?.env)};if(!e.trim())return{stdout:``,stderr:``,exitCode:0,env:un(this.state.env,t?.env)};this.logger?.info(`exec`,{command:e});let n=t?.cwd??this.state.cwd,r,i=n;if(t?.cwd)if(t.env&&`PWD`in t.env)r=t.env.PWD;else if(t?.env&&!(`PWD`in t.env))try{r=await this.fs.realpath(n),i=r}catch{r=n}else r=n;let a=t?.replaceEnv?new Map:new Map(this.state.env);if(t?.env)for(let[e,n]of Object.entries(t.env))a.set(e,n);r!==void 0&&a.set(`PWD`,r);let o={...this.state,env:a,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:t?.stdin,signal:t?.signal,extraArgs:t?.args},s=e;t?.rawScript||(s=vx(e));let c=this.defenseInDepthConfig?sn.getInstance(this.defenseInDepthConfig):null,l=c?.activate();try{let e=async()=>{let e=_t(s,{maxHeredocSize:this.limits.maxHeredocSize}),t;if(this.transformPlugins.length>0){let n=Object.create(null);for(let t of this.transformPlugins){let r=t.transform({ast:e,metadata:n});e=r.ast,r.metadata&&(n=fn(n,r.metadata))}t=n}let n=await new rb({fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:c?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode},o).executeScript(e);return t&&(n.metadata=t),this.logResult(n)};return l?await l.run(e):await e()}catch(e){if(e instanceof et||e instanceof $e)return this.logResult({stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,env:un(this.state.env,t?.env)});if(e instanceof Je)return this.logResult({stdout:e.stdout,stderr:e.stderr,exitCode:1,env:un(this.state.env,t?.env)});if(e instanceof it)return this.logResult({stdout:e.stdout,stderr:e.stderr,exitCode:124,env:un(this.state.env,t?.env)});if(e instanceof Xe)return this.logResult({stdout:e.stdout,stderr:hn(e.stderr),exitCode:Xe.EXIT_CODE,env:un(this.state.env,t?.env)});if(e instanceof on)return this.logResult({stdout:``,stderr:`bash: security violation: ${hn(e.message)}
|
|
913
|
+
`,exitCode:1,env:un(this.state.env,t?.env)});if(e.name===`ParseException`)return this.logResult({stdout:``,stderr:`bash: syntax error: ${hn(e.message)}
|
|
914
|
+
`,exitCode:2,env:un(this.state.env,t?.env)});if(e instanceof dt)return this.logResult({stdout:``,stderr:`bash: ${hn(e.message)}
|
|
915
|
+
`,exitCode:2,env:un(this.state.env,t?.env)});if(e instanceof RangeError)return this.logResult({stdout:``,stderr:`bash: ${hn(e.message)}
|
|
916
|
+
`,exitCode:1,env:un(this.state.env,t?.env)});throw e}finally{l?.deactivate()}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,t){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),t)}getCwd(){return this.state.cwd}getEnv(){return dn(this.state.env)}registerTransformPlugin(e){this.transformPlugins.push(e)}transform(e){let t=_t(vx(e),{maxHeredocSize:this.limits.maxHeredocSize}),n=Object.create(null);for(let e of this.transformPlugins){let r=e.transform({ast:t,metadata:n});t=r.ast,r.metadata&&(n=fn(n,r.metadata))}return{script:Ib(t),ast:t,metadata:n}}};function vx(e){let t=e.split(`
|
|
914
917
|
`),n=[],r=[];for(let e=0;e<t.length;e++){let i=t[e];if(r.length>0){let e=r[r.length-1];if((e.stripTabs?i.replace(/^\t+/,``):i)===e.delimiter){n.push(i.trimStart()),r.pop();continue}n.push(i);continue}let a=i.trimStart();n.push(a);for(let e of a.matchAll(/<<(-?)\s*(['"]?)([\w-]+)\2/g)){let t=e[1]===`-`,n=e[3];r.push({delimiter:n,stripTabs:t})}}return n.join(`
|
|
915
|
-
`)}var vx=new TextDecoder(`utf-8`,{fatal:!0});function yx(e){if(!e)return e;let t=!1;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>255)return e;r>127&&(t=!0)}if(!t)return e;let n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);try{return vx.decode(n)}catch{return e}}var bx=[`EACCES`,`escaping sandbox`,`EFBIG`],xx=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(e){this.root=yn.resolve(e.root),this.maxFileReadSize=e.maxFileReadSize??10485760,this.allowSymlinks=e.allowSymlinks??!1,Zt(this.root,`ReadWriteFs`),this.canonicalRoot=j.realpathSync(this.root)}resolveAndValidate(e,t){let n=this.allowSymlinks?Yt(e,this.canonicalRoot):Xt(e,this.root,this.canonicalRoot);if(n===null)throw Error(`EACCES: permission denied, '${t}' resolves outside sandbox`);return n}validateParent(e,t){let n=yn.dirname(e),r=this.resolveAndValidate(n,t);return yn.join(r,yn.basename(e))}toRealPath(e){let t=Kt(e),n=yn.join(this.root,t);return yn.resolve(n)}async readFile(e,t){return tn(await this.readFileBuffer(e),$t(t))}async readFileBuffer(e){A(e,`open`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{let t=this.allowSymlinks?j.constants.O_RDONLY:j.constants.O_RDONLY|j.constants.O_NOFOLLOW,r=await j.promises.open(n,t);try{if(this.maxFileReadSize>0){let t=await r.stat();if(t.size>this.maxFileReadSize)throw Error(`EFBIG: file too large, read '${e}' (${t.size} bytes, max ${this.maxFileReadSize})`)}let t=await r.readFile();return new Uint8Array(t)}finally{await r.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(n.code===`EISDIR`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`open`)}}async writeFile(e,t,n){A(e,`write`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e),a=en(t,$t(n)),o=yn.dirname(i);try{await j.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(r,e);let t=this.allowSymlinks?0:j.constants.O_NOFOLLOW,n=j.constants.O_WRONLY|j.constants.O_CREAT|j.constants.O_TRUNC|t,s=await j.promises.open(i,n,438);try{await s.writeFile(a)}finally{await s.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`write`)}}async appendFile(e,t,n){A(e,`append`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e),a=en(t,$t(n)),o=yn.dirname(i);try{await j.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(r,e);let t=this.allowSymlinks?0:j.constants.O_NOFOLLOW,n=j.constants.O_WRONLY|j.constants.O_CREAT|j.constants.O_APPEND|t,s=await j.promises.open(i,n,438);try{await s.writeFile(a)}finally{await s.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`append`)}}async exists(e){if(e.includes(`\0`))return!1;let t=this.toRealPath(e);try{let n=this.resolveAndValidate(t,e);return await j.promises.access(n),!0}catch{return!1}}async stat(e){A(e,`stat`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{let t=await j.promises.lstat(n);if(!this.allowSymlinks&&t.isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return{isFile:t.isFile(),isDirectory:t.isDirectory(),isSymbolicLink:t.isSymbolicLink(),mode:t.mode,size:t.size,mtime:t.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, stat '${e}'`);this.sanitizeError(t,e,`stat`)}}async lstat(e){A(e,`lstat`);let t=this.toRealPath(e),n=this.validateParent(t,e);try{let e=await j.promises.lstat(n);return{isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink(),mode:e.mode,size:e.size,mtime:e.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);this.sanitizeError(t,e,`lstat`)}}async mkdir(e,t){A(e,`mkdir`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{await j.promises.mkdir(r,{recursive:t?.recursive})}catch(t){let n=t;if(n.code===`EEXIST`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.sanitizeError(t,e,`mkdir`)}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){A(e,`scandir`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{if(!this.allowSymlinks&&(await j.promises.lstat(n)).isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return(await j.promises.readdir(n,{withFileTypes:!0})).map(e=>({name:e.name,isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink()})).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.code===`ENOTDIR`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);this.sanitizeError(t,e,`scandir`)}}async rm(e,t){A(e,`rm`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{await j.promises.rm(r,{recursive:t?.recursive??!1,force:t?.force??!1})}catch(n){let r=n;if(r.code===`ENOENT`&&!t?.force)throw Error(`ENOENT: no such file or directory, rm '${e}'`);if(r.code===`ENOTEMPTY`)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);this.sanitizeError(n,e,`rm`)}}async cp(e,t,n){A(e,`cp`),A(t,`cp`);let r=this.toRealPath(e),i=this.toRealPath(t),a=this.resolveAndValidate(r,e),o=this.resolveAndValidate(i,t);try{await j.promises.cp(a,o,{recursive:n?.recursive??!1,filter:async e=>{try{if(j.lstatSync(e).isSymbolicLink()){let t=await j.promises.realpath(e).catch(()=>null);return t===null?!1:Ut(t,this.canonicalRoot)}return!0}catch(e){return e.code===`ENOENT`}}})}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(n.code===`EISDIR`)throw Error(`EISDIR: is a directory, cp '${e}'`);this.sanitizeError(t,e,`cp`)}}async mv(e,t){A(e,`mv`),A(t,`mv`);let n=this.toRealPath(e),r=this.toRealPath(t),i=this.validateParent(n,e),a=this.validateParent(r,t);try{if((await j.promises.lstat(i)).isSymbolicLink()){let n=await j.promises.readlink(i),r=yn.resolve(yn.dirname(a),n);if(!Ut(await j.promises.realpath(r).catch(()=>r),this.canonicalRoot))throw Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlink escaping sandbox`)}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(n.message?.includes(`EACCES`)||n.message?.includes(`escaping sandbox`))throw t}let o=yn.dirname(a);try{await j.promises.mkdir(o,{recursive:!0})}catch(e){this.sanitizeError(e,t,`mv`)}try{await j.promises.rename(i,a)}catch(n){let r=n;if(r.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(r.code===`EXDEV`){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0});return}this.sanitizeError(n,e,`mv`)}try{if(j.lstatSync(a).isDirectory()&&this.findEscapingSymlinks(a).length>0)throw await j.promises.rename(a,i),Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlinks escaping sandbox`)}catch(e){if(e.message?.includes(`EACCES`)||e.message?.includes(`escaping sandbox`))throw e}}resolvePath(e,t){return Gt(e,t)}getAllPaths(){let e=[];return this.scanDir(`/`,e),e}sanitizeError(e,t,n){Jt(e,t,n,bx)}findEscapingSymlinks(e){let t=[];try{let n=j.readdirSync(e);for(let r of n){let n=yn.join(e,r);try{let r=j.lstatSync(n);if(r.isSymbolicLink()){let r=j.readlinkSync(n),i=yn.resolve(e,r),a;try{a=j.realpathSync(i)}catch{a=i}Ut(a,this.canonicalRoot)||t.push(n)}else r.isDirectory()&&t.push(...this.findEscapingSymlinks(n))}catch{}}}catch{}return t}scanDir(e,t){let n=this.toRealPath(e),r;try{r=this.resolveAndValidate(n,e)}catch{return}try{let n=j.readdirSync(r);for(let i of n){let n=e===`/`?`/${i}`:`${e}/${i}`;t.push(n);let a=yn.join(r,i);j.lstatSync(a).isDirectory()&&this.scanDir(n,t)}}catch{}}async chmod(e,t){A(e,`chmod`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{let e=this.allowSymlinks?j.constants.O_RDONLY:j.constants.O_RDONLY|j.constants.O_NOFOLLOW,n=await j.promises.open(r,e);try{await n.chmod(t)}finally{await n.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`chmod`)}}async symlink(e,t){if(!this.allowSymlinks)throw Error(`EPERM: operation not permitted, symlink '${t}'`);A(t,`symlink`);let n=this.toRealPath(t),r=this.validateParent(n,t),i=Kt(t),a=Kt(yn.dirname(i)),o=e.startsWith(`/`)?Kt(e):Kt(a===`/`?`/${e}`:`${a}/${e}`),s=yn.join(this.canonicalRoot,o),c=yn.dirname(r),l=e.startsWith(`/`)?s:yn.relative(c,s)||`.`;try{await j.promises.symlink(l,r)}catch(e){if(e.code===`EEXIST`)throw Error(`EEXIST: file already exists, symlink '${t}'`);this.sanitizeError(e,t,`symlink`)}}async link(e,t){A(e,`link`),A(t,`link`);let n=this.toRealPath(e),r=this.toRealPath(t),i=this.resolveAndValidate(n,e),a=this.resolveAndValidate(r,t);try{await j.promises.link(i,a)}catch(n){let r=n;if(r.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(r.code===`EEXIST`)throw Error(`EEXIST: file already exists, link '${t}'`);if(r.code===`EPERM`)throw Error(`EPERM: operation not permitted, link '${e}'`);this.sanitizeError(n,e,`link`)}}async readlink(e){A(e,`readlink`);let t=this.toRealPath(e),n=this.validateParent(t,e);try{let t=await j.promises.readlink(n),r=Kt(e),i=yn.dirname(r),a=yn.isAbsolute(t)?t:yn.resolve(yn.dirname(n),t),o=await j.promises.realpath(a).catch(()=>a);if(Ut(o,this.canonicalRoot)){let e=o.slice(this.canonicalRoot.length)||`/`;return i===`/`?e.startsWith(`/`)?e.slice(1)||`.`:e:yn.relative(i,e)}return yn.basename(t)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.code===`EINVAL`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);this.sanitizeError(t,e,`readlink`)}}async realpath(e){A(e,`realpath`);let t=this.toRealPath(e);try{this.resolveAndValidate(t,e)}catch{throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}let n;try{n=await j.promises.realpath(t)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, realpath '${e}'`);if(n.code===`ELOOP`)throw Error(`ELOOP: too many levels of symbolic links, realpath '${e}'`);this.sanitizeError(t,e,`realpath`)}if(Ut(n,this.canonicalRoot))return n.slice(this.canonicalRoot.length)||`/`;throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}async utimes(e,t,n){A(e,`utimes`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e);try{let e=this.allowSymlinks?j.constants.O_RDONLY:j.constants.O_RDONLY|j.constants.O_NOFOLLOW,r=await j.promises.open(i,e);try{await r.utimes(t,n)}finally{await r.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`utimes`)}}};function Sx(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const Cx=16*1024*1024;var wx=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,n){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=n}};function Tx(e){if(!Cn(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new gx({cwd:`/`,fs:new xx({root:En(e),allowSymlinks:!1})})}async function Ex(e,t){let n=await e.exec(t);if(n.stdout.length>Cx)throw new wx(Cx,n.stdout.length,{stdout:n.stdout.slice(0,Cx),stderr:n.stderr,exitCode:n.exitCode});return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}function Dx(e){return e.startsWith(`**/`)?e.slice(3):e}async function Ox(e,t,n={}){let r=Tx(t),i=[`-rn`,`-F`];(n.caseInsensitive??!0)&&i.push(`-i`);for(let e of n.include??[])i.push(`--include=${Sx(Dx(e))}`);for(let e of n.exclude??[])i.push(`--exclude=${Sx(Dx(e))}`),i.push(`--exclude-dir=${Sx(Dx(e))}`);let a=n.paths?.length?n.paths.map(Sx):[`.`],o=`grep ${i.join(` `)} ${Sx(e)} ${a.join(` `)}`,s;try{s=await Ex(r,o)}catch(e){if(e instanceof wx)s=e.partial;else throw e}if(s.exitCode===1&&!s.stdout)return[];if(s.exitCode!==0&&s.exitCode!==1&&!s.stdout)throw Error(`grep exited ${s.exitCode}: ${s.stderr}`);let c=[],l=n.maxResults??1/0;for(let e of s.stdout.split(`
|
|
916
|
-
`)){if(!e)continue;if(c.length>=l)break;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.indexOf(`:`,t+1);if(n===-1)continue;let r=e.slice(0,t),i=e.slice(t+1,n),a=e.slice(n+1),o=Number.parseInt(i,10);Number.isFinite(o)&&c.push({path:r,line:o,text:a})}return c}const
|
|
917
|
-
`)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const
|
|
918
|
-
`).map(e=>e.trim()).filter(Boolean);return s.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(s.map(e=>
|
|
919
|
-
`);function
|
|
920
|
-
`),n=t[t.length-1]===``?t.length-1:t.length;if(n<=500&&e.length<=
|
|
921
|
-
`),s=n-a;return{text:`${o}\n<truncated: ${s} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:s}}function
|
|
922
|
-
`),a=i[i.length-1]===``?i.length-1:i.length;if(a<r)return null;let o=i.slice(0,a),s=new Set(o.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,c=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${n.command} -${r}\` cap (${a} lines, ${s} unique file${s===1?``:`s`}). The \`${c}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${n.command}\` or widen the cap.`}}function
|
|
923
|
-
`)}async function
|
|
924
|
-
`)}\n\n`:``,
|
|
925
|
-
`);function
|
|
926
|
-
`);function
|
|
927
|
-
`);function
|
|
928
|
-
`);function
|
|
929
|
-
`);function
|
|
930
|
-
`);function
|
|
918
|
+
`)}var yx=new TextDecoder(`utf-8`,{fatal:!0});function bx(e){if(!e)return e;let t=!1;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>255)return e;r>127&&(t=!0)}if(!t)return e;let n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);try{return yx.decode(n)}catch{return e}}var xx=[`EACCES`,`escaping sandbox`,`EFBIG`],Sx=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(e){this.root=k.resolve(e.root),this.maxFileReadSize=e.maxFileReadSize??10485760,this.allowSymlinks=e.allowSymlinks??!1,$t(this.root,`ReadWriteFs`),this.canonicalRoot=A.realpathSync(this.root)}resolveAndValidate(e,t){let n=this.allowSymlinks?Zt(e,this.canonicalRoot):Qt(e,this.root,this.canonicalRoot);if(n===null)throw Error(`EACCES: permission denied, '${t}' resolves outside sandbox`);return n}validateParent(e,t){let n=k.dirname(e),r=this.resolveAndValidate(n,t);return k.join(r,k.basename(e))}toRealPath(e){let t=D(e),n=k.join(this.root,t);return k.resolve(n)}async readFile(e,t){return rn(await this.readFileBuffer(e),tn(t))}async readFileBuffer(e){O(e,`open`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{let t=this.allowSymlinks?A.constants.O_RDONLY:A.constants.O_RDONLY|A.constants.O_NOFOLLOW,r=await A.promises.open(n,t);try{if(this.maxFileReadSize>0){let t=await r.stat();if(t.size>this.maxFileReadSize)throw Error(`EFBIG: file too large, read '${e}' (${t.size} bytes, max ${this.maxFileReadSize})`)}let t=await r.readFile();return new Uint8Array(t)}finally{await r.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(n.code===`EISDIR`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`open`)}}async writeFile(e,t,n){O(e,`write`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e),a=nn(t,tn(n)),o=k.dirname(i);try{await A.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(r,e);let t=this.allowSymlinks?0:A.constants.O_NOFOLLOW,n=A.constants.O_WRONLY|A.constants.O_CREAT|A.constants.O_TRUNC|t,s=await A.promises.open(i,n,438);try{await s.writeFile(a)}finally{await s.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`write`)}}async appendFile(e,t,n){O(e,`append`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e),a=nn(t,tn(n)),o=k.dirname(i);try{await A.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(r,e);let t=this.allowSymlinks?0:A.constants.O_NOFOLLOW,n=A.constants.O_WRONLY|A.constants.O_CREAT|A.constants.O_APPEND|t,s=await A.promises.open(i,n,438);try{await s.writeFile(a)}finally{await s.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`append`)}}async exists(e){if(e.includes(`\0`))return!1;let t=this.toRealPath(e);try{let n=this.resolveAndValidate(t,e);return await A.promises.access(n),!0}catch{return!1}}async stat(e){O(e,`stat`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{let t=await A.promises.lstat(n);if(!this.allowSymlinks&&t.isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return{isFile:t.isFile(),isDirectory:t.isDirectory(),isSymbolicLink:t.isSymbolicLink(),mode:t.mode,size:t.size,mtime:t.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, stat '${e}'`);this.sanitizeError(t,e,`stat`)}}async lstat(e){O(e,`lstat`);let t=this.toRealPath(e),n=this.validateParent(t,e);try{let e=await A.promises.lstat(n);return{isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink(),mode:e.mode,size:e.size,mtime:e.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);this.sanitizeError(t,e,`lstat`)}}async mkdir(e,t){O(e,`mkdir`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{await A.promises.mkdir(r,{recursive:t?.recursive})}catch(t){let n=t;if(n.code===`EEXIST`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.sanitizeError(t,e,`mkdir`)}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){O(e,`scandir`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{if(!this.allowSymlinks&&(await A.promises.lstat(n)).isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return(await A.promises.readdir(n,{withFileTypes:!0})).map(e=>({name:e.name,isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink()})).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.code===`ENOTDIR`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);this.sanitizeError(t,e,`scandir`)}}async rm(e,t){O(e,`rm`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{await A.promises.rm(r,{recursive:t?.recursive??!1,force:t?.force??!1})}catch(n){let r=n;if(r.code===`ENOENT`&&!t?.force)throw Error(`ENOENT: no such file or directory, rm '${e}'`);if(r.code===`ENOTEMPTY`)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);this.sanitizeError(n,e,`rm`)}}async cp(e,t,n){O(e,`cp`),O(t,`cp`);let r=this.toRealPath(e),i=this.toRealPath(t),a=this.resolveAndValidate(r,e),o=this.resolveAndValidate(i,t);try{await A.promises.cp(a,o,{recursive:n?.recursive??!1,filter:async e=>{try{if(A.lstatSync(e).isSymbolicLink()){let t=await A.promises.realpath(e).catch(()=>null);return t===null?!1:Kt(t,this.canonicalRoot)}return!0}catch(e){return e.code===`ENOENT`}}})}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(n.code===`EISDIR`)throw Error(`EISDIR: is a directory, cp '${e}'`);this.sanitizeError(t,e,`cp`)}}async mv(e,t){O(e,`mv`),O(t,`mv`);let n=this.toRealPath(e),r=this.toRealPath(t),i=this.validateParent(n,e),a=this.validateParent(r,t);try{if((await A.promises.lstat(i)).isSymbolicLink()){let n=await A.promises.readlink(i),r=k.resolve(k.dirname(a),n);if(!Kt(await A.promises.realpath(r).catch(()=>r),this.canonicalRoot))throw Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlink escaping sandbox`)}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(n.message?.includes(`EACCES`)||n.message?.includes(`escaping sandbox`))throw t}let o=k.dirname(a);try{await A.promises.mkdir(o,{recursive:!0})}catch(e){this.sanitizeError(e,t,`mv`)}try{await A.promises.rename(i,a)}catch(n){let r=n;if(r.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(r.code===`EXDEV`){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0});return}this.sanitizeError(n,e,`mv`)}try{if(A.lstatSync(a).isDirectory()&&this.findEscapingSymlinks(a).length>0)throw await A.promises.rename(a,i),Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlinks escaping sandbox`)}catch(e){if(e.message?.includes(`EACCES`)||e.message?.includes(`escaping sandbox`))throw e}}resolvePath(e,t){return Jt(e,t)}getAllPaths(){let e=[];return this.scanDir(`/`,e),e}sanitizeError(e,t,n){Xt(e,t,n,xx)}findEscapingSymlinks(e){let t=[];try{let n=A.readdirSync(e);for(let r of n){let n=k.join(e,r);try{let r=A.lstatSync(n);if(r.isSymbolicLink()){let r=A.readlinkSync(n),i=k.resolve(e,r),a;try{a=A.realpathSync(i)}catch{a=i}Kt(a,this.canonicalRoot)||t.push(n)}else r.isDirectory()&&t.push(...this.findEscapingSymlinks(n))}catch{}}}catch{}return t}scanDir(e,t){let n=this.toRealPath(e),r;try{r=this.resolveAndValidate(n,e)}catch{return}try{let n=A.readdirSync(r);for(let i of n){let n=e===`/`?`/${i}`:`${e}/${i}`;t.push(n);let a=k.join(r,i);A.lstatSync(a).isDirectory()&&this.scanDir(n,t)}}catch{}}async chmod(e,t){O(e,`chmod`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{let e=this.allowSymlinks?A.constants.O_RDONLY:A.constants.O_RDONLY|A.constants.O_NOFOLLOW,n=await A.promises.open(r,e);try{await n.chmod(t)}finally{await n.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`chmod`)}}async symlink(e,t){if(!this.allowSymlinks)throw Error(`EPERM: operation not permitted, symlink '${t}'`);O(t,`symlink`);let n=this.toRealPath(t),r=this.validateParent(n,t),i=D(t),a=D(k.dirname(i)),o=e.startsWith(`/`)?D(e):D(a===`/`?`/${e}`:`${a}/${e}`),s=k.join(this.canonicalRoot,o),c=k.dirname(r),l=e.startsWith(`/`)?s:k.relative(c,s)||`.`;try{await A.promises.symlink(l,r)}catch(e){if(e.code===`EEXIST`)throw Error(`EEXIST: file already exists, symlink '${t}'`);this.sanitizeError(e,t,`symlink`)}}async link(e,t){O(e,`link`),O(t,`link`);let n=this.toRealPath(e),r=this.toRealPath(t),i=this.resolveAndValidate(n,e),a=this.resolveAndValidate(r,t);try{await A.promises.link(i,a)}catch(n){let r=n;if(r.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(r.code===`EEXIST`)throw Error(`EEXIST: file already exists, link '${t}'`);if(r.code===`EPERM`)throw Error(`EPERM: operation not permitted, link '${e}'`);this.sanitizeError(n,e,`link`)}}async readlink(e){O(e,`readlink`);let t=this.toRealPath(e),n=this.validateParent(t,e);try{let t=await A.promises.readlink(n),r=D(e),i=k.dirname(r),a=k.isAbsolute(t)?t:k.resolve(k.dirname(n),t),o=await A.promises.realpath(a).catch(()=>a);if(Kt(o,this.canonicalRoot)){let e=o.slice(this.canonicalRoot.length)||`/`;return i===`/`?e.startsWith(`/`)?e.slice(1)||`.`:e:k.relative(i,e)}return k.basename(t)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.code===`EINVAL`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);this.sanitizeError(t,e,`readlink`)}}async realpath(e){O(e,`realpath`);let t=this.toRealPath(e);try{this.resolveAndValidate(t,e)}catch{throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}let n;try{n=await A.promises.realpath(t)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, realpath '${e}'`);if(n.code===`ELOOP`)throw Error(`ELOOP: too many levels of symbolic links, realpath '${e}'`);this.sanitizeError(t,e,`realpath`)}if(Kt(n,this.canonicalRoot))return n.slice(this.canonicalRoot.length)||`/`;throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}async utimes(e,t,n){O(e,`utimes`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e);try{let e=this.allowSymlinks?A.constants.O_RDONLY:A.constants.O_RDONLY|A.constants.O_NOFOLLOW,r=await A.promises.open(i,e);try{await r.utimes(t,n)}finally{await r.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`utimes`)}}};function Cx(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const wx=16*1024*1024;var Tx=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,n){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=n}};function Ex(e){if(!wn(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new _x({cwd:`/`,fs:new Sx({root:Dn(e),allowSymlinks:!1})})}async function Dx(e,t){let n=await e.exec(t);if(n.stdout.length>wx)throw new Tx(wx,n.stdout.length,{stdout:n.stdout.slice(0,wx),stderr:n.stderr,exitCode:n.exitCode});return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}function Ox(e){return e.startsWith(`**/`)?e.slice(3):e}async function kx(e,t,n={}){let r=Ex(t),i=[`-rn`,`-F`];(n.caseInsensitive??!0)&&i.push(`-i`);for(let e of n.include??[])i.push(`--include=${Cx(Ox(e))}`);for(let e of n.exclude??[])i.push(`--exclude=${Cx(Ox(e))}`),i.push(`--exclude-dir=${Cx(Ox(e))}`);let a=n.paths?.length?n.paths.map(Cx):[`.`],o=`grep ${i.join(` `)} ${Cx(e)} ${a.join(` `)}`,s;try{s=await Dx(r,o)}catch(e){if(e instanceof Tx)s=e.partial;else throw e}if(s.exitCode===1&&!s.stdout)return[];if(s.exitCode!==0&&s.exitCode!==1&&!s.stdout)throw Error(`grep exited ${s.exitCode}: ${s.stderr}`);let c=[],l=n.maxResults??1/0;for(let e of s.stdout.split(`
|
|
919
|
+
`)){if(!e)continue;if(c.length>=l)break;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.indexOf(`:`,t+1);if(n===-1)continue;let r=e.slice(0,t),i=e.slice(t+1,n),a=e.slice(n+1),o=Number.parseInt(i,10);Number.isFinite(o)&&c.push({path:r,line:o,text:a})}return c}const Ax=new Set([`.git`,T,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function jx(e){let t=Dn(e),n=new Map,r=0,i=!1;async function a(e){if(i)return;let o;try{o=await $n(e,{withFileTypes:!0})}catch{return}for(let s of o){if(i)return;if(s.isDirectory()&&Ax.has(s.name))continue;let o=Dn(e,s.name);if(s.isDirectory()){await a(o);continue}if(s.isFile()){if(r>=1e3){i=!0;return}try{let e=await er(o);n.set(En(t,o),e.mtimeMs),r++}catch{}}}}return await a(t),{snapshot:n,truncated:i}}function Mx(e,t){let n=[];for(let[r,i]of t){let t=e.get(r);(t===void 0||t!==i)&&n.push(r)}for(let[r]of e)t.has(r)||n.push(r);return{changed:n}}var Nx=n(((e,t)=>{t.exports=function(e){return e.map(function(e){return e===``?`''`:e&&typeof e==`object`?e.op.replace(/(.)/g,`\\$1`):/["\s\\]/.test(e)&&!/'/.test(e)?`'`+e.replace(/(['])/g,`\\$1`)+`'`:/["'\s]/.test(e)?`"`+e.replace(/(["\\$`!])/g,`\\$1`)+`"`:String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,`$1\\$2`)}).join(` `)}})),Px=n(((e,t)=>{for(var n=`(?:`+[`\\|\\|`,`\\&\\&`,`;;`,`\\|\\&`,`\\<\\(`,`\\<\\<\\<`,`>>`,`>\\&`,`<\\&`,`[&;()|<>]`].join(`|`)+`)`,r=RegExp(`^`+n+`$`),i=`|&;()<> \\t`,a=`"((\\\\"|[^"])*?)"`,o=`'((\\\\'|[^'])*?)'`,s=/^#$/,c=`'`,l=`"`,u=`$`,d=``,f=4294967296,p=0;p<4;p++)d+=(f*Math.random()).toString(16);var m=RegExp(`^`+d);function h(e,t){for(var n=t.lastIndex,r=[],i;i=t.exec(e);)r.push(i),t.lastIndex===i.index&&(t.lastIndex+=1);return t.lastIndex=n,r}function g(e,t,n){var r=typeof e==`function`?e(n):e[n];return r===void 0&&n!=``?r=``:r===void 0&&(r=`$`),typeof r==`object`?t+d+JSON.stringify(r)+d:t+r}function _(e,t,d){d||={};var f=d.escape||`\\`,p=`(\\`+f+`['"`+i+`]|[^\\s'"`+i+`])+`,m=h(e,new RegExp([`(`+n+`)`,`(`+p+`|`+a+`|`+o+`)+`].join(`|`),`g`));if(m.length===0)return[];t||={};var _=!1;return m.map(function(n){var i=n[0];if(!i||_)return;if(r.test(i))return{op:i};var a=!1,o=!1,d=``,p=!1,m;function h(){m+=1;var e,n,r=i.charAt(m);if(r===`{`){if(m+=1,i.charAt(m)===`}`)throw Error(`Bad substitution: `+i.slice(m-2,m+1));if(e=i.indexOf(`}`,m),e<0)throw Error(`Bad substitution: `+i.slice(m));n=i.slice(m,e),m=e}else if(/[*@#?$!_-]/.test(r))n=r,m+=1;else{var a=i.slice(m);e=a.match(/[^\w\d_]/),e?(n=a.slice(0,e.index),m+=e.index-1):(n=a,m=i.length)}return g(t,``,n)}for(m=0;m<i.length;m++){var v=i.charAt(m);if(p||=!a&&(v===`*`||v===`?`),o)d+=v,o=!1;else if(a)v===a?a=!1:a==c?d+=v:v===f?(m+=1,v=i.charAt(m),v===l||v===f||v===u?d+=v:d+=f+v):v===u?d+=h():d+=v;else if(v===l||v===c)a=v;else if(r.test(v))return{op:i};else if(s.test(v)){_=!0;var y={comment:e.slice(n.index+m+1)};return d.length?[d,y]:[y]}else v===f?o=!0:v===u?d+=h():d+=v}return p?{op:`glob`,pattern:d}:d}).reduce(function(e,t){return t===void 0?e:e.concat(t)},[])}t.exports=function(e,t,n){var r=_(e,t,n);return typeof t==`function`?r.reduce(function(e,t){if(typeof t==`object`)return e.concat(t);var n=t.split(RegExp(`(`+d+`.*?`+d+`)`,`g`));return n.length===1?e.concat(n[0]):e.concat(n.filter(Boolean).map(function(e){return m.test(e)?JSON.parse(e.split(d)[1]):e}))},[]):r}})),Fx=t(n((e=>{e.quote=Nx(),e.parse=Px()}))(),1);const Ix=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,T,`.claude`];function Lx(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const Rx=[{command:`grep`,applies:e=>e.slice(1).some(Lx),hasUserExcludes:e=>e.some(e=>e===`--exclude-dir`||e.startsWith(`--exclude-dir=`)),buildExcludeArgs:e=>e.map(e=>`--exclude-dir=${e}`),insertionIndex:()=>1},{command:`find`,applies:()=>!0,hasUserExcludes:e=>e.slice(1).some(e=>e===`-not`||e===`!`||e===`-prune`),buildExcludeArgs:e=>{let t=[];for(let n of e)t.push(`-not`,`-path`,`*/${n}/*`);return t},insertionIndex:e=>{for(let t=1;t<e.length;t++)if(e[t].startsWith(`-`))return t;return e.length}}];function zx(e){return e.map(e=>{let t=Rx.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let n=t.buildExcludeArgs(Ix),r=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,r),...n,...e.args.slice(r)]}})}function Bx(e){return e.map(e=>e.args.map(Cx).join(` `)).join(` | `)}const Vx=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),Hx=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),Ux=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),Wx=new Set([`-o`,`--output-file`,`--output`]),Gx=[`-o=`,`--output-file=`,`--output=`],Kx=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),qx=/[`]|\$\(|\$\{|\$'/;function Jx(e){return typeof e==`object`&&!!e&&`op`in e}function Yx(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return Hx.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`}:Ux.has(t)?{category:`shell_construct_blocked`,message:`Shell construct '${t}' is not supported. Only pipes (|) are allowed between allowlisted stages.`}:{category:`shell_construct_blocked`,message:`Operator '${t}' is not supported.`}}function Xx(e){let t=[];for(let n of e){if(typeof n==`string`){if(qx.test(n))return{error:{category:`shell_construct_blocked`,message:`Argument '${n}' contains a shell-injection pattern (backtick, $(), or \${}); not supported.`}};t.push(n);continue}if(!Jx(n))return{error:{category:`shell_construct_blocked`,message:`Unrecognized token shape.`}};if(n.op===`glob`&&typeof n.pattern==`string`){t.push(n.pattern);continue}return typeof n.comment==`string`?{error:{category:`shell_construct_blocked`,message:`Comments are not allowed in exec commands.`}}:{error:Yx(n)}}return{args:t}}function Zx(e){if(!Vx.has(e.command))return{category:`unknown_command`,message:`Command '${e.command}' is not in the allowlist. For pattern matching try 'grep'; for file listing try 'ls' or 'find'. Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut.`};for(let t of e.args.slice(1)){if(Wx.has(t)||Gx.some(e=>t.startsWith(e)))return{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`};if(e.command===`find`&&Kx.has(t))return{category:`write_blocked`,message:`find flag '${t}' is blocked (executes commands or deletes files). Use exec for read-only discovery; chain with another allowlisted tool via '|' if you need to transform output.`}}return null}function Qx(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let n;try{n=Fx.parse(t)}catch{return{error:{category:`shell_construct_blocked`,message:`Failed to parse command — likely malformed quoting or an unsupported construct.`}}}let r=[],i=[];for(let e of n){if(Jx(e)&&e.op===`|`){r.push(i),i=[];continue}i.push(e)}r.push(i);let a=[];for(let e of r){let t=Xx(e);if(`error`in t)return t;if(t.args.length===0)return{error:{category:`shell_construct_blocked`,message:`Empty pipeline stage (trailing pipe or leading pipe).`}};let n={command:t.args[0],args:t.args},r=Zx(n);if(r)return{error:r};a.push(n)}return{stages:a}}const $x=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function eS(e,t){let n=e.match($x);if(!n)return null;try{let e=(0,ar.parse)(n[1]);if(Be(e)){if(t){let n=t.safeParse(e);return n.success?n.data:null}return e}}catch{}return null}var tS=t(Oe(),1);const nS=new WeakMap;function rS(e){let t=nS.get(e);if(t)return t;let n=e.map(e=>(0,tS.default)(e.match,{dot:!0}));return nS.set(e,n),n}function iS(e,t){if(e.length===0)return{};let n=rS(e),r={},i=[],a=!1;for(let o=0;o<e.length;o++){if(!n[o](t))continue;a=!0;let s=e[o].frontmatter;if(s.title!==void 0&&(r.title=s.title),s.description!==void 0&&(r.description=s.description),s.tags!==void 0)for(let e of s.tags)i.includes(e)||i.push(e)}return a?(i.length>0&&(r.tags=i),r):{}}function aS(e){try{return In(Dn(e,`.git`)).isDirectory()}catch{return!1}}function oS(e){return Se({baseDir:Dn(e),timeout:{block:5e3}})}async function sS(e,t,n=5){if(!aS(e))return{commits:[],source:`git-absent`};let r=oS(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
|
|
920
|
+
`)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const cS=5e3;async function lS(e){try{let t=(await Se({baseDir:e,timeout:{block:cS}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function uS(e,t){return Se({baseDir:t,timeout:{block:cS}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function dS(e,t){let n=Ae(t);return e.startsWith(n)?e.slice(n.length):e}async function fS(e,t,n,r,i){let a=``;try{a=await e.raw(`log`,t,`-${Math.max(1,i*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,n)}catch{return[]}let o=dS(t,r),s=Me(o),c=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,i=``,a=``,l=``,u=``]=t.split(`\0`),d=n.trim();d.length===40&&c.push({hash:d,date:i,writerName:a,message:l,contributors:je(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return c}async function pS(e,t,n=5){let r=Ce(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await lS(e);if(!i)return{commits:[],source:`shadow-repo`};let a=uS(r,Dn(e)),o=``;try{o=await a.raw(`for-each-ref`,Ae(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let s=o.split(`
|
|
921
|
+
`).map(e=>e.trim()).filter(Boolean);return s.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(s.map(e=>fS(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n),source:`shadow-repo`}}const mS=1e3,hS=new Set([`.git`,T,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),gS=/\.(md|mdx)$/i,_S=S({title:u().optional(),description:u().optional(),tags:y(u()).default([])});function vS(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}async function yS(e){try{let t=eS(await Qn(e,`utf-8`),_S);return t?{title:t.title,description:t.description,tags:t.tags??[]}:{tags:[]}}catch{return null}}async function bS(e,t){if(!e)return null;let n=await Bm(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.backlinks??n.results??n.links;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,n=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;n&&i.push({source:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}async function xS(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));let i=await Promise.all(r.map(async t=>{let n=await Bm(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})),a=new Map,o=!1;for(let e of i)if(e){o=!0;for(let[t,n]of Object.entries(e))typeof n==`number`&&Number.isFinite(n)&&a.set(t,n)}return o?a:null}async function SS(e,t){if(!e)return null;let n=await Bm(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.forwardLinks??n.links??n.results;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){i.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let n=typeof t.docName==`string`?t.docName:void 0;n&&i.push({kind:`doc`,docName:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}function CS(e,t,n){let r=t??[],i=r.length===0?{}:iS(r,n),a=e?.title??i.title,o=e?.description??i.description,s=e?.tags??[],c=i.tags??[],l;if(c.length===0)l=s;else{let e=new Set;l=[];for(let t of c)e.has(t)||(e.add(t),l.push(t));for(let t of s)e.has(t)||(e.add(t),l.push(t))}return{title:a,description:o,tags:l}}async function wS(e,t,n={}){let r=e.replace(/^\.\//,``).replace(/^\/+/,``),i=Dn(t.projectDir,r),a=t.historyDepth??5,o=n.includeRichFields===!0,s=yS(i);if(!o){let e=CS(await s,t.folderRules,r);return{path:r,title:e.title,description:e.description,tags:e.tags,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[c,l,u,d,f]=await Promise.all([s,bS(t.serverUrl,vS(r)).catch(()=>null),SS(t.serverUrl,vS(r)).catch(()=>null),pS(t.projectDir,r,a).catch(()=>({commits:[],source:`shadow-repo`})),sS(t.projectDir,r,a).catch(()=>({commits:[],source:`git`}))]),p=CS(c,t.folderRules,r);return{path:r,title:p.title,description:p.description,tags:p.tags,backlinkCount:l?.length??null,backlinks:l,forwardLinkCount:u?.length??null,forwardLinks:u,history:d.commits,historySource:d.source,projectHistory:f.commits,projectHistorySource:f.source}}async function TS(e,t){let n={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},r=0,i=[{path:e,depth:0}];for(;i.length>0;){let e=i.shift();if(!e)break;if(r>=mS){n.truncated=!0;break}let a;try{a=await $n(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=mS){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(hS.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&gS.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await er(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:En(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function ES(e,t){let n=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``),r=await TS(Dn(t.projectDir,n),t.projectDir),i;if(r.mostRecent){let e=await yS(r.mostRecent.absPath);i={path:r.mostRecent.relPath,title:e?.title??Sn(r.mostRecent.relPath),updatedAt:new Date(r.mostRecent.mtimeMs).toISOString()}}let a={path:n,type:`directory`,directMdCount:r.directMdCount,recursiveMdCount:r.recursiveMdCount,childDirCount:r.childDirCount,mostRecentMd:i,truncated:r.truncated},o=t.folderRules??[];if(o.length>0){let e=iS(o,n);e.title!==void 0&&(a.title=e.title),e.description!==void 0&&(a.description=e.description),e.tags!==void 0&&e.tags.length>0&&(a.tags=e.tags)}return a}const DS=50*1024,OS=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,kS=["**STOP — native tools on in-scope markdown.** Do NOT use your host's native `Read`, `Grep`, or `Glob` on `.md` / `.mdx` paths inside OK's content directory — use `exec` (this tool) instead. Native file tools skip frontmatter, backlinks, shadow-repo activity, and project git history that `exec` returns for every matched wiki file. Reserve native `Read`/`Grep`/`Glob` for source code and non-markdown paths only.",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,`Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. Pipes (|) work between stages. Redirections, subshells, and writes are rejected.`,``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
|
|
922
|
+
`);function AS(e){let t=e.split(`
|
|
923
|
+
`),n=t[t.length-1]===``?t.length-1:t.length;if(n<=500&&e.length<=DS)return{text:e,truncated:!1,omittedLines:0};let r=Math.min(n,500),i=0,a=0;for(let e=0;e<r;e++){let n=t[e];if(i+=n.length+1,i>DS)break;a++}let o=t.slice(0,a).join(`
|
|
924
|
+
`),s=n-a;return{text:`${o}\n<truncated: ${s} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:s}}function jS(e){let t=[];for(let n of e)if(n.command===`cat`)for(let e of n.args.slice(1))e.startsWith(`-`)||OS.test(e)&&t.push(e);return t}function MS(e){for(let t=1;t<e.length;t++){let n=e[t],r=n.match(/^--lines=(\d+)$/);if(r)return Number(r[1]);if(n===`--lines`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}if(n===`-n`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}let i=n.match(/^-n(\d+)$/);if(i)return Number(i[1]);let a=n.match(/^-(\d+)$/);if(a)return Number(a[1])}return 10}function NS(e,t){if(e.length<2)return null;let n=e[e.length-1];if(n.command!==`head`&&n.command!==`tail`)return null;let r=MS(n.args),i=t.split(`
|
|
925
|
+
`),a=i[i.length-1]===``?i.length-1:i.length;if(a<r)return null;let o=i.slice(0,a),s=new Set(o.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,c=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${n.command} -${r}\` cap (${a} lines, ${s} unique file${s===1?``:`s`}). The \`${c}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${n.command}\` or widen the cap.`}}function PS(e){return e.type===`directory`}function FS(e){let t=[e.title?`**${e.title}** (${e.path}/)`:`**${e.path}/** (directory)`];e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`);let n=[];return n.push(`${e.recursiveMdCount} md file${e.recursiveMdCount===1?``:`s`}`),e.childDirCount>0&&n.push(`${e.childDirCount} subdir${e.childDirCount===1?``:`s`}`),t.push(n.join(`, `)),e.mostRecentMd&&t.push(`most recent: ${e.mostRecentMd.title??e.mostRecentMd.path} (${e.mostRecentMd.path})`),e.truncated&&t.push(`scan truncated`),`- ${t.join(` — `)}`}function IS(e){let t=[`**${e.title??e.path}** (${e.path})`];if(e.description&&t.push(e.description),e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.backlinkCount!==null&&t.push(`backlinks: ${e.backlinkCount}`),e.forwardLinkCount!==null&&t.push(`forward links: ${e.forwardLinkCount}`),e.history&&e.history.length>0){let n=e.history.map(e=>{let t=e.writerClassification===`agent`?`agent: ${e.writerName}`:e.writerClassification===`principal`?`human: ${e.writerName}`:`${e.writerClassification}: ${e.writerName}`;return`${e.hash.slice(0,7)} [${t}] ${e.message}`});t.push(`OK edits: ${n.join(` · `)}`)}if(e.projectHistory&&e.projectHistory.length>0){let n=e.projectHistory.map(e=>`${e.hash.slice(0,7)} ${e.authorName}: ${e.subject}`);t.push(`commits: ${n.join(` · `)}`)}return`- ${t.join(` — `)}`}function LS(e,t,n){let r=null;for(let t=e.length-1;t>=0;t--){let n=e[t],i=n.command;if(i===`ls`||i===`cat`){r=n;break}if((i===`head`||i===`tail`)&&oh(ah(n)).length>0){r=n;break}}if(!r)return``;let i=oh(ah(r));if(r.command===`ls`){let e=i[i.length-1];if(!e||e===`.`)return``;let n=e.replace(/\/+/g,`/`);return n.startsWith(`./`)&&(n=n.slice(2)),n.endsWith(`/`)&&(n=n.slice(0,-1)),!n||!t.has(n)?``:`${n}/:\n`}let a=i.filter(e=>/\.(md|mdx)$/.test(e)&&n.has(e));return a.length===1?`==> ${a[0]} <==\n`:``}function RS(e){if(e.length===0)return``;let t=[``,`### Referenced files`,``];for(let n of e)t.push(PS(n)?FS(n):IS(n));return t.join(`
|
|
926
|
+
`)}async function zS(e,t){let n=[],r=[];return await Promise.all(t.map(async t=>{try{let i=await er(Dn(e,t));i.isDirectory()?r.push(t):i.isFile()&&n.push(t)}catch{/\.(md|mdx)$/i.test(t)&&n.push(t)}})),{files:n,dirs:r}}function BS(e,t){return q(t,{enrichedPaths:[],error:{category:e,message:t}},!0)}function VS(e,t){return e.map(e=>{let n=t(Zm(e.path));return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}})}async function HS(e,t){let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return BS(`shell_construct_blocked`,`exec failed: ${n.error}`);let{cwd:r,config:i,url:a}=n,o=Qx(e.command);if(`error`in o)return BS(o.error.category,o.error.message);let s=zx(o.stages),c=Bx(s),l=await jx(r),u=Ex(r),d=``,f=``;try{let e=await Dx(u,c);d=e.stdout,f=e.stderr}catch(e){return e instanceof Tx?BS(`output_overflow`,`Output exceeded 16 MB buffer. Narrow the command (e.g., add a more specific grep pattern, use head, restrict the path).`):BS(`shell_construct_blocked`,`exec failed: ${e instanceof Error?e.message:String(e)}`)}let p=await jx(r),m=Mx(l.snapshot,p.snapshot);if(m.changed.length>0)return BS(`security_invariant_violation`,`Security invariant violated: file(s) in the content directory were modified during a read-only exec call: ${m.changed.join(`, `)}. This indicates a parser bug; the command has been logged.`);let h=AS(d),g=mh(d,s),{files:_,dirs:v}=await zS(r,g),y=s.length===1&&s[0].command===`cat`&&_.length===1,b=i.folders,x=await Promise.all(_.map(e=>wS(e,{projectDir:r,serverUrl:a,folderRules:b},{includeRichFields:y}).catch(()=>({path:e,tags:[],backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null})))),S=await Promise.all(v.map(e=>ES(e,{projectDir:r,folderRules:b}).catch(()=>({path:e,type:`directory`,directMdCount:0,recursiveMdCount:0,childDirCount:0,truncated:!1}))));if(!y&&a&&x.length>0){let e=await xS(a,x.map(e=>vS(e.path))).catch(()=>null);if(e)for(let t of x){let n=e.get(vS(t.path));typeof n==`number`&&(t.backlinkCount=n)}}let ee=new Map(x.map(e=>[e.path,e])),te=new Map(S.map(e=>[e.path,e])),ne=[];for(let e of g){let t=ee.get(e);if(t){ne.push(t);continue}let n=te.get(e);n&&ne.push(n)}let C=jS(s),w=[];C.length>0&&w.push(`File${C.length>1?`s`:``} ${C.join(`, `)} appear${C.length===1?`s`:``} to be binary (image/PDF/etc.) — exec returns text only (NG8). For binary retrieval, use native Read.`);let re=NS(s,d);re&&w.push(re.banner),f&&w.push(`stderr: ${f.trim()}`);let ie=w.length>0?`${w.join(`
|
|
927
|
+
`)}\n\n`:``,T=LS(s,te,ee)+h.text,ae=`${ie}${T}${RS(ne)}`,{resolve:oe,ui:se}=await Xm({config:i,resolveCwd:async()=>r}),ce=VS(ne,oe),le=se;return q(ae,{enrichedPaths:ce,stdout:T,stdoutTruncated:h.truncated,cwd:r,...le?{ui:le}:{},...w.length>0?{warnings:w}:{}})}function US(e,t){e.tool(`exec`,kS,{command:u().describe(`Read-only bash command (allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut; pipes OK)`),cwd:u().optional().describe("Absolute host path to run the command from. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},async e=>{try{return await HS(e,t)}catch(e){return BS(`shell_construct_blocked`,`exec handler error: ${e instanceof Error?e.message:String(e)}`)}})}const WS=[`[Requires: Hocuspocus server] Find all pages that link to a given page.`,`Returns source page names, resolved titles, and context snippets as JSON.`,``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
|
|
928
|
+
`);function GS(e,t){e.tool(`get_backlinks`,WS,{docName:u().describe(`Target page docName`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=zm(e.docName);if(!a.ok)return K(a.error,!0);let o=await Bm(i,`/api/backlinks?docName=${encodeURIComponent(a.docName)}`);if(!o.ok)return K(`Error: ${o.error}`,!0);let{ok:s,...c}=o,l=c,{resolve:u,ui:d}=await Xm(t,r),f=(l.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,n=t?u(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),p={...l,backlinks:f,ui:d,cwd:r};return q(JSON.stringify(p,null,2),p)})}const KS=[`[Requires: Hocuspocus server] Find missing internal page targets across the corpus.`,`Returns grouped dead links keyed by missing target with source-doc rows as JSON.`,``,`**Parameters:**`,"- `sourceDocNames` (optional) — Referring source docs to narrow the audit with OR semantics"].join(`
|
|
929
|
+
`);function qS(e,t){e.tool(`get_dead_links`,KS,{sourceDocNames:y(u()).optional().describe(`Referring source docs to narrow the audit with OR semantics`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=new URLSearchParams;for(let t of e.sourceDocNames??[]){let e=zm(t);if(!e.ok)return K(e.error,!0);a.append(`sourceDocName`,e.docName)}let o=a.toString(),s=await Bm(i,`/api/dead-links${o?`?${o}`:``}`);if(!s.ok)return K(`Error: ${s.error}`,!0);let{ok:c,...l}=s,u=l,{resolve:d,ui:f}=await Xm(t,r),p=(u.deadLinks??[]).map(e=>{let t=typeof e.target==`string`?e.target:null,n=t?d(t):null,r=(e.sources??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,n=t?d(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}});return{...e,sources:r,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),m={...u,deadLinks:p,ui:f,cwd:r};return q(JSON.stringify(m,null,2),m)})}const JS=[`[Requires: Hocuspocus server] Find all pages that a given page links to.`,`Returns forward links as JSON.`,``,`**Parameters:**`,"- `docName` — Source page docName, typically without extension. A trailing `.md` or `.mdx` is stripped automatically."].join(`
|
|
930
|
+
`);function YS(e,t){e.tool(`get_forward_links`,JS,{docName:u().describe(`Source page docName`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=zm(e.docName);if(!a.ok)return K(a.error,!0);let o=await Bm(i,`/api/forward-links?docName=${encodeURIComponent(a.docName)}`);if(!o.ok)return K(`Error: ${o.error}`,!0);let{ok:s,...c}=o,l=c,{resolve:u,ui:d}=await Xm(t,r),f=(l.forwardLinks??[]).map(e=>{let t=e.kind===`doc`&&typeof e.docName==`string`?e.docName:null,n=t?u(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),p={...l,forwardLinks:f,ui:d,cwd:r};return q(JSON.stringify(p,null,2),p)})}const XS=[`[Requires: Hocuspocus server] List version history for a document.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,"Each entry includes a commit SHA that can be passed to `rollback_to_version`.",``,`**Parameters:**`,"- `docName` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `type` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
|
|
931
|
+
`);function ZS(e,t){e.tool(`get_history`,XS,{docName:u().describe(`Document name to query history for`),branch:u().optional().describe(`Branch name (default: current branch)`),limit:m().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:m().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),type:ge([`checkpoint`,`upstream`,`wip`]).optional().describe(`Filter by entry type`),author:u().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:u().optional().describe(`Exclude entries by this author name or email`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=zm(e.docName);if(!a.ok)return K(a.error,!0);let o=new URLSearchParams;o.set(`docName`,a.docName),e.branch&&o.set(`branch`,e.branch),e.limit!=null&&o.set(`limit`,String(e.limit)),e.offset!=null&&o.set(`offset`,String(e.offset)),e.type&&o.set(`type`,e.type),e.author&&o.set(`author`,e.author),e.excludeAuthor&&o.set(`excludeAuthor`,e.excludeAuthor);let s=await Bm(i,`/api/history?${o.toString()}`);if(!s.ok)return K(`Error: ${s.error}`,!0);let{ok:c,...l}=s,u=await Jm(a.docName,{config:t.config,resolveCwd:t.resolveCwd},r);return q(JSON.stringify(l,null,2),{...l,previewUrl:u?.url??null,...u?{previewUrlSource:u.source}:{}})})}const QS=[`[Requires: Hocuspocus server] Find the most-linked pages in the knowledge graph.`,`Returns hub pages ordered by inbound link count as JSON.`,``,`**Parameters:**`,"- `limit` (optional) — Maximum number of hubs to return (default 20)"].join(`
|
|
932
|
+
`);function $S(e,t){e.tool(`get_hubs`,QS,{limit:m().int().positive().optional().describe(`Maximum number of hubs to return`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=await Bm(i,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!a.ok)return K(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await Xm(t,r),d=(c.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,hubs:d,ui:u,cwd:r};return q(JSON.stringify(f,null,2),f)})}const eC=[`[Requires: Hocuspocus server] Find disconnected pages in the knowledge graph.`,`Returns orphaned pages as JSON.`,``,`**Parameters:**`,"- `mode` (optional) — Orphan lens: `incoming`, `outgoing`, or `both` (default `both`)"].join(`
|
|
933
|
+
`);function tC(e,t){e.tool(`get_orphans`,eC,{mode:ge(re).optional().describe(`Filter which type of graph disconnection to surface`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=await Bm(i,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!a.ok)return K(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await Xm(t,r),d=(c.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,orphans:d,ui:u,cwd:r};return q(JSON.stringify(f,null,2),f)})}function nC(e,t){return`${Pm(`ingest`)}Capture this external source into the project knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled INTO the knowledge base here so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a knowledge-base claim — agent-initiated fetches are not exempt. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
|
|
931
934
|
|
|
932
935
|
Source: ${e}
|
|
933
936
|
|
|
934
|
-
The content directory for this project is **\`${t}\`** (from \`${
|
|
937
|
+
The content directory for this project is **\`${t}\`** (from \`${T}/config.yml\`).
|
|
935
938
|
|
|
936
939
|
## Step 0: Is this source worth preserving?
|
|
937
940
|
|
|
@@ -1008,20 +1011,20 @@ If the source is directly relevant to an existing article or research doc, updat
|
|
|
1008
1011
|
- **No promotion to a canonical article** — that's the \`consolidate\` tool's job, later
|
|
1009
1012
|
- **No silent chaining into research** — ingest completes on its own; the user explicitly opts into \`research\`
|
|
1010
1013
|
- **No synthesis inside the raw file** — the takeaways live in chat or a separate summary doc, never mixed into the preserved source
|
|
1011
|
-
`}const
|
|
1012
|
-
`);function
|
|
1013
|
-
`);function
|
|
1014
|
-
`);function
|
|
1015
|
-
`)}function
|
|
1016
|
-
`)}function
|
|
1017
|
-
`)}function
|
|
1018
|
-
`)}function
|
|
1019
|
-
`)}function
|
|
1020
|
-
`);function
|
|
1021
|
-
`),v)})}function
|
|
1014
|
+
`}const rC=[`Fetch an external source (URL or local file) and save raw content as reference material in the project content directory.`,`Raw preservation only — no analysis or interpretation.`,`The knowledge base is closed-loop: web sources cited by KB docs MUST resolve to a local doc captured here, not bare URLs.`,``,`**Use when:**`,`- Capturing reference material for the project knowledge base`,`- Saving a URL or document for later research`,`- Archiving an external source alongside the codebase`,`- The user shares a URL or document they want preserved`,"- **You yourself fetched a URL (`WebFetch` / `WebSearch` / equivalent) to ground a claim that is about to land in a knowledge-base doc** — agent-initiated fetches are not exempt from the closed-loop rule",``,`**Triggers on:**`,`- "ingest", "save this source", "capture this URL", "add to external sources"`,`- User shares a URL, article, or document to preserve in the knowledge base`,`- Agent fetches a URL via WebFetch/WebSearch to support a knowledge-base claim — preserve the source before citing it`,`- Research workflow needs raw sources before analysis`].join(`
|
|
1015
|
+
`);function iC(e,t){e.tool(`ingest`,rC,{source:u().describe(`URL, file path, or identifier of the source to ingest`),cwd:u().optional().describe(Om)},async e=>{let n=await Lm(t.resolveCwd,t.config,e.cwd);return n.ok?q(nC(e.source,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}const aC=[`[Requires: Hocuspocus server] List available documents from the Hocuspocus server.`,`Returns document names, optionally filtered by directory.`,``,`**Parameters:**`,"- `dir` (optional) — Filter to documents in this directory"].join(`
|
|
1016
|
+
`);function oC(e,t){e.tool(`list_documents`,aC,{dir:u().optional().describe(`Optional directory to filter documents`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=await Bm(i,`/api/documents${e.dir?`?dir=${encodeURIComponent(e.dir)}`:``}`);if(!a.ok)return K(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await Xm(t,r),d=(c.documents??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,documents:d,ui:u,cwd:r};return q(JSON.stringify(f,null,2),f)})}const sC=[`Read a wiki file with enriched context: contents + frontmatter metadata + recent shadow-repo activity (agent vs human attribution) + backlink/forward-link context.`,``,`**Use when:**`,`- Loading an article for context`,`- Understanding who changed a file recently and whether it was an agent or human`,`- Seeing how this page links out and what links back to it`,``,"Prefer this over your native `Read` for wiki files — one call returns what otherwise takes 3-4.",``,`**Parameters:**`,"- `path` — Project-root-relative path to the file, including extension (e.g. `articles/auth/sso.md`). To pass this document to `edit_document` / `write_document` / `get_backlinks`, strip the extension (they take extension-less `docName`).","- `since` (reserved) — Reserved for shadow-log since-filter; currently unused."].join(`
|
|
1017
|
+
`);function cC(e){if(!e||e.length===0)return``;let t=[``,`### Recent activity (OK edits)`,``];for(let n of e){let e=n.writerClassification===`agent`?`agent: ${n.writerName}`:n.writerClassification===`principal`?`human: ${n.writerName}`:`${n.writerClassification}: ${n.writerName}`,r=n.hash.slice(0,7);t.push(`- ${r} ${n.date} [${e}] ${n.message}`)}return t.join(`
|
|
1018
|
+
`)}function lC(e){if(!e||e.length===0)return``;let t=[``,`### Commit history (project git)`,``];for(let n of e){let e=n.hash.slice(0,7);t.push(`- ${e} ${n.date} ${n.authorName} — ${n.subject}`)}return t.join(`
|
|
1019
|
+
`)}function uC(e){if(!e||e.length===0)return``;let t=[``,`### Backlinks (${e.length})`,``];for(let n of e){let e=n.title?` — "${n.title}"`:``,r=n.snippet?` — "${n.snippet}"`:``;t.push(`- ${n.source}${e}${r}`)}return t.join(`
|
|
1020
|
+
`)}function dC(e){if(!e||e.length===0)return``;let t=[``,`### Forward links (${e.length})`,``];for(let n of e){if(n.kind===`external`){let e=n.title?` — "${n.title}"`:``,r=n.snippet?` — "${n.snippet}"`:``;t.push(`- ${n.url}${e}${r}`);continue}let e=n.title?` — "${n.title}"`:``,r=n.snippet?` — "${n.snippet}"`:``;t.push(`- ${n.docName}${e}${r}`)}return t.join(`
|
|
1021
|
+
`)}function fC(e){return e.replace(/^\.\//,``).replace(/^\/+/,``)}function pC(e){return e.replace(/\.(md|mdx)$/i,``)}async function mC(e,t){let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)throw Error(n.error);let{cwd:r,config:i,url:a}=n,o=fC(e.path),s=Dn(r,o),c=i.mcp.tools.read_document.historyDepth,[l,u]=await Promise.all([Qn(s,`utf-8`),wS(o,{projectDir:r,serverUrl:a,historyDepth:c,folderRules:i.folders},{includeRichFields:!0})]),d=o.split(`/`).pop()?.replace(/\.md$/,``).replace(/\.mdx$/,``)??o,f=u.title??d,p=u.description??``,m=u.tags,h=[];h.push(`## ${f}`),p&&h.push(`**Description:** ${p}`),m.length>0&&h.push(`**Tags:** ${m.join(`, `)}`),h.push(`**Path:** ${o}`);let g=cC(u.history);g&&h.push(g);let _=lC(u.projectHistory);_&&h.push(_);let v=uC(u.backlinks);v&&h.push(v);let y=dC(u.forwardLinks);return y&&h.push(y),h.push(``,`### Content`,``,l),h.join(`
|
|
1022
|
+
`)}function hC(e,t){e.tool(`read_document`,sC,{path:u().describe(`Project-root-relative path to the file`),since:u().optional().describe(`Reserved; currently unused (§15 Future Work)`),cwd:u().optional().describe("Absolute host path to resolve `path` against. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},async e=>{try{let n=await mC(e,t),r=await Jm(pC(fC(e.path)),{config:t.config,resolveCwd:t.resolveCwd},await t.resolveCwd(e.cwd));return r?q(n,{previewUrl:r.url,previewUrlSource:r.source}):q(n,{previewUrl:null})}catch(e){return K(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const gC=["[Requires: Hocuspocus server] Rename a document through the managed rename flow at `POST /api/rename`.",`Renames the target document and rewrites inbound wiki-links plus supported internal inline Markdown links in affected docs.`,``,`**Parameters:**`,"- `docName` — Current document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `newDocName` — New document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline. If omitted, a default like "Renamed X → Y" is generated. Provide your own summary to explain the why. Avoid including secrets or PII — summaries are persisted to git history.'].join(`
|
|
1023
|
+
`);function _C(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:n}=e;return typeof t==`string`&&typeof n==`string`?[{fromDocName:t,toDocName:n}]:[]}):[]}function vC(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:n}=e;return typeof t==`string`&&typeof n==`number`?[{docName:t,rewrites:n}]:[]}):[]}function yC(e,t,n=`${t}s`){return e===1?t:n}function bC(e,t){e.tool(`rename_document`,gC,{docName:u().describe(`Current document name`),newDocName:u().describe(`New document name`),summary:km.describe(`Optional one-line user-outcome description (≤80 chars). Defaults to "Renamed X → Y" when omitted. Appears as a bullet in the timeline.`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=zm(e.docName);if(!a.ok)return K(a.error,!0);let o=zm(e.newDocName);if(!o.ok)return K(o.error,!0);let s=t.identityRef?.current,c=await Vm(i,`/api/rename`,{docName:a.docName,newDocName:o.docName,...e.summary===void 0?{}:{summary:e.summary},...s?{agentId:s.connectionId,agentName:s.displayName,clientName:s.clientInfo?.name,colorSeed:s.colorSeed}:{}});if(!c.ok){let e=typeof c.error==`string`?c.error:`Rename failed`,t={ok:!1,error:e};return q(`Error: ${e}`,t,!0)}let l=_C(c.renamed),u=vC(c.rewrittenDocs),d=l.map(({fromDocName:e,toDocName:t})=>`${e} -> ${t}`).join(`, `)||`${a.docName} -> ${o.docName}`,f=u.length===0?`No inbound links required updates.`:`Rewrote ${u.length} ${yC(u.length,`document`)}.`,p={config:t.config,resolveCwd:t.resolveCwd},m=await Jm(o.docName,p,r),h=await Jm(a.docName,p,r),g=c.summary&&typeof c.summary==`object`?c.summary:void 0,_=typeof g?.hint==`string`?g.hint:void 0,v={ok:!0,renamed:l,rewrittenDocs:u,previewUrl:m?.url??null,...m?{previewUrlSource:m.source}:{},...h?{previousPreviewUrl:h.url}:{},...g?{summary:g}:{}},y=[`Renamed ${d}. ${f}`];return _&&y.push(_),q(y.join(`
|
|
1024
|
+
`),v)})}function xC(e,t){return`${Pm(`research`)}Conduct **evidence-driven research** on this topic and produce a provisional research article in the Open Knowledge content directory. This workflow mirrors the discipline of the \`eng:research\` skill, scoped to Open Knowledge's wiki-provisional layer.
|
|
1022
1025
|
|
|
1023
1026
|
Topic: ${e}
|
|
1024
|
-
Content directory: \`${t}\` (from \`${
|
|
1027
|
+
Content directory: \`${t}\` (from \`${T}/config.yml\`)
|
|
1025
1028
|
|
|
1026
1029
|
## Three paths
|
|
1027
1030
|
|
|
@@ -1368,16 +1371,16 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
1368
1371
|
- **Don't skip the scoping gate in Supervised mode.** The user's rubric shapes everything downstream; you cannot recover a wrong-scope article cheaply.
|
|
1369
1372
|
- **Don't mix 1P codebase analysis into the article unless asked.** Findings drift from factual synthesis to opinion when you do.
|
|
1370
1373
|
- **Don't overwrite existing research silently.** If the topic was researched before, either iterate (Path C) or create a clearly-named successor (\`crdt-alternatives-2.md\`) and mark the old one as superseded.
|
|
1371
|
-
`}const
|
|
1372
|
-
`);function
|
|
1373
|
-
`);function
|
|
1374
|
-
`),{previewUrl:p?.url??null,...p?{previewUrlSource:p.source}:{},...u?{summary:u}:{}})})}const
|
|
1375
|
-
`);function
|
|
1376
|
-
`);function
|
|
1377
|
-
`),structured:{query:e.query,matchCount:d.length,fileCount:m.length,truncated:u,results:v,ui:p,cwd:r}}}function
|
|
1378
|
-
`);function
|
|
1379
|
-
`);function
|
|
1380
|
-
`);if(!u&&!f&&!p&&!m&&!h)return
|
|
1374
|
+
`}const SC=[`Analyze a topic by gathering sources via ingest and writing provisional findings into the project content directory.`,`Provisional, not canonical — findings live here until decisions solidify.`,``,`**Use when:**`,`- Researching a topic before committing to an approach`,`- Exploring a decision space or comparing alternatives`,`- Synthesizing multiple sources into structured analysis`,`- Spec conversations and exploratory work that is not yet canonical`,``,`**Triggers on:**`,`- "research", "investigate", "compare options for", "analyze alternatives"`,`- User asks to explore trade-offs, gather evidence, or evaluate approaches`,`- A decision needs structured analysis grounded in external sources`].join(`
|
|
1375
|
+
`);function CC(e,t){e.tool(`research`,SC,{topic:u().describe(`The topic, question, or anchor URL to research`),cwd:u().optional().describe(Om)},async e=>{let n=await Lm(t.resolveCwd,t.config,e.cwd);return n.ok?q(xC(e.topic,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}const wC=[`[Requires: Hocuspocus server] Restore a document to a historical version via the CRDT layer.`,`The restore is append-only — it creates a new version with the old content,`,`preserving all history. All connected editors see the change in real-time.`,``,`**Parameters:**`,"- `docName` — Document name to restore, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `commitSha` — The 40-character SHA of the shadow repo commit to restore to."," Use `get_history` to find available versions.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline. If omitted, a default like "Restored to <sha-short>" is generated. Provide your own summary to explain the why. Avoid including secrets or PII — summaries are persisted to git history.'].join(`
|
|
1376
|
+
`);function TC(e,t){e.tool(`rollback_to_version`,wC,{docName:u().describe(`Document name to restore`),commitSha:u().length(40).regex(/^[0-9a-f]+$/i).describe(`40-character commit SHA from the shadow repo timeline`),summary:km.describe(`Optional one-line user-outcome description (≤80 chars). Defaults to "Restored to <sha-short>" when omitted. Appears as a bullet in the timeline.`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=zm(e.docName);if(!a.ok)return K(a.error,!0);let o=a.docName,s=await Bm(i,`/api/history/${e.commitSha}?docName=${encodeURIComponent(o)}`);if(!s.ok)return K(`Error: ${s.error??`Version not found`}`,!0);let c=t.identityRef?.current,l=await Vm(i,`/api/rollback`,{docName:o,commitSha:e.commitSha,...e.summary===void 0?{}:{summary:e.summary},...c?{agentId:c.connectionId,agentName:c.displayName,clientName:c.clientInfo?.name,colorSeed:c.colorSeed}:{}});if(!l.ok)return K(`Error: ${l.error}`,!0);let u=l.summary&&typeof l.summary==`object`?l.summary:void 0,d=typeof u?.hint==`string`?u.hint:void 0,f=[`Restored "${o}" to version ${e.commitSha.slice(0,8)} (${s.author}, ${s.timestamp}). The change has been applied to all connected editors.`];d&&f.push(d);let p=await Jm(o,{config:t.config,resolveCwd:t.resolveCwd},r);return q(f.join(`
|
|
1377
|
+
`),{previewUrl:p?.url??null,...p?{previewUrlSource:p.source}:{},...u?{summary:u}:{}})})}const EC=[`[Requires: Hocuspocus server] Save a version checkpoint of all documents.`,`Creates a checkpoint commit in the shadow repo and project repo,`,`preserving the current state of all documents. The checkpoint can later`,"be found via `get_history` and restored via `rollback_to_version`."].join(`
|
|
1378
|
+
`);function DC(e,t,n,r,i){e.tool(`save_version`,EC,{cwd:u().optional().describe(Om)},async(e={})=>{let a=await Rm(r,t,n,e.cwd);if(!a.ok)return K(`Error: ${a.error}`,!0);if(!a.url)return K(Am,!0);let{url:o}=a,s=i?.current,c=await Vm(o,`/api/save-version`,{...s?{writers:[{id:`agent-${s.connectionId}`,name:s.displayName,email:`agent-${s.connectionId}@openknowledge.local`}]}:{}});return c.ok?q(`Checkpoint saved. Checkpoint ref: ${c.checkpointRef}`,{checkpointRef:c.checkpointRef,previewUrl:null}):K(`Error: ${c.error}`,!0)})}const OC=[`Search wiki content with metadata-enriched results. Matches are grouped by file; each file is annotated with its title, description, and tags so you can judge relevance without opening it first.`,``,`**Use when:**`,`- Finding all articles mentioning a topic`,`- Locating a specific term across the wiki before deciding which file to read`,``,"Prefer this over your native `Grep` for wiki search — results include article metadata so you can skip irrelevant matches without extra reads.",``,`**Parameters:**`,"- `query` — Literal text to search for (fixed-string match, no regex)","- `case_sensitive` (optional, default false) — case-sensitive match"].join(`
|
|
1379
|
+
`);function kC(e){let t=new Map;for(let n of e){let e=t.get(n.path);e?e.push(n):t.set(n.path,[n])}return[...t.entries()].map(([e,t])=>({path:e,matches:t}))}async function AC(e,t){let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)throw Error(n.error);let{cwd:r,config:i,url:a}=n,o=i.mcp.tools.search.maxResults,s=i.content.include,c=i.content.exclude,l=await kx(e.query,r,{caseInsensitive:!(e.case_sensitive??!1),include:s,exclude:[...c,`node_modules`,`.git`,`.claude`,`.changeset`,T],maxResults:o+1}),u=l.length>o,d=u?l.slice(0,o):l,{resolve:f,ui:p}=await Xm({config:i,resolveCwd:async()=>r},r);if(d.length===0)return{text:`No matches for "${e.query}".`,structured:{query:e.query,matchCount:0,fileCount:0,truncated:!1,results:[],ui:p,cwd:r}};let m=kC(d),h=new Map,g=i.folders;await Promise.all(m.map(async e=>{try{let t=await wS(e.path,{projectDir:r,serverUrl:a,folderRules:g});h.set(e.path,t)}catch{}}));let _=[];_.push(`## Search results for "${e.query}" (${d.length} match${d.length===1?``:`es`} in ${m.length} file${m.length===1?``:`s`})`,``);let v=[];for(let e of m){let t=h.get(e.path),n=t?.title??e.path;_.push(`### ${n} (${e.path})`),t?.tags?.length&&_.push(`Tags: ${t.tags.join(`, `)}`),t?.description&&_.push(`${t.description}`);for(let t of e.matches)_.push(`- Line ${t.line}: ${t.text}`);_.push(``);let r=Zm(e.path),i=f(r);v.push({path:e.path,docName:r,title:t?.title??null,description:t?.description??null,tags:t?.tags??[],matches:e.matches.map(e=>({line:e.line,text:e.text})),previewUrl:i?.url??null,...i?{previewUrlSource:i.source}:{}})}return u&&_.push(`_${d.length} of ${l.length}+ matches shown. Raise \`mcp.tools.search.maxResults\` in config.yml to see more._`),{text:_.join(`
|
|
1380
|
+
`),structured:{query:e.query,matchCount:d.length,fileCount:m.length,truncated:u,results:v,ui:p,cwd:r}}}function jC(e,t){e.tool(`search`,OC,{query:u().describe(`Literal text to search for`),case_sensitive:p().optional().describe(`Case-sensitive search (default false)`),cwd:u().optional().describe("Absolute host path to search in. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},async e=>{try{let{text:n,structured:r}=await AC(e,t);return r?q(n,r):K(n)}catch(e){return K(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const MC=[`[Requires: Hocuspocus server] Find missing link candidates for a target page.`,"Returns JSON with structure: `{ target: { docName, title, aliases }, mentions: [{ source, excerpt, offset }], truncated }`.","Each mention includes an `offset` you can pass to `edit_document` for precision patching.","When `truncated` is true, the scan hit its time budget before reading every admitted document.",``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
|
|
1381
|
+
`);function NC(e,t){e.tool(`suggest_links`,MC,{docName:u().describe(`Target page docName`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=zm(e.docName);if(!a.ok)return K(a.error,!0);let o=await Bm(i,`/api/suggest-links?docName=${encodeURIComponent(a.docName)}`);if(!o.ok)return K(`Error: ${o.error}`,!0);let{ok:s,...c}=o,l=await Jm(a.docName,{config:t.config,resolveCwd:t.resolveCwd},r);return q(JSON.stringify(c,null,2),{...c,previewUrl:l?.url??null,...l?{previewUrlSource:l.source}:{}})})}const PC=[`[Requires: Hocuspocus server] Write markdown content to a document via the CRDT layer.`,`Content is applied through Hocuspocus and propagated to all connected editors in real-time.`,``,'**Link liberally.** Every noun-phrase that names another document in this knowledge base should be a `[[wiki-link]]`, not plain prose. Backlinks are the primary navigation surface — underlinked documents become islands. Redlinks (links to pages that don\'t exist yet) are fine; they signal "this should exist." Prefer `[[Page Name]]` over Markdown `[text](./page.md)` — only wiki-links participate in the backlinks index.',``,`**Parameters:**`,'- `docName` — Document name, typically without extension (e.g., "my-doc" or "notes/meeting"). A trailing `.md` or `.mdx` is stripped automatically. New documents are created as `.md` by default; to create a `.mdx` file, first place it on disk, then use this tool for edits.',"- `markdown` — Markdown content to write",'- `position` — Where to insert: "append", "prepend", or "replace"','- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Added 3 lines"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
|
|
1382
|
+
`);function FC(e,t){e.tool(`write_document`,PC,{docName:u().describe(`Document name to write to`),markdown:u().describe(`Markdown content to write`),position:ge([`append`,`prepend`,`replace`]).describe(`Where to insert the content`),summary:km,cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n;if(!a)return K(Am,!0);let o=zm(e.docName);if(!o.ok)return K(o.error,!0);let s=t.identityRef?.current,c=await Vm(a,`/api/agent-write-md`,{docName:o.docName,markdown:e.markdown,position:e.position,...e.summary===void 0?{}:{summary:e.summary},...s?{agentId:s.connectionId,agentName:s.displayName,clientName:s.clientInfo?.name,colorSeed:s.colorSeed}:{}});if(!c.ok)return K(`Error: ${c.error}`,!0);let l=_e(ve(i,r)),u=Qm(o.docName,{config:i,lockDir:l}),d=typeof c.subscriberCount==`number`?c.subscriberCount:void 0,f=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,p=d===0,m=Array.isArray(c.hints)?c.hints:void 0,h=c.summary&&typeof c.summary==`object`?c.summary:void 0,g=typeof h?.hint==`string`?h.hint:void 0,_=[`Written successfully (${e.position}).`];if(u&&_.push(`Preview: ${u.url}`),f&&_.push(u?`Open ${u.url} in your preview browser.`:`No preview attached. Start the UI.`),g&&_.push(g),m)for(let e of m)e.message&&_.push(e.message);let v=_.join(`
|
|
1383
|
+
`);if(!u&&!f&&!p&&!m&&!h)return K(v);let y={};return u&&(y.previewUrl=u.url,y.previewUrlSource=u.source),f&&(y.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:u?.url??null}),m&&(y.hints=m),h&&(y.summary=h),q(v,y)})}function IC(e,t){let n=t.logger,r=Dm(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(pm()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(pm()??n)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...r?{explicit:r}:{}}),t}};US(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),iC(r,{config:t.config,resolveCwd:i(`ingest`)}),CC(r,{config:t.config,resolveCwd:i(`research`)}),Wm(r,{config:t.config,resolveCwd:i(`consolidate`)}),hC(r,{resolveCwd:i(`read_document`),config:t.config,serverUrl:t.serverUrl}),jC(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl}),NC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`suggest_links`)}),FC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write_document`),identityRef:t.identityRef}),eh(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit_document`),identityRef:t.identityRef}),bC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`rename_document`),identityRef:t.identityRef}),ZS(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_history`)}),DC(r,t.config,t.serverUrl,i(`save_version`),t.identityRef),TC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`rollback_to_version`),identityRef:t.identityRef}),oC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`list_documents`)}),GS(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_backlinks`)}),YS(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_forward_links`)}),tC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_orphans`)}),$S(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_hubs`)}),qS(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_dead_links`)})}function LC(e){return e&&typeof e==`object`&&`code`in e&&typeof e.code==`string`?e.code:e instanceof Error&&e.name?e.name:typeof e}var RC=class extends Error{};function zC(e){let t=Ve(e.startupCwd),n=null,r=null,i=async()=>n===null?(r||=(async()=>{let t=await e.listRoots(),r=await Promise.all(t.roots.map(async e=>e.uri.startsWith(`file://`)?await Ve(Jn(e.uri)):null)),i=[...new Set(r.filter(e=>e!==null))];return n=i,e.logger?.info(`roots resolved`,{roots:i,count:i.length}),i})().finally(()=>{r=null}),await r):n;return{async resolveCwd(n){if(n){let t=await Ve(n);return e.logger?.debug(`cwd resolved`,{cwd:t,routing:`explicit`}),t}if(e.bypassProjectSelection){let n=await t;return e.logger?.debug(`cwd resolved`,{cwd:n,routing:`bypass`}),n}let r;try{r=await i()}catch(t){throw e.logger?.warn(`roots/list unavailable`,{error:t instanceof Error?t.message:String(t),errorType:LC(t)}),new RC(`Client roots unavailable; pass cwd explicitly.`)}if(r.length===0)throw new RC(`No client roots available; pass cwd explicitly.`);if(r.length>1)throw new RC(`Multiple roots available; pass cwd explicitly.`);return e.logger?.debug(`cwd resolved`,{cwd:r[0],routing:`single-root`}),r[0]},invalidateRoots(){n=null,r=null,e.logger?.info(`roots cache invalidated`)}}}function BC(e){let t=Ve(e.startupCwd),n;return{async resolveCwdForTools(t){let r=await e.resolveCwd(t);return n=r,r},async getKeepaliveCwd(){return e.bypassProjectSelection?await t:n}}}let VC;function HC(e,t){let{dir:n,include:r,exclude:i}=e.content,a=i.length>0?i.map(e=>`\`${e}\``).join(`, `):`(none)`;return`# Open Knowledge (OK) — collaborative markdown via MCP
|
|
1381
1384
|
|
|
1382
1385
|
**STOP — native tools on in-scope \`.md\` / \`.mdx\`.** Do NOT use host-native \`Read\`, \`Grep\`, \`Glob\`, \`Edit\`, \`Write\` on markdown inside the content dir. Reads: \`exec\` / \`read_document\` / \`search\`. Writes: \`write_document\` / \`edit_document\` ONLY.
|
|
1383
1386
|
|
|
@@ -1398,8 +1401,8 @@ Claude Code Desktop: \`preview_start("open-knowledge-ui")\`. Other hosts: open-U
|
|
|
1398
1401
|
Detailed conventions (wiki-link authoring, frontmatter, anti-patterns) live in the installed \`open-knowledge\` Agent Skill. If missing, run \`npx @inkeep/open-knowledge init\`.
|
|
1399
1402
|
|
|
1400
1403
|
**Escape hatch.** Native \`Read\`/\`Grep\`/\`Glob\` on \`.md\` is allowed ONLY when no OK MCP is registered, or immediately after an OK MCP call failed — then begin your sentence with \`Open Knowledge MCP unavailable:\`. Non-markdown: native tools always.
|
|
1401
|
-
`}async function HC(e,t){try{let t=e.replace(`ws://`,`http://`).replace(`wss://`,`https://`);return(await fetch(`${t}/api/document`,{signal:AbortSignal.timeout(2e3)})).ok}catch(n){return t.warn(`Hocuspocus probe failed`,{serverUrl:e,error:n instanceof Error?n.message:String(n)}),!1}}async function UC(e){let{projectDir:t,serverUrl:n,config:r,startupConfig:i,bypassProjectSelection:a=!1}=e;if(BC=lm(),BC.info(`MCP server starting`,{startupCwd:t,bypassProjectSelection:a,serverUrlType:typeof n==`string`?`explicit`:`lazy`}),typeof n==`string`){let e=await HC(n,BC);BC.info(`Hocuspocus detection complete`,{serverUrl:n,available:e})}else BC.info(`server discovery is lazy per effective cwd`);let o=new qp({name:l,version:c},{instructions:VC(i,{dynamicConfig:typeof r==`function`&&!a})}),s=RC({startupCwd:t,bypassProjectSelection:a,listRoots:()=>o.server.listRoots(),logger:BC}),u=zC({startupCwd:t,resolveCwd:s.resolveCwd,bypassProjectSelection:a}),d=u.resolveCwdForTools;o.server.setNotificationHandler(id,async()=>{s.invalidateRoots()});let f=async e=>{if(typeof n==`string`)return n.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await d();return(typeof n==`function`?await n(t):n)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},p=Jn(),m=process.env.AGENT_LABEL||void 0,h={current:{connectionId:p,label:m,displayName:m??`Agent`,colorSeed:m??p}};o.server.oninitialized=()=>{let e=o.server.getClientVersion();h.current={connectionId:p,clientInfo:e?{name:e.name,version:e.version}:void 0,label:m,displayName:m??e?.name??`Agent`,colorSeed:m??e?.name??p},BC?.info(`agent identity established`,{displayName:h.current.displayName,connectionId:p.slice(0,8),clientName:e?.name})},FC(o,{serverUrl:f,resolveCwd:d,config:r,identityRef:h,logger:BC});let g=new om;await o.connect(g),BC.info(`MCP server running on stdio`);let{startKeepalive:_}=await import(`./keepalive-CZzB5k1h.mjs`),v=_({resolveWsUrl:async()=>{let e=await u.getKeepaliveCwd();if(!e)return;let t=await f(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},connectionId:`agent-${p}`,logger:BC.child(`keepalive`)}),y=e=>{BC?.info(`MCP server shutting down`,{signal:e});try{v.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>y(`SIGINT`)),process.on(`SIGTERM`,()=>y(`SIGTERM`))}const WC=[`/_npx/`,`/.npm/_npx/`,`/_bunx/`,`/.bun/install/cache/`,`/pnpm/dlx/`],GC=new Set([`/usr/local/bin/ok`,`/usr/local/bin/open-knowledge`,`/opt/homebrew/bin/ok`,`/opt/homebrew/bin/open-knowledge`]);function KC(e){if(!e||e.length===0)return`unknown`;for(let t of WC)if(e.includes(t))return`npx-cache`;return GC.has(e)||e.startsWith(`/Applications/`)||e.includes(`.app/Contents/`)?`stable-shim`:e.startsWith(`/`)?`absolute-pin`:`unknown`}function qC(e,t){switch(e){case`npx-cache`:return"This MCP was launched via a package-manager cache (npx / bunx / pnpm dlx) and just resolved a different package version than the running server. Stop `ok start` so the next launch matches, or run `ok init --pin` for a stable launch path.";case`stable-shim`:return"The CLI shim was likely upgraded while a project server is still running (a desktop auto-update or `npm i -g` / `brew upgrade` will do this). Close and reopen the project window, or stop `ok start`, so the next launch matches.";case`absolute-pin`:return`This MCP is launched from a pinned path${t?` (${t})`:``} that no longer matches the running server. Re-run \`ok init --pin\` from your current install to refresh, or stop \`ok start\` so the next launch matches.`;default:return"Stop `ok start` and retry, or align CLI versions across your installs."}}function JC(e){return e?/\bENOENT\b/i.test(e):!1}function YC(e){switch(KC(e)){case`absolute-pin`:return"This failure usually means the CLI entry script no longer exists at the pinned path (common after changing how you installed Open Knowledge or removing an old global package). Re-run `ok init --pin` from your current install and update your editor MCP config, or use an unpinned launcher such as `npx @inkeep/open-knowledge mcp`.";case`stable-shim`:return"The expected `ok` shim is missing on disk. Reinstall or repair your Open Knowledge CLI. If you switched install sources, run `ok init --pin` again so your editor matches the binary you have.";case`npx-cache`:return"The package-manager cache copy used for this launch may have been removed. Retry once, or run `ok init --pin` so your editor uses a durable absolute path.";default:return"Often means the configured launcher path does not exist (stale pin, moved install, or missing runtime). Re-run `ok init --pin` from your current install or fix the MCP command in your editor settings."}}function XC(e,t,n){let r=`spawn failed: ${e}${t?` stderr:\n${t}`:``}`;return JC(e)&&(r+=`\n\n${YC(n)}`),r}function ZC(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function QC(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t))return{action:`disk-only`,message:`invalid --port value '${e.portOverride}' — disk-only mode`};if(t>0){let n=`ws://${e.host}:${t}`;return{action:`connect`,url:n,message:`using --port override, connecting to ${n}`}}return{action:`disk-only`,message:`--port=0 — disk-only mode`}}let t=e.readLock();if(t&&t.port>0&&e.isAlive(t.pid)){let n=e.expectedProtocolVersion??1,r=t.protocolVersion;if(r===n){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}let i=r===void 0?`unknown (pre-version-field lock)`:`v${r}`,a=t.runtimeVersion?` runtime ${t.runtimeVersion}`:``,o=e.launchPath??process.argv[1],s=KC(o),c=qC(s,o);return{action:`incompatible`,message:`Open Knowledge server at port ${t.port} (pid ${t.pid}${a}) speaks protocol ${i}; this MCP needs protocol v${n}.\n`+c,expectedProtocolVersion:n,actualProtocolVersion:r,lock:t,launchShape:s,launchPath:o}}return e.envAutoStart===`0`?{action:`disk-only`,message:`auto-spawn disabled via OK_MCP_AUTOSTART=0 — disk-only mode`}:e.configAutoStart?t?{action:`spawn`,message:`existing lock is not usable (port=${t.port}, pid=${t.pid}) — spawning ok start`}:{action:`spawn`,message:`no running instance — spawning ok start`}:{action:`disk-only`,message:`auto-spawn disabled via config.mcp.autoStart=false — disk-only mode`}}async function $C(e){let t=e.readLock??(()=>ge(e.lockDir)),n=e.isAlive??_e,r=e.sleep??(e=>Yn(e)),i=e.spawn??vn,a=e.readErrorLog??(e=>kn(e)?Mn(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>jn(e,`w`)),s=e.closeFd??On,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=e.launchPath??process.argv[1],d=QC({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n,launchPath:e.launchPath});if(e.logger?.info(`auto-start decision`,{action:d.action,message:d.message,contentDir:e.contentDir}),d.action===`connect`)return{serverUrl:d.url,message:d.message};if(d.action===`disk-only`)return{serverUrl:void 0,message:d.message};if(d.action===`incompatible`)throw e.logger?.error(`protocol mismatch — refusing to connect`,void 0,{expectedProtocolVersion:d.expectedProtocolVersion,actualProtocolVersion:d.actualProtocolVersion,lockPid:d.lock.pid,lockPort:d.lock.port,lockRuntimeVersion:d.lock.runtimeVersion,launchShape:d.launchShape,launchPath:d.launchPath}),Error(d.message);kn(e.lockDir)||An(e.lockDir,{recursive:!0});let f=wn(e.lockDir,`last-spawn-error.log`),p=o(f),m,h,g=gn();e.logger?.info(`spawning server`,{command:g.command,cwd:e.contentDir,timeoutMs:c});try{try{m=i(g.command,[...g.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,p],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,OK_PARENT_PID:String(process.pid)}}),m.on(`error`,e=>{h=e instanceof Error?e.message:String(e)}),m.unref()}catch(e){h=e instanceof Error?e.message:String(e)}}finally{try{s(p)}catch{}}let _=Date.now()+c;for(;Date.now()<_;){if(h){let t=a(f);throw e.logger?.error(`spawn failed`,void 0,{error:h,stderr:t,launchPath:u,stalePinHint:JC(h)}),Error(XC(h,t,u))}await r(l);let i=t();if(i&&i.port>0&&n(i.pid)){let t=`ws://localhost:${i.port}`;return e.logger?.info(`server ready after spawn`,{url:t,pid:i.pid}),{serverUrl:t,message:`spawned ok start; connected at ${t} (pid ${i.pid})`}}}if(h){let t=a(f);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:h,stderr:t,launchPath:u,stalePinHint:JC(h)}),Error(XC(h,t,u))}let v=a(f),y=(c/1e3).toFixed(c%1e3==0?0:2),b=m?.pid,x=``;throw typeof b==`number`&&(x=n(b)?` child pid=${b} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${b} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:b,childAlive:typeof b==`number`?n(b):void 0,stderr:v||void 0}),Error(`server did not start within ${y}s.${x}${v?` stderr:\n${v}`:``}`)}function ew(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)return async()=>void 0;let n=`ws://${e.host}:${t}`;return async()=>n}let t=e.ensureServerRunningFn??$C,n=e.cacheMs??1e3,r=new Map,i=new Map;return async a=>{let o=await Re(a??e.startupCwd),s=Date.now(),c=r.get(o);if(c&&c.expiresAt>s)return e.logger?.debug(`server url cache hit`,{cwd:o,url:c.url}),c.url;let l=i.get(o);if(l)return e.logger?.debug(`server url resolution pending`,{cwd:o}),await l;e.logger?.debug(`server url cache miss`,{cwd:o});let u=(async()=>{let i=await e.resolveConfig(o),a=he(i,o),s=me(a),c=e.readLock,l=c?()=>c(s):void 0,u=await t({lockDir:s,contentDir:a,host:i.server.host,portOverride:void 0,envAutoStart:e.envAutoStart,configAutoStart:i.mcp.autoStart,logger:e.logger,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,spawn:e.spawn,readLock:l,isAlive:e.isAlive,sleep:e.sleep,readErrorLog:e.readErrorLog,openErrorLog:e.openErrorLog,closeFd:e.closeFd,launchPath:e.launchPath});return r.set(o,{url:u.serverUrl,expiresAt:Date.now()+n}),u.serverUrl})();i.set(o,u);try{return await u}finally{i.delete(o)}}}function tw(e){return new r(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=Be({startupCwd:r,startupConfig:n}),a=ZC(process.env.OK_MCP_SPAWN_TIMEOUT_MS),o,s;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(o=void 0,s=`invalid --port value '${t.port}' — disk-only mode`):e>0?(o=`ws://${n.server.host}:${e}`,s=`using --port override, connecting to ${o}`):(o=void 0,s=`--port=0 — disk-only mode`)}else o=ew({startupCwd:r,resolveConfig:i,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:a}),s=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${s}\n`),await UC({projectDir:r,serverUrl:o,config:i,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function nw(e){return new r(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-CHvLSbhb.mjs`),r=e(),i=process.cwd(),a=he(r,i),o;try{o=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function rw(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function iw(e,t,n=process.cwd()){let r=e.op??`sync`,i=ge(me(he(t,n)));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})…\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Server responded with ${n.status}`)}rw(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly…\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)…\n`);let a=ye({baseDir:n});if(r===`sync`||r===`pull`){rw(e.json,{type:`step`,step:`pull`});let t=await a.pull();rw(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(rw(e.json,{type:`step`,step:`push`}),await a.push(),rw(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
|
|
1402
|
-
`)),
|
|
1403
|
-
`),plan:n,exitCode:1}}return{status:`applied`,message:`${
|
|
1404
|
-
`)}async function uw(e,t){let n=rr({input:t??process.stdin,output:process.stdout});try{let t=(await n.question(e)).trim().toLowerCase();return t===``||t===`y`||t===`yes`}finally{n.close()}}function dw(){return new r(`seed`).description(`Scaffold the Karpathy three-layer knowledge-base structure (external-sources/, research/, articles/) + log.md + config.yml folders: entries. Use --root to place them inside a subfolder instead of the project root.`).argument(`[path]`,`Project directory (defaults to cwd)`).option(`-r, --root <path>`,`Subfolder (relative to the project dir) to scaffold into — created if missing. Defaults to the project root when omitted in non-interactive runs; prompts on a TTY.`).option(`-y, --yes`,`Skip confirmation prompt`).option(`--dry-run`,`Print the plan and exit without writing`).action(async(e,t)=>{let n=await cw({cwd:e??process.cwd(),root:t.root,yes:t.yes,dryRun:t.dryRun});process.stdout.write(`${n.message}\n`),n.exitCode!==0&&(process.exitCode=n.exitCode)})}function fw(e,t){return{server:pw(`server`,e),ui:pw(`ui`,t)}}function pw(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:return{name:e,state:`dead-pid`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function mw(e){return`${hw(e.server)}\n${hw(e.ui)}`}function hw(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`ok clean\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function gw(e){let t=e.inspect??(t=>bo(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=fw(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(mw(r)),r}function _w(e){return new r(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{gw({lockDir:me(he(e(),process.cwd())),json:t.json===!0})})}function vw(e,t){let n=[];return e.status===`alive`&&n.push({name:`server`,pid:e.lock.pid,port:e.lock.port}),t.status===`alive`&&n.push({name:`ui`,pid:t.lock.pid,port:t.lock.port}),{targets:n}}function yw(e){let t=e.inspect??(t=>bo(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=vw(t(`server`),t(`ui`));if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function bw(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{yw({lockDir:me(he(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const xw=1e4,Sw=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Cw(e){let t=e.upstreamTimeoutMs??xw,n=er((n,r)=>{Tw(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,r)=>{let i=e=>r(e);n.once(`error`,i),n.listen(e.listenPort,e.host,()=>{n.off(`error`,i),t()})});let r=n.address();return{httpServer:n,port:typeof r==`object`&&r?r.port:e.listenPort,close:()=>new Promise(e=>{n.close(()=>e())})}}function ww(e,t,n){Tw(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??xw)}function Tw(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Sw)delete a[e];e.setTimeout(3e4,()=>{if(t.headersSent)try{t.end()}catch{}else try{t.writeHead(408,{"Content-Type":`text/plain`}),t.end(`Request Timeout`)}catch{}try{e.socket?.destroy()}catch{}});let o=tr({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Sw)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)t.writeHead(504,{"Content-Type":`text/plain`}),t.end(`Gateway Timeout`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)t.writeHead(502,{"Content-Type":`text/plain`}),t.end(`Bad Gateway`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function Ew(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function Dw(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,readServerLock:a,releaseUiLock:o,updateUiLockPort:s}=await import(`./dist-Ct-gJ7iD.mjs`),{default:c}=await import(`./build-D4l8tfO0.mjs`),{resolveContentDir:l,resolveLockDir:u}=await import(`./paths-fx16Ahvg.mjs`),d=l(e.config,e.cwd),f=u(d);i(f,{port:0,worktreeRoot:e.cwd});let p=import.meta.dirname??new URL(`.`,import.meta.url).pathname,m=[r(p,`public`),r(p,`../../app/dist`),r(p,`../../../app/dist`)].find(e=>t(e)),h=m?c(m,{single:!0,gzip:!0,immutable:!0}):null,g=t(d)?c(d,{dotfiles:!1,dev:!0}):null,_=e.port,v=null,y=(e,t)=>{let n=e.url?.split(`?`)[0];if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){v?.();let n=a(f),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:_});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(i);return}if(n?.startsWith(`/api/`)){v?.();let r=a(f);if(!r||r.port<=0){t.writeHead(503,{"Content-Type":`application/json`,"Cache-Control":`no-store`}),t.end(JSON.stringify({error:"Collab server not running. Start `ok start` or run `ok status`.",path:n}));return}ww(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(decodeURIComponent(n?.replace(/^\//,``)??``)&&g){t.setHeader(`X-Content-Type-Options`,`nosniff`),g(e,t,()=>{h?h(e,t):Ow(t)});return}if(h){h(e,t);return}Ow(t)},x=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],S=[],C=e.port;try{for(let e of x){let t=n(y);S.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(C,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(C=e.port),n()})})}}catch(e){await Promise.all(S.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{o(f)}catch{}throw e}let w=C;_=w,s(f,w);let ee=e.scheduler??b,T=e.safetyNetMs??432e5,E=null,te=!1,ne=!1,re=()=>{te||(te=!0,E!==null&&(ee.clearTimeout(E),E=null))},ie=()=>{if(re(),!ne){ne=!0;try{o(f)}catch{}}},ae=()=>{te||T<=0||(E!==null&&(ee.clearTimeout(E),E=null),E=ee.setTimeout(()=>{E=null,console.warn(`[ui] safety-net (${T}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of S)try{e.close()}catch{}ie()},T))},oe=()=>{te||T<=0||ae()};return v=oe,ae(),{httpServers:S,port:w,release:ie,detachSafetyNet:re,nudgeSafetyNet:oe}}function Ow(e){e.writeHead(404),e.end(`Not found`)}function kw(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return t}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return e}return 0}async function Aw(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-Ct-gJ7iD.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await Cw({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function jw(e){return new r(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or 0 / kernel-allocated)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud (D-033). Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-BnZ-i-vb.mjs`),{UiLockCollisionError:r}=await import(`./dist-Ct-gJ7iD.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-fx16Ahvg.mjs`),o=e(),s=t.host,c;try{c=kw(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await Dw({config:o,cwd:process.cwd(),port:c,host:s}),t=s===void 0||s===`::`||s===`0.0.0.0`?`localhost`:s;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})...`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};Ew(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=a(i(o,process.cwd())),l=s??`localhost`,u;try{u=await Aw({requestedPort:c,host:l,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}u.mode===`already-running`&&(console.log(`UI already running at http://${l}:${u.port}`),process.exit(0)),console.log(`UI running at http://${l}:${u.upstreamPort}; acting as HTTP proxy on port ${u.handle.port}`);let d=!1,f=e=>{d||(d=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),u.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>f(`SIGINT`)),process.once(`SIGTERM`,()=>f(`SIGTERM`))}})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Mw=new r;let Nw;Mw.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(c).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts(),n=t.cwd;n!==void 0&&process.chdir(n);let{config:r}=ze(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.port!==void 0&&(r.server.port=Number(i.port)),i.host!==void 0&&(r.server.host=i.host),process.env.PORT&&(r.server.port=Number(process.env.PORT)),process.env.HOST&&(r.server.host=process.env.HOST),Nw=r});const Pw=hn(()=>Nw);Mw.addCommand(Pw,{isDefault:!0});const Fw=tw(()=>Nw);Mw.addCommand(Fw),Mw.addCommand(Ae()),Mw.addCommand(dw()),Mw.addCommand(Io());const Iw=nw(()=>Nw);Mw.addCommand(Iw);const Lw=jw(()=>Nw);Mw.addCommand(Lw),Mw.addCommand(bw(()=>Nw)),Mw.addCommand(Co(()=>Nw)),Mw.addCommand(_w(()=>Nw)),Mw.addCommand(yo(()=>Nw)),Mw.addCommand(Mo(()=>Nw)),Mw.addCommand(aw(()=>Nw)),Mw.addCommand(sw(()=>Nw)),Mw.addCommand(ow(()=>Nw)),await Mw.parseAsync();export{};
|
|
1404
|
+
`}async function UC(e,t){try{let t=e.replace(`ws://`,`http://`).replace(`wss://`,`https://`);return(await fetch(`${t}/api/document`,{signal:AbortSignal.timeout(2e3)})).ok}catch(n){return t.warn(`Hocuspocus probe failed`,{serverUrl:e,error:n instanceof Error?n.message:String(n)}),!1}}async function WC(e){let{projectDir:t,serverUrl:n,config:r,startupConfig:i,bypassProjectSelection:a=!1}=e;if(VC=dm(),VC.info(`MCP server starting`,{startupCwd:t,bypassProjectSelection:a,serverUrlType:typeof n==`string`?`explicit`:`lazy`}),typeof n==`string`){let e=await UC(n,VC);VC.info(`Hocuspocus detection complete`,{serverUrl:n,available:e})}else VC.info(`server discovery is lazy per effective cwd`);let o=new Yp({name:l,version:c},{instructions:HC(i,{dynamicConfig:typeof r==`function`&&!a})}),s=zC({startupCwd:t,bypassProjectSelection:a,listRoots:()=>o.server.listRoots(),logger:VC}),u=BC({startupCwd:t,resolveCwd:s.resolveCwd,bypassProjectSelection:a}),d=u.resolveCwdForTools;o.server.setNotificationHandler(od,async()=>{s.invalidateRoots()});let f=async e=>{if(typeof n==`string`)return n.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await d();return(typeof n==`function`?await n(t):n)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},p=Yn(),m=process.env.AGENT_LABEL||void 0,h={current:{connectionId:p,label:m,displayName:m??`Agent`,colorSeed:m??p}};o.server.oninitialized=()=>{let e=o.server.getClientVersion();h.current={connectionId:p,clientInfo:e?{name:e.name,version:e.version}:void 0,label:m,displayName:m??e?.name??`Agent`,colorSeed:m??e?.name??p},VC?.info(`agent identity established`,{displayName:h.current.displayName,connectionId:p.slice(0,8),clientName:e?.name})},IC(o,{serverUrl:f,resolveCwd:d,config:r,identityRef:h,logger:VC});let g=new cm;await o.connect(g),VC.info(`MCP server running on stdio`);let{startKeepalive:_}=await import(`./keepalive-CZzB5k1h.mjs`),v=_({resolveWsUrl:async()=>{let e=await u.getKeepaliveCwd();if(!e)return;let t=await f(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},connectionId:`agent-${p}`,logger:VC.child(`keepalive`)}),y=e=>{VC?.info(`MCP server shutting down`,{signal:e});try{v.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>y(`SIGINT`)),process.on(`SIGTERM`,()=>y(`SIGTERM`))}const GC=[`/_npx/`,`/.npm/_npx/`,`/_bunx/`,`/.bun/install/cache/`,`/pnpm/dlx/`],KC=new Set([`/usr/local/bin/ok`,`/usr/local/bin/open-knowledge`,`/opt/homebrew/bin/ok`,`/opt/homebrew/bin/open-knowledge`]);function qC(e){if(!e||e.length===0)return`unknown`;for(let t of GC)if(e.includes(t))return`npx-cache`;return KC.has(e)||e.startsWith(`/Applications/`)||e.includes(`.app/Contents/`)?`stable-shim`:e.startsWith(`/`)?`absolute-pin`:`unknown`}function JC(e,t){switch(e){case`npx-cache`:return"This MCP was launched via a package-manager cache (npx / bunx / pnpm dlx) and just resolved a different package version than the running server. Stop `ok start` so the next launch matches, or run `ok init --pin` for a stable launch path.";case`stable-shim`:return"The CLI shim was likely upgraded while a project server is still running (a desktop auto-update or `npm i -g` / `brew upgrade` will do this). Close and reopen the project window, or stop `ok start`, so the next launch matches.";case`absolute-pin`:return`This MCP is launched from a pinned path${t?` (${t})`:``} that no longer matches the running server. Re-run \`ok init --pin\` from your current install to refresh, or stop \`ok start\` so the next launch matches.`;default:return"Stop `ok start` and retry, or align CLI versions across your installs."}}function YC(e){return e?/\bENOENT\b/i.test(e):!1}function XC(e){switch(qC(e)){case`absolute-pin`:return"This failure usually means the CLI entry script no longer exists at the pinned path (common after changing how you installed Open Knowledge or removing an old global package). Re-run `ok init --pin` from your current install and update your editor MCP config, or use an unpinned launcher such as `npx @inkeep/open-knowledge mcp`.";case`stable-shim`:return"The expected `ok` shim is missing on disk. Reinstall or repair your Open Knowledge CLI. If you switched install sources, run `ok init --pin` again so your editor matches the binary you have.";case`npx-cache`:return"The package-manager cache copy used for this launch may have been removed. Retry once, or run `ok init --pin` so your editor uses a durable absolute path.";default:return"Often means the configured launcher path does not exist (stale pin, moved install, or missing runtime). Re-run `ok init --pin` from your current install or fix the MCP command in your editor settings."}}function ZC(e,t,n){let r=`spawn failed: ${e}${t?` stderr:\n${t}`:``}`;return YC(e)&&(r+=`\n\n${XC(n)}`),r}function QC(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function $C(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t))return{action:`disk-only`,message:`invalid --port value '${e.portOverride}' — disk-only mode`};if(t>0){let n=`ws://${e.host}:${t}`;return{action:`connect`,url:n,message:`using --port override, connecting to ${n}`}}return{action:`disk-only`,message:`--port=0 — disk-only mode`}}let t=e.readLock();if(t&&t.port>0&&e.isAlive(t.pid)){let n=e.expectedProtocolVersion??1,r=t.protocolVersion;if(r===n){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}let i=r===void 0?`unknown (pre-version-field lock)`:`v${r}`,a=t.runtimeVersion?` runtime ${t.runtimeVersion}`:``,o=e.launchPath??process.argv[1],s=qC(o),c=JC(s,o);return{action:`incompatible`,message:`Open Knowledge server at port ${t.port} (pid ${t.pid}${a}) speaks protocol ${i}; this MCP needs protocol v${n}.\n`+c,expectedProtocolVersion:n,actualProtocolVersion:r,lock:t,launchShape:s,launchPath:o}}return e.envAutoStart===`0`?{action:`disk-only`,message:`auto-spawn disabled via OK_MCP_AUTOSTART=0 — disk-only mode`}:e.configAutoStart?t?{action:`spawn`,message:`existing lock is not usable (port=${t.port}, pid=${t.pid}) — spawning ok start`}:{action:`spawn`,message:`no running instance — spawning ok start`}:{action:`disk-only`,message:`auto-spawn disabled via config.mcp.autoStart=false — disk-only mode`}}async function ew(e){let t=e.readLock??(()=>ye(e.lockDir)),n=e.isAlive??be,r=e.sleep??(e=>Xn(e)),i=e.spawn??bn,a=e.readErrorLog??(e=>An(e)?Nn(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>Mn(e,`w`)),s=e.closeFd??kn,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=e.launchPath??process.argv[1],d=$C({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n,launchPath:e.launchPath});if(e.logger?.info(`auto-start decision`,{action:d.action,message:d.message,contentDir:e.contentDir}),d.action===`connect`)return{serverUrl:d.url,message:d.message};if(d.action===`disk-only`)return{serverUrl:void 0,message:d.message};if(d.action===`incompatible`)throw e.logger?.error(`protocol mismatch — refusing to connect`,void 0,{expectedProtocolVersion:d.expectedProtocolVersion,actualProtocolVersion:d.actualProtocolVersion,lockPid:d.lock.pid,lockPort:d.lock.port,lockRuntimeVersion:d.lock.runtimeVersion,launchShape:d.launchShape,launchPath:d.launchPath}),Error(d.message);An(e.lockDir)||jn(e.lockDir,{recursive:!0});let f=Tn(e.lockDir,`last-spawn-error.log`),p=o(f),m,h,g=vn();e.logger?.info(`spawning server`,{command:g.command,cwd:e.contentDir,timeoutMs:c});try{try{m=i(g.command,[...g.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,p],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,OK_PARENT_PID:String(process.pid)}}),m.on(`error`,e=>{h=e instanceof Error?e.message:String(e)}),m.unref()}catch(e){h=e instanceof Error?e.message:String(e)}}finally{try{s(p)}catch{}}let _=Date.now()+c;for(;Date.now()<_;){if(h){let t=a(f);throw e.logger?.error(`spawn failed`,void 0,{error:h,stderr:t,launchPath:u,stalePinHint:YC(h)}),Error(ZC(h,t,u))}await r(l);let i=t();if(i&&i.port>0&&n(i.pid)){let t=`ws://localhost:${i.port}`;return e.logger?.info(`server ready after spawn`,{url:t,pid:i.pid}),{serverUrl:t,message:`spawned ok start; connected at ${t} (pid ${i.pid})`}}}if(h){let t=a(f);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:h,stderr:t,launchPath:u,stalePinHint:YC(h)}),Error(ZC(h,t,u))}let v=a(f),y=(c/1e3).toFixed(c%1e3==0?0:2),b=m?.pid,x=``;throw typeof b==`number`&&(x=n(b)?` child pid=${b} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${b} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:b,childAlive:typeof b==`number`?n(b):void 0,stderr:v||void 0}),Error(`server did not start within ${y}s.${x}${v?` stderr:\n${v}`:``}`)}function tw(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)return async()=>void 0;let n=`ws://${e.host}:${t}`;return async()=>n}let t=e.ensureServerRunningFn??ew,n=e.cacheMs??1e3,r=new Map,i=new Map;return async a=>{let o=await Ve(a??e.startupCwd),s=Date.now(),c=r.get(o);if(c&&c.expiresAt>s)return e.logger?.debug(`server url cache hit`,{cwd:o,url:c.url}),c.url;let l=i.get(o);if(l)return e.logger?.debug(`server url resolution pending`,{cwd:o}),await l;e.logger?.debug(`server url cache miss`,{cwd:o});let u=(async()=>{let i=await e.resolveConfig(o),a=ve(i,o),s=_e(a),c=e.readLock,l=c?()=>c(s):void 0,u=await t({lockDir:s,contentDir:a,host:i.server.host,portOverride:void 0,envAutoStart:e.envAutoStart,configAutoStart:i.mcp.autoStart,logger:e.logger,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,spawn:e.spawn,readLock:l,isAlive:e.isAlive,sleep:e.sleep,readErrorLog:e.readErrorLog,openErrorLog:e.openErrorLog,closeFd:e.closeFd,launchPath:e.launchPath});return r.set(o,{url:u.serverUrl,expiresAt:Date.now()+n}),u.serverUrl})();i.set(o,u);try{return await u}finally{i.delete(o)}}}function nw(e){return new r(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=Ue({startupCwd:r,startupConfig:n}),a=QC(process.env.OK_MCP_SPAWN_TIMEOUT_MS),o,s;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(o=void 0,s=`invalid --port value '${t.port}' — disk-only mode`):e>0?(o=`ws://${n.server.host}:${e}`,s=`using --port override, connecting to ${o}`):(o=void 0,s=`--port=0 — disk-only mode`)}else o=tw({startupCwd:r,resolveConfig:i,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:a}),s=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${s}\n`),await WC({projectDir:r,serverUrl:o,config:i,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function rw(e){return new r(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-DT0ltjSs.mjs`),r=e(),i=process.cwd(),a=ve(r,i),o;try{o=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function iw(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function aw(e,t,n=process.cwd()){let r=e.op??`sync`,i=ye(_e(ve(t,n)));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})…\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Server responded with ${n.status}`)}iw(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly…\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)…\n`);let a=Se({baseDir:n});if(r===`sync`||r===`pull`){iw(e.json,{type:`step`,step:`pull`});let t=await a.pull();iw(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(iw(e.json,{type:`step`,step:`push`}),await a.push(),iw(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
|
|
1405
|
+
`)),iw(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function ow(e){return new r(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await aw({json:t.json,op:`sync`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ sync failed: ${n}\n`),process.exit(1)}})}function sw(e){return new r(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await aw({json:t.json,op:`pull`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ pull failed: ${n}\n`),process.exit(1)}})}function cw(e){return new r(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await aw({json:t.json,op:`push`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ push failed: ${n}\n`),process.exit(1)}})}async function lw(e={}){let t=Dn(e.cwd??process.cwd()),n;try{n=await ke({projectDir:t,rootDir:e.root})}catch(e){return e instanceof Te?{status:`prerequisite-missing`,message:`${Le(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${Le(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(n.created.length===0&&n.configEdits.length===0)return{status:`no-op`,message:`${Ie(`Your knowledge base is already seeded.`)}\n${Fe(`Nothing to do.`)}`,plan:n,exitCode:0};if(e.dryRun)return{status:`dry-run`,message:`${ze(`Plan (dry-run — no changes made):`)}\n\n${uw(n,t)}`,plan:n,exitCode:0};if(!e.yes&&!await dw(`${ze(`Plan:`)}\n\n${uw(n,t)}\n\n${ze(`Apply?`)} ${Fe(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:Fe(`Cancelled.`),plan:n,exitCode:0};let r=await we(n,{projectDir:t});if(r.errors.length>0){let e=r.errors.map(e=>` ${Le(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${Re(`Applied`)} ${r.applied} entries, ${Re(String(r.errors.length))} error(s):`,...e].join(`
|
|
1406
|
+
`),plan:n,exitCode:1}}return{status:`applied`,message:`${Ie(`✓ Seeded knowledge base`)} ${Fe(`(${r.applied} entries, ${r.durationMs}ms)`)}`,plan:n,exitCode:0}}function uw(e,t){let n=[],r=e.created.filter(e=>e.kind===`folder`),i=e.created.filter(e=>e.kind===`file`);if(r.length>0){n.push(ze(`Folders to create:`));for(let e of r)n.push(` ${Ie(`+`)} ${Pe(En(t,Dn(t,e.path))||e.path)}${Fe(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(ze(`Files to create:`));for(let e of i)n.push(` ${Ie(`+`)} ${Pe(En(t,Dn(t,e.path))||e.path)}`)}if(e.configEdits.length>0){n.length>0&&n.push(``),n.push(ze(`config.yml folders: entries to add:`));for(let t of e.configEdits)n.push(` ${Ie(`+`)} ${Pe(t.folderMatch)} ${Fe(`—`)} ${t.entry.frontmatter.title??``}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(Fe(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${Fe(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(Re(`Warnings:`));for(let t of e.warnings)n.push(` ${Re(`!`)} ${t}`)}return n.join(`
|
|
1407
|
+
`)}async function dw(e,t){let n=ir({input:t??process.stdin,output:process.stdout});try{let t=(await n.question(e)).trim().toLowerCase();return t===``||t===`y`||t===`yes`}finally{n.close()}}function fw(){return new r(`seed`).description(`Scaffold the Karpathy three-layer knowledge-base structure (external-sources/, research/, articles/) + log.md + config.yml folders: entries. Use --root to place them inside a subfolder instead of the project root.`).argument(`[path]`,`Project directory (defaults to cwd)`).option(`-r, --root <path>`,`Subfolder (relative to the project dir) to scaffold into — created if missing. Defaults to the project root when omitted in non-interactive runs; prompts on a TTY.`).option(`-y, --yes`,`Skip confirmation prompt`).option(`--dry-run`,`Print the plan and exit without writing`).action(async(e,t)=>{let n=await lw({cwd:e??process.cwd(),root:t.root,yes:t.yes,dryRun:t.dryRun});process.stdout.write(`${n.message}\n`),n.exitCode!==0&&(process.exitCode=n.exitCode)})}function pw(e,t){return{server:mw(`server`,e),ui:mw(`ui`,t)}}function mw(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:return{name:e,state:`dead-pid`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function hw(e){return`${gw(e.server)}\n${gw(e.ui)}`}function gw(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`ok clean\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function _w(e){let t=e.inspect??(t=>xo(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=pw(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(hw(r)),r}function vw(e){return new r(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{_w({lockDir:_e(ve(e(),process.cwd())),json:t.json===!0})})}function yw(e,t){let n=[];return e.status===`alive`&&n.push({name:`server`,pid:e.lock.pid,port:e.lock.port}),t.status===`alive`&&n.push({name:`ui`,pid:t.lock.pid,port:t.lock.port}),{targets:n}}function bw(e){let t=e.inspect??(t=>xo(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=yw(t(`server`),t(`ui`));if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function xw(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{bw({lockDir:_e(ve(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const Sw=1e4,Cw=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function ww(e){let t=e.upstreamTimeoutMs??Sw,n=tr((n,r)=>{Ew(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,r)=>{let i=e=>r(e);n.once(`error`,i),n.listen(e.listenPort,e.host,()=>{n.off(`error`,i),t()})});let r=n.address();return{httpServer:n,port:typeof r==`object`&&r?r.port:e.listenPort,close:()=>new Promise(e=>{n.close(()=>e())})}}function Tw(e,t,n){Ew(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??Sw)}function Ew(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Cw)delete a[e];e.setTimeout(3e4,()=>{if(t.headersSent)try{t.end()}catch{}else try{t.writeHead(408,{"Content-Type":`text/plain`}),t.end(`Request Timeout`)}catch{}try{e.socket?.destroy()}catch{}});let o=nr({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Cw)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)t.writeHead(504,{"Content-Type":`text/plain`}),t.end(`Gateway Timeout`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)t.writeHead(502,{"Content-Type":`text/plain`}),t.end(`Bad Gateway`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function Dw(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function Ow(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,readServerLock:a,releaseUiLock:o,updateUiLockPort:s}=await import(`./dist-CNDKfHI8.mjs`),{default:c}=await import(`./build-D4l8tfO0.mjs`),{resolveContentDir:l,resolveLockDir:u}=await import(`./paths-CcD8Nh_5.mjs`),d=l(e.config,e.cwd),f=u(d);i(f,{port:0,worktreeRoot:e.cwd});let p=import.meta.dirname??new URL(`.`,import.meta.url).pathname,m=[r(p,`public`),r(p,`../../app/dist`),r(p,`../../../app/dist`)].find(e=>t(e)),h=m?c(m,{single:!0,gzip:!0,immutable:!0}):null,g=t(d)?c(d,{dotfiles:!1,dev:!0}):null,_=e.port,v=null,y=(e,t)=>{let n=e.url?.split(`?`)[0];if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){v?.();let n=a(f),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:_});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(i);return}if(n?.startsWith(`/api/`)){v?.();let r=a(f);if(!r||r.port<=0){t.writeHead(503,{"Content-Type":`application/json`,"Cache-Control":`no-store`}),t.end(JSON.stringify({error:"Collab server not running. Start `ok start` or run `ok status`.",path:n}));return}Tw(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(decodeURIComponent(n?.replace(/^\//,``)??``)&&g){t.setHeader(`X-Content-Type-Options`,`nosniff`),g(e,t,()=>{h?h(e,t):kw(t)});return}if(h){h(e,t);return}kw(t)},b=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],x=[],S=e.port;try{for(let e of b){let t=n(y);x.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(S,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(S=e.port),n()})})}}catch(e){await Promise.all(x.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{o(f)}catch{}throw e}let ee=S;_=ee,s(f,ee);let te=e.scheduler??he,ne=e.safetyNetMs??432e5,C=null,w=!1,re=!1,ie=()=>{w||(w=!0,C!==null&&(te.clearTimeout(C),C=null))},T=()=>{if(ie(),!re){re=!0;try{o(f)}catch{}}},ae=()=>{w||ne<=0||(C!==null&&(te.clearTimeout(C),C=null),C=te.setTimeout(()=>{C=null,console.warn(`[ui] safety-net (${ne}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of x)try{e.close()}catch{}T()},ne))},oe=()=>{w||ne<=0||ae()};return v=oe,ae(),{httpServers:x,port:ee,release:T,detachSafetyNet:ie,nudgeSafetyNet:oe}}function kw(e){e.writeHead(404),e.end(`Not found`)}function Aw(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return t}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return e}return 0}async function jw(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-CNDKfHI8.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await ww({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Mw(e){return new r(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or 0 / kernel-allocated)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud (D-033). Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-BnZ-i-vb.mjs`),{UiLockCollisionError:r}=await import(`./dist-CNDKfHI8.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-CcD8Nh_5.mjs`),o=e(),s=t.host,c;try{c=Aw(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await Ow({config:o,cwd:process.cwd(),port:c,host:s}),t=s===void 0||s===`::`||s===`0.0.0.0`?`localhost`:s;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})...`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};Dw(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=a(i(o,process.cwd())),l=s??`localhost`,u;try{u=await jw({requestedPort:c,host:l,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}u.mode===`already-running`&&(console.log(`UI already running at http://${l}:${u.port}`),process.exit(0)),console.log(`UI running at http://${l}:${u.upstreamPort}; acting as HTTP proxy on port ${u.handle.port}`);let d=!1,f=e=>{d||(d=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),u.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>f(`SIGINT`)),process.once(`SIGTERM`,()=>f(`SIGTERM`))}})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Nw=new r;let Pw;Nw.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(c).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts(),n=t.cwd;n!==void 0&&process.chdir(n);let{config:r}=He(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.port!==void 0&&(r.server.port=Number(i.port)),i.host!==void 0&&(r.server.host=i.host),process.env.PORT&&(r.server.port=Number(process.env.PORT)),process.env.HOST&&(r.server.host=process.env.HOST),Pw=r});const Fw=_n(()=>Pw);Nw.addCommand(Fw,{isDefault:!0});const Iw=nw(()=>Pw);Nw.addCommand(Iw),Nw.addCommand(Ne()),Nw.addCommand(fw()),Nw.addCommand(Ro());const Lw=rw(()=>Pw);Nw.addCommand(Lw);const Rw=Mw(()=>Pw);Nw.addCommand(Rw),Nw.addCommand(xw(()=>Pw)),Nw.addCommand(wo(()=>Pw)),Nw.addCommand(vw(()=>Pw)),Nw.addCommand(bo(()=>Pw)),Nw.addCommand(Po(()=>Pw)),Nw.addCommand(ow(()=>Pw)),Nw.addCommand(cw(()=>Pw)),Nw.addCommand(sw(()=>Pw)),await Nw.parseAsync();export{};
|
|
1405
1408
|
//# sourceMappingURL=cli.mjs.map
|