allwright 1.1.0 → 1.2.1
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/bin/allwright.js +112 -102
- package/package.json +1 -1
package/bin/allwright.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`).replace(/^/gm," ".repeat(i))}let l=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(l=l.concat([t.wrap(d,s,0),""]));let p=t.visibleArguments(e).map(x=>a(t.argumentTerm(x),t.argumentDescription(x)));p.length>0&&(l=l.concat(["Arguments:",
|
|
4
|
-
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=t-n;if(a<s)return e;let
|
|
2
|
+
"use strict";var gd=Object.create;var si=Object.defineProperty;var yd=Object.getOwnPropertyDescriptor;var _d=Object.getOwnPropertyNames;var vd=Object.getPrototypeOf,bd=Object.prototype.hasOwnProperty;var ii=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Y=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Yn=(r,e)=>{for(var t in e)si(r,t,{get:e[t],enumerable:!0})},wd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _d(e))!bd.call(r,s)&&s!==t&&si(r,s,{get:()=>e[s],enumerable:!(n=yd(e,s))||n.enumerable});return r};var $=(r,e,t)=>(t=r!=null?gd(vd(r)):{},wd(e||!r||!r.__esModule?si(t,"default",{value:r,enumerable:!0}):t,r));var vn=Y(ai=>{var Xn=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},oi=class extends Xn{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ai.CommanderError=Xn;ai.InvalidArgumentError=oi});var Qn=Y(ci=>{var{InvalidArgumentError:kd}=vn(),ui=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new kd(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Sd(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}ci.Argument=ui;ci.humanReadableArgName=Sd});var di=Y(ia=>{var{humanReadableArgName:Td}=Qn(),li=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,i)=>s.name().localeCompare(i.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>Td(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,s)=>Math.max(n,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth||80,i=2,o=2;function a(x,w){if(w){let j=`${x.padEnd(n+o)}${w}`;return t.wrap(j,s-i,n+o)}return x}function c(x){return x.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(i))}let l=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(l=l.concat([t.wrap(d,s,0),""]));let p=t.visibleArguments(e).map(x=>a(t.argumentTerm(x),t.argumentDescription(x)));p.length>0&&(l=l.concat(["Arguments:",c(p),""]));let v=t.visibleOptions(e).map(x=>a(t.optionTerm(x),t.optionDescription(x)));if(v.length>0&&(l=l.concat(["Options:",c(v),""])),this.showGlobalOptions){let x=t.visibleGlobalOptions(e).map(w=>a(t.optionTerm(w),t.optionDescription(w)));x.length>0&&(l=l.concat(["Global Options:",c(x),""]))}let S=t.visibleCommands(e).map(x=>a(t.subcommandTerm(x),t.subcommandDescription(x)));return S.length>0&&(l=l.concat(["Commands:",c(S),""])),l.join(`
|
|
4
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=t-n;if(a<s)return e;let c=e.slice(0,n),l=e.slice(n).replace(`\r
|
|
5
5
|
`,`
|
|
6
6
|
`),d=" ".repeat(n),v="\\s\u200B",S=new RegExp(`
|
|
7
|
-
|.{1,${a-1}}([${v}]|$)|[^${v}]+?([${v}]|$)`,"g"),x=l.match(S)||[];return
|
|
7
|
+
|.{1,${a-1}}([${v}]|$)|[^${v}]+?([${v}]|$)`,"g"),x=l.match(S)||[];return c+x.map((w,j)=>w===`
|
|
8
8
|
`?"":(j>0?d:"")+w.trimEnd()).join(`
|
|
9
|
-
`)}};
|
|
9
|
+
`)}};ia.Help=li});var mi=Y(pi=>{var{InvalidArgumentError:xd}=vn(),hi=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Ed(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new xd(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Cd(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},fi=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function Cd(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ed(r){let e,t,n=r.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}pi.Option=hi;pi.DualOptions=fi});var aa=Y(oa=>{function Id(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let i=1;r[s-1]===e[n-1]?i=0:i=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+i),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function Ad(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Id(r,o),c=Math.max(r.length,o.length);(c-a)/c>i&&(a<s?(s=a,n=[o]):a===s&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
|
|
10
10
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
-
(Did you mean ${n[0]}?)`:""}
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
13
|
-
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new
|
|
14
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}oa.suggestSimilar=Ad});var ha=Y(da=>{var Rd=require("node:events").EventEmitter,gi=require("node:child_process"),Qe=require("node:path"),yi=require("node:fs"),se=require("node:process"),{Argument:$d,humanReadableArgName:Pd}=Qn(),{CommanderError:_i}=vn(),{Help:jd}=di(),{Option:ua,DualOptions:Od}=mi(),{suggestSimilar:ca}=aa(),vi=class r extends Rd{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>se.stdout.write(t),writeErr:t=>se.stderr.write(t),getOutHelpWidth:()=>se.stdout.isTTY?se.stdout.columns:void 0,getErrHelpWidth:()=>se.stderr.isTTY?se.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return s&&(c.description(s),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),s?this:c}createCommand(e){return new r(e)}createHelp(){return Object.assign(new jd,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new $d(e,t)}argument(e,t,n,s){let i=this.createArgument(e,t);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new _i(e,t,n)),se.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new ua(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let c=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,o):i!==null&&e.variadic&&(i=e._concatValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,a)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,n,s,i){if(typeof t=="object"&&t instanceof ua)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(c,l)=>{let d=a.exec(c);return d?d[0]:l},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){se.versions?.electron&&(t.from="electron");let s=se.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=se.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":se.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,p){let v=Qe.resolve(d,p);if(yi.existsSync(v))return v;if(s.includes(Qe.extname(p)))return;let S=s.find(x=>yi.existsSync(`${v}${x}`));if(S)return`${v}${S}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=yi.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=Qe.resolve(Qe.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let p=Qe.basename(this._scriptPath,Qe.extname(this._scriptPath));p!==this._name&&(d=i(a,`${p}-${e._name}`))}o=d||o}n=s.includes(Qe.extname(o));let c;se.platform!=="win32"?n?(t.unshift(o),t=la(se.execArgv).concat(t),c=gi.spawn(se.argv[0],t,{stdio:"inherit"})):c=gi.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=la(se.execArgv).concat(t),c=gi.spawn(se.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{se.on(p,()=>{c.killed===!1&&c.exitCode===null&&c.kill(p)})});let l=this._exitCallback;c.on("close",d=>{d=d??1,l?l(new _i(d,"commander.executeSubCommandAsync","(close)")):se.exit(d)}),c.on("error",d=>{if(d.code==="ENOENT"){let p=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",v=`'${o}' does not exist
|
|
15
15
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
16
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
-
- ${p}`;throw new Error(v)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)se.exit(1);else{let p=new
|
|
17
|
+
- ${p}`;throw new Error(v)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)se.exit(1);else{let p=new _i(1,"commander.executeSubCommandAsync","(error)");p.nestedError=d,l(p)}}),this.runningCommand=c}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,i)=>{let o=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,a)=>e(n,a,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),t[s]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,i=e.slice();function o(c){return c.length>1&&c[0]==="-"}let a=null;for(;i.length;){let c=i.shift();if(c==="--"){s===n&&s.push(c),s.push(...i);break}if(a&&!o(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,o(c)){let l=this._findOption(c);if(l){if(l.required){let d=i.shift();d===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,d)}else if(l.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${l.name()}`,d)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),d=this._findOption(c.slice(0,l));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,c.slice(l+1));continue}}if(o(c)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(c)){t.push(c),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){t.push(c),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(c),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(c),i.length>0&&s.push(...i);break}s.push(c)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
18
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
19
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in se.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,se.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>
|
|
20
|
+
`),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in se.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,se.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Od(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=o=>{let a=o.attributeName(),c=this.getOptionValue(a),l=this.options.find(p=>p.negate&&a===p.attributeName()),d=this.options.find(p=>!p.negate&&a===p.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:d||o},s=o=>{let a=n(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=ca(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=ca(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>Pd(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Qe.basename(e,Qe.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=se.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
22
|
Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ca(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}ua.Command=gi});var pa=Y(Ee=>{var{Argument:da}=Jn(),{Command:yi}=la(),{CommanderError:Ed,InvalidArgumentError:ha}=gn(),{Help:Id}=ci(),{Option:fa}=hi();Ee.program=new yi;Ee.createCommand=r=>new yi(r);Ee.createOption=(r,e)=>new fa(r,e);Ee.createArgument=(r,e)=>new da(r,e);Ee.Command=yi;Ee.Option=fa;Ee.Argument=da;Ee.Help=Id;Ee.CommanderError=Ed;Ee.InvalidArgumentError=ha;Ee.InvalidOptionArgumentError=ha});var kn=Y(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.getParsedType=te.ZodParsedType=te.objectUtil=te.util=void 0;var Ti;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Ti||(te.util=Ti={}));var Da;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Da||(te.objectUtil=Da={}));te.ZodParsedType=Ti.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var Vh=r=>{switch(typeof r){case"undefined":return te.ZodParsedType.undefined;case"string":return te.ZodParsedType.string;case"number":return Number.isNaN(r)?te.ZodParsedType.nan:te.ZodParsedType.number;case"boolean":return te.ZodParsedType.boolean;case"function":return te.ZodParsedType.function;case"bigint":return te.ZodParsedType.bigint;case"symbol":return te.ZodParsedType.symbol;case"object":return Array.isArray(r)?te.ZodParsedType.array:r===null?te.ZodParsedType.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?te.ZodParsedType.promise:typeof Map<"u"&&r instanceof Map?te.ZodParsedType.map:typeof Set<"u"&&r instanceof Set?te.ZodParsedType.set:typeof Date<"u"&&r instanceof Date?te.ZodParsedType.date:te.ZodParsedType.object;default:return te.ZodParsedType.unknown}};te.getParsedType=Vh});var us=Y(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.ZodError=Tt.quotelessJson=Tt.ZodIssueCode=void 0;var La=kn();Tt.ZodIssueCode=La.util.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 Hh=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");Tt.quotelessJson=Hh;var Sn=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};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(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,u=0;for(;u<o.path.length;){let l=o.path[u];u===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],u++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,La.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Tt.ZodError=Sn;Sn.create=r=>new Sn(r)});var Ci=Y(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});var fe=us(),Jt=kn(),Gh=(r,e)=>{let t;switch(r.code){case fe.ZodIssueCode.invalid_type:r.received===Jt.ZodParsedType.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case fe.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,Jt.util.jsonStringifyReplacer)}`;break;case fe.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${Jt.util.joinValues(r.keys,", ")}`;break;case fe.ZodIssueCode.invalid_union:t="Invalid input";break;case fe.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Jt.util.joinValues(r.options)}`;break;case fe.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${Jt.util.joinValues(r.options)}, received '${r.received}'`;break;case fe.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case fe.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case fe.ZodIssueCode.invalid_date:t="Invalid date";break;case fe.ZodIssueCode.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:Jt.util.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case fe.ZodIssueCode.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case fe.ZodIssueCode.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case fe.ZodIssueCode.custom:t="Invalid input";break;case fe.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case fe.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case fe.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,Jt.util.assertNever(r)}return{message:t}};xi.default=Gh});var ls=Y(xt=>{"use strict";var Wh=xt&&xt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(xt,"__esModule",{value:!0});xt.defaultErrorMap=void 0;xt.setErrorMap=Jh;xt.getErrorMap=Yh;var za=Wh(Ci());xt.defaultErrorMap=za.default;var Ua=za.default;function Jh(r){Ua=r}function Yh(){return Ua}});var Ii=Y(X=>{"use strict";var Xh=X&&X.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(X,"__esModule",{value:!0});X.isAsync=X.isValid=X.isDirty=X.isAborted=X.OK=X.DIRTY=X.INVALID=X.ParseStatus=X.EMPTY_PATH=X.makeIssue=void 0;X.addIssueToContext=tf;var Qh=ls(),qa=Xh(Ci()),ef=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",u=n.filter(l=>!!l).slice().reverse();for(let l of u)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};X.makeIssue=ef;X.EMPTY_PATH=[];function tf(r,e){let t=(0,Qh.getErrorMap)(),n=(0,X.makeIssue)({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===qa.default?void 0:qa.default].filter(s=>!!s)});r.common.issues.push(n)}var Ei=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return X.INVALID;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return X.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}};X.ParseStatus=Ei;X.INVALID=Object.freeze({status:"aborted"});var rf=r=>({status:"dirty",value:r});X.DIRTY=rf;var nf=r=>({status:"valid",value:r});X.OK=nf;var sf=r=>r.status==="aborted";X.isAborted=sf;var of=r=>r.status==="dirty";X.isDirty=of;var af=r=>r.status==="valid";X.isValid=af;var cf=r=>typeof Promise<"u"&&r instanceof Promise;X.isAsync=cf});var Fa=Y(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0})});var Ka=Y(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.errorUtil=void 0;var Za;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(Za||(ds.errorUtil=Za={}))});var nc=Y(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.discriminatedUnion=y.date=y.boolean=y.bigint=y.array=y.any=y.coerce=y.ZodFirstPartyTypeKind=y.late=y.ZodSchema=y.Schema=y.ZodReadonly=y.ZodPipeline=y.ZodBranded=y.BRAND=y.ZodNaN=y.ZodCatch=y.ZodDefault=y.ZodNullable=y.ZodOptional=y.ZodTransformer=y.ZodEffects=y.ZodPromise=y.ZodNativeEnum=y.ZodEnum=y.ZodLiteral=y.ZodLazy=y.ZodFunction=y.ZodSet=y.ZodMap=y.ZodRecord=y.ZodTuple=y.ZodIntersection=y.ZodDiscriminatedUnion=y.ZodUnion=y.ZodObject=y.ZodArray=y.ZodVoid=y.ZodNever=y.ZodUnknown=y.ZodAny=y.ZodNull=y.ZodUndefined=y.ZodSymbol=y.ZodDate=y.ZodBoolean=y.ZodBigInt=y.ZodNumber=y.ZodString=y.ZodType=void 0;y.NEVER=y.void=y.unknown=y.union=y.undefined=y.tuple=y.transformer=y.symbol=y.string=y.strictObject=y.set=y.record=y.promise=y.preprocess=y.pipeline=y.ostring=y.optional=y.onumber=y.oboolean=y.object=y.number=y.nullable=y.null=y.never=y.nativeEnum=y.nan=y.map=y.literal=y.lazy=y.intersection=y.instanceof=y.function=y.enum=y.effect=void 0;y.datetimeRegex=Ja;y.custom=Xa;var C=us(),hs=ls(),O=Ka(),_=Ii(),E=kn(),Pe=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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}},Va=(r,e)=>{if((0,_.isValid)(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new C.ZodError(r.common.issues);return this._error=t,this._error}}};function B(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:u}=r;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??t??a.defaultError}},description:s}}var F=class{get description(){return this._def.description}_getType(e){return(0,E.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,E.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,E.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,_.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let 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:(0,E.getParsedType)(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Va(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,E.getParsedType)(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return(0,_.isValid)(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>(0,_.isValid)(n)?{value:n.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:(0,E.getParsedType)(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await((0,_.isAsync)(s)?s:Promise.resolve(s));return Va(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:C.ZodIssueCode.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new ke({schema:this,typeName:L.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return $e.create(this,this._def)}nullable(){return He.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ct.create(this)}promise(){return It.create(this,this._def)}or(e){return nr.create([this,e],this._def)}and(e){return sr.create(this,e,this._def)}transform(e){return new ke({...B(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ur({...B(this._def),innerType:this,defaultValue:t,typeName:L.ZodDefault})}brand(){return new Tn({typeName:L.ZodBranded,type:this,...B(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new lr({...B(this._def),innerType:this,catchValue:t,typeName:L.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return xn.create(this,e)}readonly(){return dr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};y.ZodType=F;y.Schema=F;y.ZodSchema=F;var uf=/^c[^\s-]{8,}$/i,lf=/^[0-9a-z]+$/,df=/^[0-9A-HJKMNP-TV-Z]{26}$/i,hf=/^[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,ff=/^[a-z0-9_-]{21}$/i,pf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,mf=/^[-+]?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)?)??$/,gf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,yf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ai,_f=/^(?:(?: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])$/,vf=/^(?:(?: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])$/,bf=/^(([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]))$/,wf=/^(([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])$/,kf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Sf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ga="((\\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])))",Tf=new RegExp(`^${Ga}$`);function Wa(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function xf(r){return new RegExp(`^${Wa(r)}$`)}function Ja(r){let e=`${Ga}T${Wa(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Cf(r,e){return!!((e==="v4"||!e)&&_f.test(r)||(e==="v6"||!e)&&bf.test(r))}function Ef(r,e){if(!pf.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function If(r,e){return!!((e==="v4"||!e)&&vf.test(r)||(e==="v6"||!e)&&wf.test(r))}var Ct=class r extends F{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==E.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.string,received:i.parsedType}),_.INVALID}let n=new _.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")gf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"email",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Ai||(Ai=new RegExp(yf,"u")),Ai.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"emoji",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")hf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"uuid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")ff.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"nanoid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")uf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cuid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")lf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cuid2",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")df.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"ulid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"url",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"regex",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Ja(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Tf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?xf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?mf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"duration",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Cf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"ip",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Ef(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"jwt",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?If(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cidr",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?kf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"base64",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Sf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"base64url",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):E.util.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:C.ZodIssueCode.invalid_string,...O.errorUtil.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...O.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...O.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...O.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...O.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...O.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...O.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...O.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...O.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...O.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,O.errorUtil.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodString=Ct;Ct.create=r=>new Ct({checks:[],typeName:L.ZodString,coerce:r?.coerce??!1,...B(r)});function Af(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Yt=class r extends F{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)!==E.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.number,received:i.parsedType}),_.INVALID}let n,s=new _.ParseStatus;for(let i of this._def.checks)i.kind==="int"?E.util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Af(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_finite,message:i.message}),s.dirty()):E.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:O.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.errorUtil.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"&&E.util.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;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)}};y.ZodNumber=Yt;Yt.create=r=>new Yt({checks:[],typeName:L.ZodNumber,coerce:r?.coerce||!1,...B(r)});var Xt=class r extends F{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)!==E.ZodParsedType.bigint)return this._getInvalidInput(e);let n,s=new _.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):E.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.bigint,received:t.parsedType}),_.INVALID}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.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}};y.ZodBigInt=Xt;Xt.create=r=>new Xt({checks:[],typeName:L.ZodBigInt,coerce:r?.coerce??!1,...B(r)});var Qt=class extends F{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==E.ZodParsedType.boolean){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.boolean,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodBoolean=Qt;Qt.create=r=>new Qt({typeName:L.ZodBoolean,coerce:r?.coerce||!1,...B(r)});var er=class r extends F{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==E.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.date,received:i.parsedType}),_.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_date}),_.INVALID}let n=new _.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):E.util.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:O.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:O.errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};y.ZodDate=er;er.create=r=>new er({checks:[],coerce:r?.coerce||!1,typeName:L.ZodDate,...B(r)});var qr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.symbol){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.symbol,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodSymbol=qr;qr.create=r=>new qr({typeName:L.ZodSymbol,...B(r)});var tr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.undefined,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodUndefined=tr;tr.create=r=>new tr({typeName:L.ZodUndefined,...B(r)});var rr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.null){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.null,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodNull=rr;rr.create=r=>new rr({typeName:L.ZodNull,...B(r)});var Et=class extends F{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,_.OK)(e.data)}};y.ZodAny=Et;Et.create=r=>new Et({typeName:L.ZodAny,...B(r)});var at=class extends F{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,_.OK)(e.data)}};y.ZodUnknown=at;at.create=r=>new at({typeName:L.ZodUnknown,...B(r)});var Le=class extends F{_parse(e){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.never,received:t.parsedType}),_.INVALID}};y.ZodNever=Le;Le.create=r=>new Le({typeName:L.ZodNever,...B(r)});var Br=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.void,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodVoid=Br;Br.create=r=>new Br({typeName:L.ZodVoid,...B(r)});var ct=class r extends F{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==E.ZodParsedType.array)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.array,received:t.parsedType}),_.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&((0,_.addIssueToContext)(t,{code:o?C.ZodIssueCode.too_big:C.ZodIssueCode.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Pe(t,o,t.path,a)))).then(o=>_.ParseStatus.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Pe(t,o,t.path,a)));return _.ParseStatus.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:O.errorUtil.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:O.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};y.ZodArray=ct;ct.create=(r,e)=>new ct({type:r,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...B(e)});function Ur(r){if(r instanceof _e){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=$e.create(Ur(n))}return new _e({...r._def,shape:()=>e})}else return r instanceof ct?new ct({...r._def,type:Ur(r.element)}):r instanceof $e?$e.create(Ur(r.unwrap())):r instanceof He?He.create(Ur(r.unwrap())):r instanceof Ve?Ve.create(r.items.map(e=>Ur(e))):r}var _e=class r extends F{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=E.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==E.ZodParsedType.object){let l=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(l,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:l.parsedType}),_.INVALID}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Le&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let u=[];for(let l of o){let d=i[l],p=s.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new Pe(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Le){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of a)u.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")a.length>0&&((0,_.addIssueToContext)(s,{code:C.ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of a){let p=s.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new Pe(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of u){let p=await d.key,v=await d.value;l.push({key:p,value:v,alwaysSet:d.alwaysSet})}return l}).then(l=>_.ParseStatus.mergeObjectSync(n,l)):_.ParseStatus.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return O.errorUtil.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:O.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:L.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of E.util.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of E.util.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Ur(this)}partial(e){let t={};for(let n of E.util.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of E.util.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof $e;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Ya(E.util.objectKeys(this.shape))}};y.ZodObject=_e;_e.create=(r,e)=>new _e({shape:()=>r,unknownKeys:"strip",catchall:Le.create(),typeName:L.ZodObject,...B(e)});_e.strictCreate=(r,e)=>new _e({shape:()=>r,unknownKeys:"strict",catchall:Le.create(),typeName:L.ZodObject,...B(e)});_e.lazycreate=(r,e)=>new _e({shape:r,unknownKeys:"strip",catchall:Le.create(),typeName:L.ZodObject,...B(e)});var nr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new C.ZodError(a.ctx.common.issues));return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union,unionErrors:o}),_.INVALID}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of n){let l={...t,common:{...t.common,issues:[]},parent:null},d=u._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(u=>new C.ZodError(u));return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union,unionErrors:a}),_.INVALID}}get options(){return this._def.options}};y.ZodUnion=nr;nr.create=(r,e)=>new nr({options:r,typeName:L.ZodUnion,...B(e)});var ot=r=>r instanceof ir?ot(r.schema):r instanceof ke?ot(r.innerType()):r instanceof or?[r.value]:r instanceof ar?r.options:r instanceof cr?E.util.objectValues(r.enum):r instanceof ur?ot(r._def.innerType):r instanceof tr?[void 0]:r instanceof rr?[null]:r instanceof $e?[void 0,...ot(r.unwrap())]:r instanceof He?[null,...ot(r.unwrap())]:r instanceof Tn||r instanceof dr?ot(r.unwrap()):r instanceof lr?ot(r._def.innerType):[],fs=class r extends F{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.object)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:t.parsedType}),_.INVALID;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);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}):((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),_.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=ot(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:L.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...B(n)})}};y.ZodDiscriminatedUnion=fs;function Ri(r,e){let t=(0,E.getParsedType)(r),n=(0,E.getParsedType)(e);if(r===e)return{valid:!0,data:r};if(t===E.ZodParsedType.object&&n===E.ZodParsedType.object){let s=E.util.objectKeys(e),i=E.util.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let u=Ri(r[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===E.ZodParsedType.array&&n===E.ZodParsedType.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],u=Ri(o,a);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===E.ZodParsedType.date&&n===E.ZodParsedType.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var sr=class extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if((0,_.isAborted)(i)||(0,_.isAborted)(o))return _.INVALID;let a=Ri(i.value,o.value);return a.valid?(((0,_.isDirty)(i)||(0,_.isDirty)(o))&&t.dirty(),{status:t.value,value:a.data}):((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_intersection_types}),_.INVALID)};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(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};y.ZodIntersection=sr;sr.create=(r,e,t)=>new sr({left:r,right:e,typeName:L.ZodIntersection,...B(t)});var Ve=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.array)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.array,received:n.parsedType}),_.INVALID;if(n.data.length<this._def.items.length)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.INVALID;!this._def.rest&&n.data.length>this._def.items.length&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Pe(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>_.ParseStatus.mergeArray(t,o)):_.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};y.ZodTuple=Ve;Ve.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ve({items:r,typeName:L.ZodTuple,rest:null,...B(e)})};var ps=class r extends F{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!==E.ZodParsedType.object)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:n.parsedType}),_.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Pe(n,a,n.path,a)),value:o._parse(new Pe(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?_.ParseStatus.mergeObjectAsync(t,s):_.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof F?new r({keyType:e,valueType:t,typeName:L.ZodRecord,...B(n)}):new r({keyType:Ct.create(),valueType:e,typeName:L.ZodRecord,...B(t)})}};y.ZodRecord=ps;var Fr=class extends F{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!==E.ZodParsedType.map)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.map,received:n.parsedType}),_.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,u],l)=>({key:s._parse(new Pe(n,a,n.path,[l,"key"])),value:i._parse(new Pe(n,u,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of o){let l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return _.INVALID;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let u of o){let l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return _.INVALID;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}}}};y.ZodMap=Fr;Fr.create=(r,e,t)=>new Fr({valueType:e,keyType:r,typeName:L.ZodMap,...B(t)});var Zr=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.set)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.set,received:n.parsedType}),_.INVALID;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(u){let l=new Set;for(let d of u){if(d.status==="aborted")return _.INVALID;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((u,l)=>i._parse(new Pe(n,u,n.path,l)));return n.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:O.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};y.ZodSet=Zr;Zr.create=(r,e)=>new Zr({valueType:r,minSize:null,maxSize:null,typeName:L.ZodSet,...B(e)});var ms=class r extends F{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.function)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.function,received:t.parsedType}),_.INVALID;function n(a,u){return(0,_.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,hs.getErrorMap)(),hs.defaultErrorMap].filter(l=>!!l),issueData:{code:C.ZodIssueCode.invalid_arguments,argumentsError:u}})}function s(a,u){return(0,_.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,hs.getErrorMap)(),hs.defaultErrorMap].filter(l=>!!l),issueData:{code:C.ZodIssueCode.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof It){let a=this;return(0,_.OK)(async function(...u){let l=new C.ZodError([]),d=await a._def.args.parseAsync(u,i).catch(S=>{throw l.addIssue(n(u,S)),l}),p=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw l.addIssue(s(p,S)),l})})}else{let a=this;return(0,_.OK)(function(...u){let l=a._def.args.safeParse(u,i);if(!l.success)throw new C.ZodError([n(u,l.error)]);let d=Reflect.apply(o,this,l.data),p=a._def.returns.safeParse(d,i);if(!p.success)throw new C.ZodError([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ve.create(e).rest(at.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Ve.create([]).rest(at.create()),returns:t||at.create(),typeName:L.ZodFunction,...B(n)})}};y.ZodFunction=ms;var ir=class extends F{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})}};y.ZodLazy=ir;ir.create=(r,e)=>new ir({getter:r,typeName:L.ZodLazy,...B(e)});var or=class extends F{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{received:t.data,code:C.ZodIssueCode.invalid_literal,expected:this._def.value}),_.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};y.ZodLiteral=or;or.create=(r,e)=>new or({value:r,typeName:L.ZodLiteral,...B(e)});function Ya(r,e){return new ar({values:r,typeName:L.ZodEnum,...B(e)})}var ar=class r extends F{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,_.addIssueToContext)(t,{expected:E.util.joinValues(n),received:t.parsedType,code:C.ZodIssueCode.invalid_type}),_.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,_.addIssueToContext)(t,{received:t.data,code:C.ZodIssueCode.invalid_enum_value,options:n}),_.INVALID}return(0,_.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};y.ZodEnum=ar;ar.create=Ya;var cr=class extends F{_parse(e){let t=E.util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==E.ZodParsedType.string&&n.parsedType!==E.ZodParsedType.number){let s=E.util.objectValues(t);return(0,_.addIssueToContext)(n,{expected:E.util.joinValues(s),received:n.parsedType,code:C.ZodIssueCode.invalid_type}),_.INVALID}if(this._cache||(this._cache=new Set(E.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=E.util.objectValues(t);return(0,_.addIssueToContext)(n,{received:n.data,code:C.ZodIssueCode.invalid_enum_value,options:s}),_.INVALID}return(0,_.OK)(e.data)}get enum(){return this._def.values}};y.ZodNativeEnum=cr;cr.create=(r,e)=>new cr({values:r,typeName:L.ZodNativeEnum,...B(e)});var It=class extends F{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.promise&&t.common.async===!1)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.promise,received:t.parsedType}),_.INVALID;let n=t.parsedType===E.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,_.OK)(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};y.ZodPromise=It;It.create=(r,e)=>new It({type:r,typeName:L.ZodPromise,...B(e)});var ke=class extends F{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,_.addIssueToContext)(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return _.INVALID;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?_.INVALID:u.status==="dirty"||t.value==="dirty"?(0,_.DIRTY)(u.value):u});{if(t.value==="aborted")return _.INVALID;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?_.INVALID:a.status==="dirty"||t.value==="dirty"?(0,_.DIRTY)(a.value):a}}if(s.type==="refinement"){let o=a=>{let u=s.refinement(a,i);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?_.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?_.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!(0,_.isValid)(o))return _.INVALID;let a=s.transform(o.value,i);if(a instanceof Promise)throw new 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(o=>(0,_.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):_.INVALID);E.util.assertNever(s)}};y.ZodEffects=ke;y.ZodTransformer=ke;ke.create=(r,e,t)=>new ke({schema:r,typeName:L.ZodEffects,effect:e,...B(t)});ke.createWithPreprocess=(r,e,t)=>new ke({schema:e,effect:{type:"preprocess",transform:r},typeName:L.ZodEffects,...B(t)});var $e=class extends F{_parse(e){return this._getType(e)===E.ZodParsedType.undefined?(0,_.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodOptional=$e;$e.create=(r,e)=>new $e({innerType:r,typeName:L.ZodOptional,...B(e)});var He=class extends F{_parse(e){return this._getType(e)===E.ZodParsedType.null?(0,_.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodNullable=He;He.create=(r,e)=>new He({innerType:r,typeName:L.ZodNullable,...B(e)});var ur=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===E.ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};y.ZodDefault=ur;ur.create=(r,e)=>new ur({innerType:r,typeName:L.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});var lr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return(0,_.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new C.ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new C.ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};y.ZodCatch=lr;lr.create=(r,e)=>new lr({innerType:r,typeName:L.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});var Kr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.nan){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.nan,received:n.parsedType}),_.INVALID}return{status:"valid",value:e.data}}};y.ZodNaN=Kr;Kr.create=r=>new Kr({typeName:L.ZodNaN,...B(r)});y.BRAND=Symbol("zod_brand");var Tn=class extends F{_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}};y.ZodBranded=Tn;var xn=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?_.INVALID:i.status==="dirty"?(t.dirty(),(0,_.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?_.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:L.ZodPipeline})}};y.ZodPipeline=xn;var dr=class extends F{_parse(e){let t=this._def.innerType._parse(e),n=s=>((0,_.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,_.isAsync)(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};y.ZodReadonly=dr;dr.create=(r,e)=>new dr({innerType:r,typeName:L.ZodReadonly,...B(e)});function Ha(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Xa(r,e={},t){return r?Et.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Ha(e,n),u=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:u})}});if(!i){let o=Ha(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):Et.create()}y.late={object:_e.lazycreate};var L;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(L||(y.ZodFirstPartyTypeKind=L={}));var Rf=(r,e={message:`Input not instance of ${r.name}`})=>Xa(t=>t instanceof r,e);y.instanceof=Rf;var Qa=Ct.create;y.string=Qa;var ec=Yt.create;y.number=ec;var $f=Kr.create;y.nan=$f;var Pf=Xt.create;y.bigint=Pf;var tc=Qt.create;y.boolean=tc;var jf=er.create;y.date=jf;var Of=qr.create;y.symbol=Of;var Nf=tr.create;y.undefined=Nf;var Mf=rr.create;y.null=Mf;var Df=Et.create;y.any=Df;var Lf=at.create;y.unknown=Lf;var zf=Le.create;y.never=zf;var Uf=Br.create;y.void=Uf;var qf=ct.create;y.array=qf;var Bf=_e.create;y.object=Bf;var Ff=_e.strictCreate;y.strictObject=Ff;var Zf=nr.create;y.union=Zf;var Kf=fs.create;y.discriminatedUnion=Kf;var Vf=sr.create;y.intersection=Vf;var Hf=Ve.create;y.tuple=Hf;var Gf=ps.create;y.record=Gf;var Wf=Fr.create;y.map=Wf;var Jf=Zr.create;y.set=Jf;var Yf=ms.create;y.function=Yf;var Xf=ir.create;y.lazy=Xf;var Qf=or.create;y.literal=Qf;var ep=ar.create;y.enum=ep;var tp=cr.create;y.nativeEnum=tp;var rp=It.create;y.promise=rp;var rc=ke.create;y.effect=rc;y.transformer=rc;var np=$e.create;y.optional=np;var sp=He.create;y.nullable=sp;var ip=ke.createWithPreprocess;y.preprocess=ip;var op=xn.create;y.pipeline=op;var ap=()=>Qa().optional();y.ostring=ap;var cp=()=>ec().optional();y.onumber=cp;var up=()=>tc().optional();y.oboolean=up;y.coerce={string:(r=>Ct.create({...r,coerce:!0})),number:(r=>Yt.create({...r,coerce:!0})),boolean:(r=>Qt.create({...r,coerce:!0})),bigint:(r=>Xt.create({...r,coerce:!0})),date:(r=>er.create({...r,coerce:!0}))};y.NEVER=_.INVALID});var $i=Y(je=>{"use strict";var lp=je&&je.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Vr=je&&je.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&lp(e,r,t)};Object.defineProperty(je,"__esModule",{value:!0});Vr(ls(),je);Vr(Ii(),je);Vr(Fa(),je);Vr(kn(),je);Vr(nc(),je);Vr(us(),je)});var oc=Y(ve=>{"use strict";var sc=ve&&ve.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),dp=ve&&ve.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),hp=ve&&ve.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&sc(e,r,t);return dp(e,r),e},fp=ve&&ve.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&sc(e,r,t)};Object.defineProperty(ve,"__esModule",{value:!0});ve.z=void 0;var ic=hp($i());ve.z=ic;fp($i(),ve);ve.default=ic});var Se=Y(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.ChatLoadResultMsg=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.RuleConfig=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.PROTOCOL_VERSION=void 0;h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.DeploySuggestResultMsg=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditListResultMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditScope=h.AuditSeverity=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.PROMPT_PRESETS=h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=void 0;h.missingAgentCapabilities=pp;h.parseRunnerMsg=gp;h.parseServerMsg=yp;var c=oc();h.PROTOCOL_VERSION="1.21";h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[]};function pp(r,e){let t=h.REGISTERED_AGENTS.find(n=>n.id===r);return t?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(n=>!t.capabilities[n]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var mp=r=>r.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>r.includes(e));h.needsInputMarkerIn=mp;h.RunStatus=c.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=c.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=c.z.enum(["plan_only","implement","respond","deploy"]);h.LabelAddedTrigger=c.z.object({type:c.z.literal("label_added"),label:c.z.string().min(1),doneLabel:c.z.string().min(1).default("agent-planned"),failedLabel:c.z.string().min(1).default("agent-failed")});h.CommentKeywordTrigger=c.z.object({type:c.z.literal("comment_keyword"),keyword:c.z.string().min(1),doneLabel:c.z.string().min(1).default("agent-implemented"),failedLabel:c.z.string().min(1).default("agent-failed")});h.StatusChangedTrigger=c.z.object({type:c.z.literal("status_changed"),status:c.z.string().min(1),doneLabel:c.z.string().min(1).default("agent-deployed"),failedLabel:c.z.string().min(1).default("agent-failed")});h.TriggerConfig=c.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.PlanOnlyAction=c.z.object({type:c.z.literal("plan_only"),promptTemplate:c.z.string().min(1),timeoutSeconds:c.z.number().int().positive().max(3600).default(900),agent:c.z.string().default(h.DEFAULT_AGENT_ID),model:c.z.string().default("")});h.ImplementAction=c.z.object({type:c.z.literal("implement"),promptTemplate:c.z.string().min(1),timeoutSeconds:c.z.number().int().positive().max(7200).default(1800),maxTurns:c.z.number().int().positive().max(500).default(120),requireApproval:c.z.boolean().default(!0),branchTemplate:c.z.string().min(1).default("agent/{{issueKey}}").refine(r=>r.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:c.z.string().min(1).default("main"),jiraTransition:c.z.string().optional(),jiraTransitionOnStart:c.z.string().optional(),jiraTransitionOnMerge:c.z.string().optional(),agent:c.z.string().default(h.DEFAULT_AGENT_ID),model:c.z.string().default(""),updateMemory:c.z.boolean().default(!1)});h.RespondAction=c.z.object({type:c.z.literal("respond"),promptTemplate:c.z.string().min(1),timeoutSeconds:c.z.number().int().positive().max(3600).default(600),agent:c.z.string().default(h.DEFAULT_AGENT_ID),model:c.z.string().default("")});h.DeployStep=c.z.object({name:c.z.string().min(1).max(120),run:c.z.string().min(1).max(4e3),continueOnError:c.z.boolean().default(!1)});h.PromotionMode=c.z.enum(["deploy_only","merge_and_deploy"]);h.EnvironmentConfig=c.z.object({id:c.z.string(),projectId:c.z.string(),name:c.z.string(),rank:c.z.number().int().nonnegative(),auditBeforeDeploy:c.z.enum(["","security","testing"]).default(""),branch:c.z.string().default(""),useDedicatedCheckout:c.z.boolean().default(!1),promotionMode:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:c.z.string().default("agent/{{issueKey}}"),steps:c.z.array(h.DeployStep).default([]),workdir:c.z.string().default(""),timeoutSeconds:c.z.number().int().positive().max(21600).default(1800),requiredSecrets:c.z.array(c.z.string()).default([]),requireApproval:c.z.boolean().default(!1),requireSyncCheck:c.z.boolean().default(!1),previousEnvBranch:c.z.string().optional(),deployFromColumn:c.z.string().default(""),deployToColumn:c.z.string().default("")});h.DeployAction=c.z.object({type:c.z.literal("deploy"),envSelection:c.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:c.z.string().optional(),requireStatus:c.z.string().optional()});h.ActionConfig=c.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=c.z.object({id:c.z.string(),name:c.z.string(),jiraProjectKey:c.z.string(),repoName:c.z.string(),componentRoutes:c.z.array(c.z.object({component:c.z.string().min(1),repoName:c.z.string().min(1)})).default([])});h.RuleConfig=c.z.object({id:c.z.string(),projectId:c.z.string(),name:c.z.string(),enabled:c.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.HelloMsg=c.z.object({type:c.z.literal("hello"),protocolVersion:c.z.string(),runnerVersion:c.z.string(),platform:c.z.string(),justBooted:c.z.boolean().optional()});h.HeartbeatMsg=c.z.object({type:c.z.literal("heartbeat"),ts:c.z.string()});h.RunClaimMsg=c.z.object({type:c.z.literal("run.claim"),requestId:c.z.string(),ruleId:c.z.string(),issueKey:c.z.string(),issueSummary:c.z.string().default(""),triggerFingerprint:c.z.string(),dedupKey:c.z.string().optional(),triggeredByAccountId:c.z.string().optional()});h.RunLogMsg=c.z.object({type:c.z.literal("run.log"),runId:c.z.string(),seq:c.z.number().int().nonnegative(),ts:c.z.string(),level:c.z.enum(["info","warn","error","agent"]),message:c.z.string().max(16384)});h.RunStatusMsg=c.z.object({type:c.z.literal("run.status"),runId:c.z.string(),status:h.RunStatus,error:c.z.string().optional(),errorKind:c.z.enum(["guard"]).optional(),costUsd:c.z.number().nonnegative().optional(),inputTokens:c.z.number().int().nonnegative().optional(),outputTokens:c.z.number().int().nonnegative().optional(),resultSummary:c.z.string().max(2e3).optional(),billingMode:c.z.enum(["subscription","api","unknown"]).optional(),model:c.z.string().max(200).optional(),prUrl:c.z.string().optional(),headSha:c.z.string().optional(),deployedRef:c.z.string().optional(),retryAvailable:c.z.boolean().optional()});h.ProjectTestResultMsg=c.z.object({type:c.z.literal("project.test.result"),requestId:c.z.string(),ok:c.z.boolean(),checks:c.z.array(c.z.object({name:c.z.string(),ok:c.z.boolean(),detail:c.z.string()}))});h.RuleDiagnoseResultMsg=c.z.object({type:c.z.literal("rule.diagnose.result"),requestId:c.z.string(),checks:c.z.array(c.z.object({name:c.z.string(),ok:c.z.boolean(),detail:c.z.string()})),matchedCount:c.z.number().int().nonnegative(),excludedCount:c.z.number().int().nonnegative(),excludedSample:c.z.array(c.z.string()).max(5)});h.DeployClaimMsg=c.z.object({type:c.z.literal("deploy.claim"),requestId:c.z.string(),projectId:c.z.string(),ruleId:c.z.string(),issueKey:c.z.string(),issueSummary:c.z.string().default(""),environmentName:c.z.string(),requestedByAccountId:c.z.string().optional(),requestedByDisplayName:c.z.string().default(""),dedupKey:c.z.string(),triggerFingerprint:c.z.string()});h.DeployClaimResultMsg=c.z.object({type:c.z.literal("deploy.claim.result"),requestId:c.z.string(),accepted:c.z.boolean(),runId:c.z.string().optional(),environment:h.EnvironmentConfig.optional(),reason:c.z.string().optional(),code:c.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});h.JiraUsersResultMsg=c.z.object({type:c.z.literal("jira.users.result"),requestId:c.z.string(),ok:c.z.boolean(),users:c.z.array(c.z.object({accountId:c.z.string(),displayName:c.z.string(),email:c.z.string().default(""),active:c.z.boolean().default(!0)})).default([]),error:c.z.string().optional()});h.ChatStreamMsg=c.z.object({type:c.z.literal("chat.stream"),requestId:c.z.string(),seq:c.z.number().int().nonnegative(),text:c.z.string().max(8e3)});h.ChatListMsg=c.z.object({type:c.z.literal("chat.list"),requestId:c.z.string(),projectId:c.z.string()});h.ChatListResultMsg=c.z.object({type:c.z.literal("chat.list.result"),requestId:c.z.string(),sessions:c.z.array(c.z.object({sessionId:c.z.string(),title:c.z.string().default(""),updatedAt:c.z.string().default(""),messageCount:c.z.number().int().nonnegative().default(0)})).default([])});h.ChatLoadMsg=c.z.object({type:c.z.literal("chat.load"),requestId:c.z.string(),sessionId:c.z.string()});h.ChatLoadResultMsg=c.z.object({type:c.z.literal("chat.load.result"),requestId:c.z.string(),ok:c.z.boolean(),projectId:c.z.string().default(""),messages:c.z.array(c.z.object({role:c.z.enum(["user","agent"]),text:c.z.string()})).default([]),error:c.z.string().optional()});h.BoardFetchMsg=c.z.object({type:c.z.literal("board.fetch"),requestId:c.z.string(),projectId:c.z.string()});h.BoardFetchResultMsg=c.z.object({type:c.z.literal("board.fetch.result"),requestId:c.z.string(),ok:c.z.boolean(),browseBaseUrl:c.z.string().default(""),columns:c.z.array(c.z.object({name:c.z.string(),issues:c.z.array(c.z.object({key:c.z.string(),summary:c.z.string(),labels:c.z.array(c.z.string()).default([])})).default([])})).default([]),error:c.z.string().optional()});h.BoardTriggerMsg=c.z.object({type:c.z.literal("board.trigger"),requestId:c.z.string(),projectId:c.z.string(),issueKey:c.z.string(),comment:c.z.string().max(2e3).default(""),removeLabel:c.z.string().default(""),requestedBy:c.z.string().default(""),requestedByEmail:c.z.string().default(""),reimplement:c.z.boolean().default(!1)});h.BoardTriggerResultMsg=c.z.object({type:c.z.literal("board.trigger.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional()});h.EpicListMsg=c.z.object({type:c.z.literal("epic.list"),requestId:c.z.string(),projectId:c.z.string(),epicKey:c.z.string().default("")});h.EpicChild=c.z.object({key:c.z.string(),summary:c.z.string(),status:c.z.string(),statusCategory:c.z.string(),labels:c.z.array(c.z.string()).default([])});h.EpicListResultMsg=c.z.object({type:c.z.literal("epic.list.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),epics:c.z.array(c.z.object({key:c.z.string(),summary:c.z.string(),status:c.z.string()})).default([]),children:c.z.array(h.EpicChild).default([])});h.EpicSuggestMsg=c.z.object({type:c.z.literal("epic.suggest"),requestId:c.z.string(),projectId:c.z.string(),epicKey:c.z.string().min(1),model:c.z.string().default("")});h.EpicSuggestResultMsg=c.z.object({type:c.z.literal("epic.suggest.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),issueKey:c.z.string().default(""),reason:c.z.string().default(""),considered:c.z.number().int().default(0)});h.AuditRole=c.z.enum(["security","testing","architecture"]);h.AuditSeverity=c.z.enum(["critical","high","medium","low","info"]);h.AuditScope=c.z.object({kind:c.z.enum(["repo","ticket","branch"]).default("repo"),ref:c.z.string().default("")});h.AuditFinding=c.z.object({id:c.z.string().min(1),title:c.z.string().min(1),ruleId:c.z.string().max(20).default(""),severity:h.AuditSeverity,area:c.z.string().default(""),evidence:c.z.array(c.z.object({file:c.z.string().min(1),line:c.z.number().int().positive().optional(),note:c.z.string().default("")})).min(1),fix:c.z.string().default("")});h.AuditRecord=c.z.object({id:c.z.string(),role:h.AuditRole,createdAt:c.z.string(),model:c.z.string().default(""),summary:c.z.string().default(""),packNames:c.z.array(c.z.string()).default([]),findings:c.z.array(h.AuditFinding).default([]),costUsd:c.z.number().default(0),review:c.z.object({selected:c.z.array(c.z.string()),updatedAt:c.z.string()}).optional(),verdicts:c.z.record(c.z.object({verdict:c.z.enum(["valid","false-positive","wont-fix"]),note:c.z.string().default(""),by:c.z.string().default(""),at:c.z.string().default("")})).default({}),lessonsWritten:c.z.array(c.z.string()).default([]),ticketed:c.z.record(c.z.string()).default({}),scope:h.AuditScope.default({kind:"repo",ref:""}),testRun:c.z.array(c.z.object({command:c.z.string(),exitCode:c.z.number().int(),durationMs:c.z.number().int().default(0),tail:c.z.string().default("")})).optional()});h.AuditStartMsg=c.z.object({type:c.z.literal("audit.start"),requestId:c.z.string(),projectId:c.z.string(),role:h.AuditRole,model:c.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""})});h.AuditStartResultMsg=c.z.object({type:c.z.literal("audit.start.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditListMsg=c.z.object({type:c.z.literal("audit.list"),requestId:c.z.string(),projectId:c.z.string()});h.AuditListResultMsg=c.z.object({type:c.z.literal("audit.list.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),audits:c.z.array(c.z.object({id:c.z.string(),role:h.AuditRole,createdAt:c.z.string(),findingCount:c.z.number().int(),bySeverity:c.z.record(c.z.number().int()).default({})})).default([])});h.AuditGetMsg=c.z.object({type:c.z.literal("audit.get"),requestId:c.z.string(),projectId:c.z.string(),auditId:c.z.string()});h.AuditGetResultMsg=c.z.object({type:c.z.literal("audit.get.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditReviewMsg=c.z.object({type:c.z.literal("audit.review"),requestId:c.z.string(),projectId:c.z.string(),auditId:c.z.string(),selected:c.z.array(c.z.string()).optional(),ticketed:c.z.array(c.z.object({findingId:c.z.string(),issueKey:c.z.string()})).default([]),verdicts:c.z.array(c.z.object({findingId:c.z.string(),verdict:c.z.enum(["valid","false-positive","wont-fix"]),note:c.z.string().max(2e3).default("")})).default([]),verdictBy:c.z.string().default("")});h.AuditReviewResultMsg=c.z.object({type:c.z.literal("audit.review.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),audit:h.AuditRecord.optional()});h.KnowledgeListMsg=c.z.object({type:c.z.literal("knowledge.list"),requestId:c.z.string(),projectId:c.z.string()});h.KnowledgeFile=c.z.object({role:h.AuditRole,level:c.z.enum(["global","org","project"]),source:c.z.enum(["pack","lessons"]),name:c.z.string(),content:c.z.string(),editable:c.z.boolean().default(!1)});h.KnowledgeListResultMsg=c.z.object({type:c.z.literal("knowledge.list.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),files:c.z.array(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=c.z.object({type:c.z.literal("knowledge.save"),requestId:c.z.string(),projectId:c.z.string(),role:h.AuditRole,level:c.z.enum(["org","project"]),source:c.z.enum(["pack","lessons"]),name:c.z.string().min(1).max(100),content:c.z.string().max(6e4),append:c.z.boolean().default(!1),by:c.z.string().default("")});h.KnowledgeSaveResultMsg=c.z.object({type:c.z.literal("knowledge.save.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional()});h.TeamCredsMsg=c.z.object({type:c.z.literal("team.creds"),requestId:c.z.string(),emails:c.z.array(c.z.string()).max(200)});h.TeamCredsResultMsg=c.z.object({type:c.z.literal("team.creds.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),githubShared:c.z.boolean().default(!1),sharedGithubLogin:c.z.string().default(""),entries:c.z.array(c.z.object({email:c.z.string(),jira:c.z.enum(["own","runner-account","missing"]),jiraAs:c.z.string().default(""),github:c.z.enum(["own","shared","missing"]),githubAs:c.z.string().default("")})).default([])});h.ChatFile=c.z.object({name:c.z.string().min(1).max(255),contentBase64:c.z.string().min(1).max(6e6)});h.ChatTurnMsg=c.z.object({type:c.z.literal("chat.turn"),requestId:c.z.string(),projectId:c.z.string(),sessionId:c.z.string().optional(),message:c.z.string().min(1).max(2e4),userName:c.z.string().default(""),model:c.z.string().default(""),files:c.z.array(h.ChatFile).max(8).default([])});h.ChatTurnResultMsg=c.z.object({type:c.z.literal("chat.turn.result"),requestId:c.z.string(),ok:c.z.boolean(),sessionId:c.z.string().default(""),reply:c.z.string().default(""),error:c.z.string().optional()});h.ChatCreateTicketMsg=c.z.object({type:c.z.literal("chat.create.ticket"),requestId:c.z.string(),projectId:c.z.string(),summary:c.z.string().min(1).max(250),description:c.z.string().default(""),triggerComment:c.z.string().default(""),requestedBy:c.z.string().default(""),requestedByEmail:c.z.string().default(""),asEpic:c.z.boolean().default(!1),children:c.z.array(c.z.object({summary:c.z.string().min(1),description:c.z.string().default("")})).max(20).default([]),files:c.z.array(h.ChatFile).max(8).default([])});h.ChatCreateTicketResultMsg=c.z.object({type:c.z.literal("chat.create.ticket.result"),requestId:c.z.string(),ok:c.z.boolean(),issueKey:c.z.string().default(""),error:c.z.string().optional(),childKeys:c.z.array(c.z.string()).default([])});h.EnvPreflightMsg=c.z.object({type:c.z.literal("env.preflight"),requestId:c.z.string(),projectId:c.z.string(),environmentName:c.z.string().default(""),steps:c.z.array(h.DeployStep).default([]),requiredSecrets:c.z.array(c.z.string()).default([]),workdir:c.z.string().default(""),branch:c.z.string().default("")});h.EnvPreflightResultMsg=c.z.object({type:c.z.literal("env.preflight.result"),requestId:c.z.string(),ok:c.z.boolean(),checks:c.z.array(c.z.object({name:c.z.string(),ok:c.z.boolean(),detail:c.z.string().default("")})).default([])});h.DeploySuggestResultMsg=c.z.object({type:c.z.literal("deploy.suggest.result"),requestId:c.z.string(),ok:c.z.boolean(),steps:c.z.array(h.DeployStep).default([]),requiredSecrets:c.z.array(c.z.string()).default([]),notes:c.z.string().default(""),error:c.z.string().optional()});h.RunnerToServerMsg=c.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg]);h.HelloAckMsg=c.z.object({type:c.z.literal("hello.ack"),runnerId:c.z.string(),runnerName:c.z.string(),serverTime:c.z.string()});h.ConfigMsg=c.z.object({type:c.z.literal("config"),projects:c.z.array(h.ProjectConfig),rules:c.z.array(h.RuleConfig),environments:c.z.array(h.EnvironmentConfig).default([]),pollingPaused:c.z.boolean().default(!1)});h.RunClaimResultMsg=c.z.object({type:c.z.literal("run.claim.result"),requestId:c.z.string(),accepted:c.z.boolean(),runId:c.z.string().optional(),reason:c.z.string().optional(),claudeProfile:c.z.string().optional(),actorEmail:c.z.string().optional()});h.ProjectTestMsg=c.z.object({type:c.z.literal("project.test"),requestId:c.z.string(),projectId:c.z.string()});h.RuleDiagnoseMsg=c.z.object({type:c.z.literal("rule.diagnose"),requestId:c.z.string(),ruleId:c.z.string()});h.RunCancelMsg=c.z.object({type:c.z.literal("run.cancel"),runId:c.z.string()});h.RunApprovedMsg=c.z.object({type:c.z.literal("run.approved"),runId:c.z.string(),headSha:c.z.string().optional()});h.RunRejectedMsg=c.z.object({type:c.z.literal("run.rejected"),runId:c.z.string()});h.RunRetryPushMsg=c.z.object({type:c.z.literal("run.retryPush"),runId:c.z.string()});h.DeployStartMsg=c.z.object({type:c.z.literal("deploy.start"),runId:c.z.string(),projectId:c.z.string(),issueKey:c.z.string(),issueSummary:c.z.string().default(""),environment:h.EnvironmentConfig,requestedBy:c.z.string().default(""),attempt:c.z.number().int().positive().default(1)});h.DeploySuggestMsg=c.z.object({type:c.z.literal("deploy.suggest"),requestId:c.z.string(),projectId:c.z.string(),environmentName:c.z.string(),notes:c.z.string().default(""),timeoutSeconds:c.z.number().int().positive().max(1800).default(300)});h.JiraUsersMsg=c.z.object({type:c.z.literal("jira.users"),requestId:c.z.string(),query:c.z.string().default("")});h.ServerToRunnerMsg=c.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.EnvPreflightMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg]);h.EnrollRequest=c.z.object({enrollToken:c.z.string().min(10),name:c.z.string().min(1).max(100),platform:c.z.string(),runnerVersion:c.z.string()});h.EnrollResponse=c.z.object({runnerId:c.z.string(),runnerToken:c.z.string(),controlPlaneWsUrl:c.z.string()});function gp(r){return h.RunnerToServerMsg.parse(r)}function yp(r){return h.ServerToRunnerMsg.parse(r)}h.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository \u2014 do not attempt to modify anything.
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function la(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}da.Command=vi});var ga=Y(Ee=>{var{Argument:fa}=Qn(),{Command:bi}=ha(),{CommanderError:Nd,InvalidArgumentError:pa}=vn(),{Help:Md}=di(),{Option:ma}=mi();Ee.program=new bi;Ee.createCommand=r=>new bi(r);Ee.createOption=(r,e)=>new ma(r,e);Ee.createArgument=(r,e)=>new fa(r,e);Ee.Command=bi;Ee.Option=ma;Ee.Argument=fa;Ee.Help=Md;Ee.CommanderError=Nd;Ee.InvalidArgumentError=pa;Ee.InvalidOptionArgumentError=pa});var xn=Y(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.getParsedType=te.ZodParsedType=te.objectUtil=te.util=void 0;var Ei;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Ei||(te.util=Ei={}));var za;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(za||(te.objectUtil=za={}));te.ZodParsedType=Ei.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var ef=r=>{switch(typeof r){case"undefined":return te.ZodParsedType.undefined;case"string":return te.ZodParsedType.string;case"number":return Number.isNaN(r)?te.ZodParsedType.nan:te.ZodParsedType.number;case"boolean":return te.ZodParsedType.boolean;case"function":return te.ZodParsedType.function;case"bigint":return te.ZodParsedType.bigint;case"symbol":return te.ZodParsedType.symbol;case"object":return Array.isArray(r)?te.ZodParsedType.array:r===null?te.ZodParsedType.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?te.ZodParsedType.promise:typeof Map<"u"&&r instanceof Map?te.ZodParsedType.map:typeof Set<"u"&&r instanceof Set?te.ZodParsedType.set:typeof Date<"u"&&r instanceof Date?te.ZodParsedType.date:te.ZodParsedType.object;default:return te.ZodParsedType.unknown}};te.getParsedType=ef});var hs=Y(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.ZodError=Tt.quotelessJson=Tt.ZodIssueCode=void 0;var Ua=xn();Tt.ZodIssueCode=Ua.util.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 tf=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");Tt.quotelessJson=tf;var Cn=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};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(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ua.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Tt.ZodError=Cn;Cn.create=r=>new Cn(r)});var Ai=Y(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});var fe=hs(),Yt=xn(),rf=(r,e)=>{let t;switch(r.code){case fe.ZodIssueCode.invalid_type:r.received===Yt.ZodParsedType.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case fe.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,Yt.util.jsonStringifyReplacer)}`;break;case fe.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${Yt.util.joinValues(r.keys,", ")}`;break;case fe.ZodIssueCode.invalid_union:t="Invalid input";break;case fe.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Yt.util.joinValues(r.options)}`;break;case fe.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${Yt.util.joinValues(r.options)}, received '${r.received}'`;break;case fe.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case fe.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case fe.ZodIssueCode.invalid_date:t="Invalid date";break;case fe.ZodIssueCode.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:Yt.util.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case fe.ZodIssueCode.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case fe.ZodIssueCode.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case fe.ZodIssueCode.custom:t="Invalid input";break;case fe.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case fe.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case fe.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,Yt.util.assertNever(r)}return{message:t}};Ii.default=rf});var fs=Y(xt=>{"use strict";var nf=xt&&xt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(xt,"__esModule",{value:!0});xt.defaultErrorMap=void 0;xt.setErrorMap=sf;xt.getErrorMap=of;var qa=nf(Ai());xt.defaultErrorMap=qa.default;var Ba=qa.default;function sf(r){Ba=r}function of(){return Ba}});var $i=Y(X=>{"use strict";var af=X&&X.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(X,"__esModule",{value:!0});X.isAsync=X.isValid=X.isDirty=X.isAborted=X.OK=X.DIRTY=X.INVALID=X.ParseStatus=X.EMPTY_PATH=X.makeIssue=void 0;X.addIssueToContext=lf;var uf=fs(),Fa=af(Ai()),cf=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};X.makeIssue=cf;X.EMPTY_PATH=[];function lf(r,e){let t=(0,uf.getErrorMap)(),n=(0,X.makeIssue)({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Fa.default?void 0:Fa.default].filter(s=>!!s)});r.common.issues.push(n)}var Ri=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return X.INVALID;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return X.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}};X.ParseStatus=Ri;X.INVALID=Object.freeze({status:"aborted"});var df=r=>({status:"dirty",value:r});X.DIRTY=df;var hf=r=>({status:"valid",value:r});X.OK=hf;var ff=r=>r.status==="aborted";X.isAborted=ff;var pf=r=>r.status==="dirty";X.isDirty=pf;var mf=r=>r.status==="valid";X.isValid=mf;var gf=r=>typeof Promise<"u"&&r instanceof Promise;X.isAsync=gf});var Ka=Y(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0})});var Ha=Y(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.errorUtil=void 0;var Va;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(Va||(ps.errorUtil=Va={}))});var iu=Y(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.discriminatedUnion=y.date=y.boolean=y.bigint=y.array=y.any=y.coerce=y.ZodFirstPartyTypeKind=y.late=y.ZodSchema=y.Schema=y.ZodReadonly=y.ZodPipeline=y.ZodBranded=y.BRAND=y.ZodNaN=y.ZodCatch=y.ZodDefault=y.ZodNullable=y.ZodOptional=y.ZodTransformer=y.ZodEffects=y.ZodPromise=y.ZodNativeEnum=y.ZodEnum=y.ZodLiteral=y.ZodLazy=y.ZodFunction=y.ZodSet=y.ZodMap=y.ZodRecord=y.ZodTuple=y.ZodIntersection=y.ZodDiscriminatedUnion=y.ZodUnion=y.ZodObject=y.ZodArray=y.ZodVoid=y.ZodNever=y.ZodUnknown=y.ZodAny=y.ZodNull=y.ZodUndefined=y.ZodSymbol=y.ZodDate=y.ZodBoolean=y.ZodBigInt=y.ZodNumber=y.ZodString=y.ZodType=void 0;y.NEVER=y.void=y.unknown=y.union=y.undefined=y.tuple=y.transformer=y.symbol=y.string=y.strictObject=y.set=y.record=y.promise=y.preprocess=y.pipeline=y.ostring=y.optional=y.onumber=y.oboolean=y.object=y.number=y.nullable=y.null=y.never=y.nativeEnum=y.nan=y.map=y.literal=y.lazy=y.intersection=y.instanceof=y.function=y.enum=y.effect=void 0;y.datetimeRegex=Xa;y.custom=eu;var C=hs(),ms=fs(),O=Ha(),_=$i(),E=xn(),Pe=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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}},Ga=(r,e)=>{if((0,_.isValid)(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new C.ZodError(r.common.issues);return this._error=t,this._error}}};function B(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:c}=r;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??t??a.defaultError}},description:s}}var F=class{get description(){return this._def.description}_getType(e){return(0,E.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,E.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,E.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,_.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let 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:(0,E.getParsedType)(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Ga(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,E.getParsedType)(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return(0,_.isValid)(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>(0,_.isValid)(n)?{value:n.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:(0,E.getParsedType)(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await((0,_.isAsync)(s)?s:Promise.resolve(s));return Ga(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:C.ZodIssueCode.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new ke({schema:this,typeName:L.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return $e.create(this,this._def)}nullable(){return He.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ut.create(this)}promise(){return It.create(this,this._def)}or(e){return sr.create([this,e],this._def)}and(e){return ir.create(this,e,this._def)}transform(e){return new ke({...B(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new lr({...B(this._def),innerType:this,defaultValue:t,typeName:L.ZodDefault})}brand(){return new En({typeName:L.ZodBranded,type:this,...B(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new dr({...B(this._def),innerType:this,catchValue:t,typeName:L.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return In.create(this,e)}readonly(){return hr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};y.ZodType=F;y.Schema=F;y.ZodSchema=F;var yf=/^c[^\s-]{8,}$/i,_f=/^[0-9a-z]+$/,vf=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bf=/^[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,wf=/^[a-z0-9_-]{21}$/i,kf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Sf=/^[-+]?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)?)??$/,Tf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Pi,Cf=/^(?:(?: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])$/,Ef=/^(?:(?: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])$/,If=/^(([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]))$/,Af=/^(([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])$/,Rf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$f=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ja="((\\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])))",Pf=new RegExp(`^${Ja}$`);function Ya(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function jf(r){return new RegExp(`^${Ya(r)}$`)}function Xa(r){let e=`${Ja}T${Ya(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Of(r,e){return!!((e==="v4"||!e)&&Cf.test(r)||(e==="v6"||!e)&&If.test(r))}function Nf(r,e){if(!kf.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Mf(r,e){return!!((e==="v4"||!e)&&Ef.test(r)||(e==="v6"||!e)&&Af.test(r))}var Ct=class r extends F{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==E.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.string,received:i.parsedType}),_.INVALID}let n=new _.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Tf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"email",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Pi||(Pi=new RegExp(xf,"u")),Pi.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"emoji",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")bf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"uuid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")wf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"nanoid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")yf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cuid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")_f.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cuid2",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")vf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"ulid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"url",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"regex",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Xa(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Pf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?jf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Sf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"duration",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Of(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"ip",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Nf(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"jwt",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Mf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cidr",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Rf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"base64",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?$f.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"base64url",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):E.util.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:C.ZodIssueCode.invalid_string,...O.errorUtil.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...O.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...O.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...O.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...O.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...O.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...O.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...O.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...O.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...O.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,O.errorUtil.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodString=Ct;Ct.create=r=>new Ct({checks:[],typeName:L.ZodString,coerce:r?.coerce??!1,...B(r)});function Df(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Xt=class r extends F{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)!==E.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.number,received:i.parsedType}),_.INVALID}let n,s=new _.ParseStatus;for(let i of this._def.checks)i.kind==="int"?E.util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Df(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_finite,message:i.message}),s.dirty()):E.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:O.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.errorUtil.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"&&E.util.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;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)}};y.ZodNumber=Xt;Xt.create=r=>new Xt({checks:[],typeName:L.ZodNumber,coerce:r?.coerce||!1,...B(r)});var Qt=class r extends F{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)!==E.ZodParsedType.bigint)return this._getInvalidInput(e);let n,s=new _.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):E.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.bigint,received:t.parsedType}),_.INVALID}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.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}};y.ZodBigInt=Qt;Qt.create=r=>new Qt({checks:[],typeName:L.ZodBigInt,coerce:r?.coerce??!1,...B(r)});var er=class extends F{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==E.ZodParsedType.boolean){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.boolean,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodBoolean=er;er.create=r=>new er({typeName:L.ZodBoolean,coerce:r?.coerce||!1,...B(r)});var tr=class r extends F{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==E.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.date,received:i.parsedType}),_.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_date}),_.INVALID}let n=new _.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):E.util.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:O.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:O.errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};y.ZodDate=tr;tr.create=r=>new tr({checks:[],coerce:r?.coerce||!1,typeName:L.ZodDate,...B(r)});var Fr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.symbol){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.symbol,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodSymbol=Fr;Fr.create=r=>new Fr({typeName:L.ZodSymbol,...B(r)});var rr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.undefined,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodUndefined=rr;rr.create=r=>new rr({typeName:L.ZodUndefined,...B(r)});var nr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.null){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.null,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodNull=nr;nr.create=r=>new nr({typeName:L.ZodNull,...B(r)});var Et=class extends F{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,_.OK)(e.data)}};y.ZodAny=Et;Et.create=r=>new Et({typeName:L.ZodAny,...B(r)});var at=class extends F{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,_.OK)(e.data)}};y.ZodUnknown=at;at.create=r=>new at({typeName:L.ZodUnknown,...B(r)});var Le=class extends F{_parse(e){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.never,received:t.parsedType}),_.INVALID}};y.ZodNever=Le;Le.create=r=>new Le({typeName:L.ZodNever,...B(r)});var Zr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.void,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodVoid=Zr;Zr.create=r=>new Zr({typeName:L.ZodVoid,...B(r)});var ut=class r extends F{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==E.ZodParsedType.array)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.array,received:t.parsedType}),_.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&((0,_.addIssueToContext)(t,{code:o?C.ZodIssueCode.too_big:C.ZodIssueCode.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Pe(t,o,t.path,a)))).then(o=>_.ParseStatus.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Pe(t,o,t.path,a)));return _.ParseStatus.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:O.errorUtil.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:O.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};y.ZodArray=ut;ut.create=(r,e)=>new ut({type:r,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...B(e)});function Br(r){if(r instanceof _e){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=$e.create(Br(n))}return new _e({...r._def,shape:()=>e})}else return r instanceof ut?new ut({...r._def,type:Br(r.element)}):r instanceof $e?$e.create(Br(r.unwrap())):r instanceof He?He.create(Br(r.unwrap())):r instanceof Ve?Ve.create(r.items.map(e=>Br(e))):r}var _e=class r extends F{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=E.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==E.ZodParsedType.object){let l=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(l,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:l.parsedType}),_.INVALID}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Le&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let d=i[l],p=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new Pe(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Le){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")a.length>0&&((0,_.addIssueToContext)(s,{code:C.ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of a){let p=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new Pe(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of c){let p=await d.key,v=await d.value;l.push({key:p,value:v,alwaysSet:d.alwaysSet})}return l}).then(l=>_.ParseStatus.mergeObjectSync(n,l)):_.ParseStatus.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return O.errorUtil.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:O.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:L.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of E.util.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of E.util.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Br(this)}partial(e){let t={};for(let n of E.util.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of E.util.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof $e;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Qa(E.util.objectKeys(this.shape))}};y.ZodObject=_e;_e.create=(r,e)=>new _e({shape:()=>r,unknownKeys:"strip",catchall:Le.create(),typeName:L.ZodObject,...B(e)});_e.strictCreate=(r,e)=>new _e({shape:()=>r,unknownKeys:"strict",catchall:Le.create(),typeName:L.ZodObject,...B(e)});_e.lazycreate=(r,e)=>new _e({shape:r,unknownKeys:"strip",catchall:Le.create(),typeName:L.ZodObject,...B(e)});var sr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new C.ZodError(a.ctx.common.issues));return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union,unionErrors:o}),_.INVALID}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of n){let l={...t,common:{...t.common,issues:[]},parent:null},d=c._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new C.ZodError(c));return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union,unionErrors:a}),_.INVALID}}get options(){return this._def.options}};y.ZodUnion=sr;sr.create=(r,e)=>new sr({options:r,typeName:L.ZodUnion,...B(e)});var ot=r=>r instanceof or?ot(r.schema):r instanceof ke?ot(r.innerType()):r instanceof ar?[r.value]:r instanceof ur?r.options:r instanceof cr?E.util.objectValues(r.enum):r instanceof lr?ot(r._def.innerType):r instanceof rr?[void 0]:r instanceof nr?[null]:r instanceof $e?[void 0,...ot(r.unwrap())]:r instanceof He?[null,...ot(r.unwrap())]:r instanceof En||r instanceof hr?ot(r.unwrap()):r instanceof dr?ot(r._def.innerType):[],gs=class r extends F{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.object)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:t.parsedType}),_.INVALID;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);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}):((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),_.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=ot(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:L.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...B(n)})}};y.ZodDiscriminatedUnion=gs;function ji(r,e){let t=(0,E.getParsedType)(r),n=(0,E.getParsedType)(e);if(r===e)return{valid:!0,data:r};if(t===E.ZodParsedType.object&&n===E.ZodParsedType.object){let s=E.util.objectKeys(e),i=E.util.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let c=ji(r[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(t===E.ZodParsedType.array&&n===E.ZodParsedType.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],c=ji(o,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===E.ZodParsedType.date&&n===E.ZodParsedType.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var ir=class extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if((0,_.isAborted)(i)||(0,_.isAborted)(o))return _.INVALID;let a=ji(i.value,o.value);return a.valid?(((0,_.isDirty)(i)||(0,_.isDirty)(o))&&t.dirty(),{status:t.value,value:a.data}):((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_intersection_types}),_.INVALID)};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(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};y.ZodIntersection=ir;ir.create=(r,e,t)=>new ir({left:r,right:e,typeName:L.ZodIntersection,...B(t)});var Ve=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.array)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.array,received:n.parsedType}),_.INVALID;if(n.data.length<this._def.items.length)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.INVALID;!this._def.rest&&n.data.length>this._def.items.length&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Pe(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>_.ParseStatus.mergeArray(t,o)):_.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};y.ZodTuple=Ve;Ve.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ve({items:r,typeName:L.ZodTuple,rest:null,...B(e)})};var ys=class r extends F{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!==E.ZodParsedType.object)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:n.parsedType}),_.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Pe(n,a,n.path,a)),value:o._parse(new Pe(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?_.ParseStatus.mergeObjectAsync(t,s):_.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof F?new r({keyType:e,valueType:t,typeName:L.ZodRecord,...B(n)}):new r({keyType:Ct.create(),valueType:e,typeName:L.ZodRecord,...B(t)})}};y.ZodRecord=ys;var Kr=class extends F{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!==E.ZodParsedType.map)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.map,received:n.parsedType}),_.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,c],l)=>({key:s._parse(new Pe(n,a,n.path,[l,"key"])),value:i._parse(new Pe(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return _.INVALID;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return _.INVALID;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}}}};y.ZodMap=Kr;Kr.create=(r,e,t)=>new Kr({valueType:e,keyType:r,typeName:L.ZodMap,...B(t)});var Vr=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.set)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.set,received:n.parsedType}),_.INVALID;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(c){let l=new Set;for(let d of c){if(d.status==="aborted")return _.INVALID;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((c,l)=>i._parse(new Pe(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:O.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};y.ZodSet=Vr;Vr.create=(r,e)=>new Vr({valueType:r,minSize:null,maxSize:null,typeName:L.ZodSet,...B(e)});var _s=class r extends F{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.function)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.function,received:t.parsedType}),_.INVALID;function n(a,c){return(0,_.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ms.getErrorMap)(),ms.defaultErrorMap].filter(l=>!!l),issueData:{code:C.ZodIssueCode.invalid_arguments,argumentsError:c}})}function s(a,c){return(0,_.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ms.getErrorMap)(),ms.defaultErrorMap].filter(l=>!!l),issueData:{code:C.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof It){let a=this;return(0,_.OK)(async function(...c){let l=new C.ZodError([]),d=await a._def.args.parseAsync(c,i).catch(S=>{throw l.addIssue(n(c,S)),l}),p=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw l.addIssue(s(p,S)),l})})}else{let a=this;return(0,_.OK)(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new C.ZodError([n(c,l.error)]);let d=Reflect.apply(o,this,l.data),p=a._def.returns.safeParse(d,i);if(!p.success)throw new C.ZodError([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ve.create(e).rest(at.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Ve.create([]).rest(at.create()),returns:t||at.create(),typeName:L.ZodFunction,...B(n)})}};y.ZodFunction=_s;var or=class extends F{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})}};y.ZodLazy=or;or.create=(r,e)=>new or({getter:r,typeName:L.ZodLazy,...B(e)});var ar=class extends F{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{received:t.data,code:C.ZodIssueCode.invalid_literal,expected:this._def.value}),_.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};y.ZodLiteral=ar;ar.create=(r,e)=>new ar({value:r,typeName:L.ZodLiteral,...B(e)});function Qa(r,e){return new ur({values:r,typeName:L.ZodEnum,...B(e)})}var ur=class r extends F{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,_.addIssueToContext)(t,{expected:E.util.joinValues(n),received:t.parsedType,code:C.ZodIssueCode.invalid_type}),_.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,_.addIssueToContext)(t,{received:t.data,code:C.ZodIssueCode.invalid_enum_value,options:n}),_.INVALID}return(0,_.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};y.ZodEnum=ur;ur.create=Qa;var cr=class extends F{_parse(e){let t=E.util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==E.ZodParsedType.string&&n.parsedType!==E.ZodParsedType.number){let s=E.util.objectValues(t);return(0,_.addIssueToContext)(n,{expected:E.util.joinValues(s),received:n.parsedType,code:C.ZodIssueCode.invalid_type}),_.INVALID}if(this._cache||(this._cache=new Set(E.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=E.util.objectValues(t);return(0,_.addIssueToContext)(n,{received:n.data,code:C.ZodIssueCode.invalid_enum_value,options:s}),_.INVALID}return(0,_.OK)(e.data)}get enum(){return this._def.values}};y.ZodNativeEnum=cr;cr.create=(r,e)=>new cr({values:r,typeName:L.ZodNativeEnum,...B(e)});var It=class extends F{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.promise&&t.common.async===!1)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.promise,received:t.parsedType}),_.INVALID;let n=t.parsedType===E.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,_.OK)(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};y.ZodPromise=It;It.create=(r,e)=>new It({type:r,typeName:L.ZodPromise,...B(e)});var ke=class extends F{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,_.addIssueToContext)(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return _.INVALID;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?_.INVALID:c.status==="dirty"||t.value==="dirty"?(0,_.DIRTY)(c.value):c});{if(t.value==="aborted")return _.INVALID;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?_.INVALID:a.status==="dirty"||t.value==="dirty"?(0,_.DIRTY)(a.value):a}}if(s.type==="refinement"){let o=a=>{let c=s.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?_.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?_.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!(0,_.isValid)(o))return _.INVALID;let a=s.transform(o.value,i);if(a instanceof Promise)throw new 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(o=>(0,_.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):_.INVALID);E.util.assertNever(s)}};y.ZodEffects=ke;y.ZodTransformer=ke;ke.create=(r,e,t)=>new ke({schema:r,typeName:L.ZodEffects,effect:e,...B(t)});ke.createWithPreprocess=(r,e,t)=>new ke({schema:e,effect:{type:"preprocess",transform:r},typeName:L.ZodEffects,...B(t)});var $e=class extends F{_parse(e){return this._getType(e)===E.ZodParsedType.undefined?(0,_.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodOptional=$e;$e.create=(r,e)=>new $e({innerType:r,typeName:L.ZodOptional,...B(e)});var He=class extends F{_parse(e){return this._getType(e)===E.ZodParsedType.null?(0,_.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodNullable=He;He.create=(r,e)=>new He({innerType:r,typeName:L.ZodNullable,...B(e)});var lr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===E.ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};y.ZodDefault=lr;lr.create=(r,e)=>new lr({innerType:r,typeName:L.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});var dr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return(0,_.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new C.ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new C.ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};y.ZodCatch=dr;dr.create=(r,e)=>new dr({innerType:r,typeName:L.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});var Hr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.nan){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.nan,received:n.parsedType}),_.INVALID}return{status:"valid",value:e.data}}};y.ZodNaN=Hr;Hr.create=r=>new Hr({typeName:L.ZodNaN,...B(r)});y.BRAND=Symbol("zod_brand");var En=class extends F{_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}};y.ZodBranded=En;var In=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?_.INVALID:i.status==="dirty"?(t.dirty(),(0,_.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?_.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:L.ZodPipeline})}};y.ZodPipeline=In;var hr=class extends F{_parse(e){let t=this._def.innerType._parse(e),n=s=>((0,_.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,_.isAsync)(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};y.ZodReadonly=hr;hr.create=(r,e)=>new hr({innerType:r,typeName:L.ZodReadonly,...B(e)});function Wa(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function eu(r,e={},t){return r?Et.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Wa(e,n),c=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=Wa(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):Et.create()}y.late={object:_e.lazycreate};var L;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(L||(y.ZodFirstPartyTypeKind=L={}));var Lf=(r,e={message:`Input not instance of ${r.name}`})=>eu(t=>t instanceof r,e);y.instanceof=Lf;var tu=Ct.create;y.string=tu;var ru=Xt.create;y.number=ru;var zf=Hr.create;y.nan=zf;var Uf=Qt.create;y.bigint=Uf;var nu=er.create;y.boolean=nu;var qf=tr.create;y.date=qf;var Bf=Fr.create;y.symbol=Bf;var Ff=rr.create;y.undefined=Ff;var Zf=nr.create;y.null=Zf;var Kf=Et.create;y.any=Kf;var Vf=at.create;y.unknown=Vf;var Hf=Le.create;y.never=Hf;var Gf=Zr.create;y.void=Gf;var Wf=ut.create;y.array=Wf;var Jf=_e.create;y.object=Jf;var Yf=_e.strictCreate;y.strictObject=Yf;var Xf=sr.create;y.union=Xf;var Qf=gs.create;y.discriminatedUnion=Qf;var ep=ir.create;y.intersection=ep;var tp=Ve.create;y.tuple=tp;var rp=ys.create;y.record=rp;var np=Kr.create;y.map=np;var sp=Vr.create;y.set=sp;var ip=_s.create;y.function=ip;var op=or.create;y.lazy=op;var ap=ar.create;y.literal=ap;var up=ur.create;y.enum=up;var cp=cr.create;y.nativeEnum=cp;var lp=It.create;y.promise=lp;var su=ke.create;y.effect=su;y.transformer=su;var dp=$e.create;y.optional=dp;var hp=He.create;y.nullable=hp;var fp=ke.createWithPreprocess;y.preprocess=fp;var pp=In.create;y.pipeline=pp;var mp=()=>tu().optional();y.ostring=mp;var gp=()=>ru().optional();y.onumber=gp;var yp=()=>nu().optional();y.oboolean=yp;y.coerce={string:(r=>Ct.create({...r,coerce:!0})),number:(r=>Xt.create({...r,coerce:!0})),boolean:(r=>er.create({...r,coerce:!0})),bigint:(r=>Qt.create({...r,coerce:!0})),date:(r=>tr.create({...r,coerce:!0}))};y.NEVER=_.INVALID});var Oi=Y(je=>{"use strict";var _p=je&&je.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Gr=je&&je.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&_p(e,r,t)};Object.defineProperty(je,"__esModule",{value:!0});Gr(fs(),je);Gr($i(),je);Gr(Ka(),je);Gr(xn(),je);Gr(iu(),je);Gr(hs(),je)});var uu=Y(ve=>{"use strict";var ou=ve&&ve.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),vp=ve&&ve.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),bp=ve&&ve.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&ou(e,r,t);return vp(e,r),e},wp=ve&&ve.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&ou(e,r,t)};Object.defineProperty(ve,"__esModule",{value:!0});ve.z=void 0;var au=bp(Oi());ve.z=au;wp(Oi(),ve);ve.default=au});var Se=Y(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.ChatLoadResultMsg=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.RuleConfig=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.PROTOCOL_VERSION=void 0;h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditListResultMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditScope=h.AuditSeverity=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.PROMPT_PRESETS=h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=void 0;h.missingAgentCapabilities=kp;h.parseRunnerMsg=Tp;h.parseServerMsg=xp;var u=uu();h.PROTOCOL_VERSION="1.22";h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[]};function kp(r,e){let t=h.REGISTERED_AGENTS.find(n=>n.id===r);return t?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(n=>!t.capabilities[n]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var Sp=r=>r.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>r.includes(e));h.needsInputMarkerIn=Sp;h.RunStatus=u.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=u.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=u.z.enum(["plan_only","implement","respond","deploy"]);h.LabelAddedTrigger=u.z.object({type:u.z.literal("label_added"),label:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-planned"),failedLabel:u.z.string().min(1).default("agent-failed")});h.CommentKeywordTrigger=u.z.object({type:u.z.literal("comment_keyword"),keyword:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-implemented"),failedLabel:u.z.string().min(1).default("agent-failed")});h.StatusChangedTrigger=u.z.object({type:u.z.literal("status_changed"),status:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-deployed"),failedLabel:u.z.string().min(1).default("agent-failed")});h.TriggerConfig=u.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.PlanOnlyAction=u.z.object({type:u.z.literal("plan_only"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(3600).default(900),agent:u.z.string().default(h.DEFAULT_AGENT_ID),model:u.z.string().default("")});h.ImplementAction=u.z.object({type:u.z.literal("implement"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(7200).default(1800),maxTurns:u.z.number().int().positive().max(500).default(120),requireApproval:u.z.boolean().default(!0),branchTemplate:u.z.string().min(1).default("agent/{{issueKey}}").refine(r=>r.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:u.z.string().min(1).default("main"),jiraTransition:u.z.string().optional(),jiraTransitionOnStart:u.z.string().optional(),jiraTransitionOnMerge:u.z.string().optional(),agent:u.z.string().default(h.DEFAULT_AGENT_ID),model:u.z.string().default(""),updateMemory:u.z.boolean().default(!1)});h.RespondAction=u.z.object({type:u.z.literal("respond"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(3600).default(600),agent:u.z.string().default(h.DEFAULT_AGENT_ID),model:u.z.string().default("")});h.DeployStep=u.z.object({name:u.z.string().min(1).max(120),run:u.z.string().min(1).max(4e3),continueOnError:u.z.boolean().default(!1)});h.PromotionMode=u.z.enum(["deploy_only","merge_and_deploy"]);h.EnvironmentConfig=u.z.object({id:u.z.string(),projectId:u.z.string(),name:u.z.string(),rank:u.z.number().int().nonnegative(),auditBeforeDeploy:u.z.enum(["","security","testing"]).default(""),branch:u.z.string().default(""),useDedicatedCheckout:u.z.boolean().default(!1),promotionMode:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:u.z.string().default("agent/{{issueKey}}"),steps:u.z.array(h.DeployStep).default([]),workdir:u.z.string().default(""),timeoutSeconds:u.z.number().int().positive().max(21600).default(1800),requiredSecrets:u.z.array(u.z.string()).default([]),requireApproval:u.z.boolean().default(!1),requireSyncCheck:u.z.boolean().default(!1),previousEnvBranch:u.z.string().optional(),deployFromColumn:u.z.string().default(""),deployToColumn:u.z.string().default("")});h.DeployAction=u.z.object({type:u.z.literal("deploy"),envSelection:u.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:u.z.string().optional(),requireStatus:u.z.string().optional()});h.ActionConfig=u.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=u.z.object({id:u.z.string(),name:u.z.string(),jiraProjectKey:u.z.string(),repoName:u.z.string(),componentRoutes:u.z.array(u.z.object({component:u.z.string().min(1),repoName:u.z.string().min(1)})).default([])});h.RuleConfig=u.z.object({id:u.z.string(),projectId:u.z.string(),name:u.z.string(),enabled:u.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.HelloMsg=u.z.object({type:u.z.literal("hello"),protocolVersion:u.z.string(),runnerVersion:u.z.string(),platform:u.z.string(),justBooted:u.z.boolean().optional()});h.HeartbeatMsg=u.z.object({type:u.z.literal("heartbeat"),ts:u.z.string()});h.RunClaimMsg=u.z.object({type:u.z.literal("run.claim"),requestId:u.z.string(),ruleId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),triggerFingerprint:u.z.string(),dedupKey:u.z.string().optional(),triggeredByAccountId:u.z.string().optional()});h.RunLogMsg=u.z.object({type:u.z.literal("run.log"),runId:u.z.string(),seq:u.z.number().int().nonnegative(),ts:u.z.string(),level:u.z.enum(["info","warn","error","agent"]),message:u.z.string().max(16384)});h.RunStatusMsg=u.z.object({type:u.z.literal("run.status"),runId:u.z.string(),status:h.RunStatus,error:u.z.string().optional(),errorKind:u.z.enum(["guard"]).optional(),costUsd:u.z.number().nonnegative().optional(),inputTokens:u.z.number().int().nonnegative().optional(),outputTokens:u.z.number().int().nonnegative().optional(),resultSummary:u.z.string().max(2e3).optional(),billingMode:u.z.enum(["subscription","api","unknown"]).optional(),model:u.z.string().max(200).optional(),prUrl:u.z.string().optional(),headSha:u.z.string().optional(),deployedRef:u.z.string().optional(),retryAvailable:u.z.boolean().optional()});h.ProjectTestResultMsg=u.z.object({type:u.z.literal("project.test.result"),requestId:u.z.string(),ok:u.z.boolean(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string()}))});h.RuleDiagnoseResultMsg=u.z.object({type:u.z.literal("rule.diagnose.result"),requestId:u.z.string(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string()})),matchedCount:u.z.number().int().nonnegative(),excludedCount:u.z.number().int().nonnegative(),excludedSample:u.z.array(u.z.string()).max(5)});h.DeployClaimMsg=u.z.object({type:u.z.literal("deploy.claim"),requestId:u.z.string(),projectId:u.z.string(),ruleId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),environmentName:u.z.string(),requestedByAccountId:u.z.string().optional(),requestedByDisplayName:u.z.string().default(""),dedupKey:u.z.string(),triggerFingerprint:u.z.string()});h.DeployClaimResultMsg=u.z.object({type:u.z.literal("deploy.claim.result"),requestId:u.z.string(),accepted:u.z.boolean(),runId:u.z.string().optional(),environment:h.EnvironmentConfig.optional(),reason:u.z.string().optional(),code:u.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});h.JiraUsersResultMsg=u.z.object({type:u.z.literal("jira.users.result"),requestId:u.z.string(),ok:u.z.boolean(),users:u.z.array(u.z.object({accountId:u.z.string(),displayName:u.z.string(),email:u.z.string().default(""),active:u.z.boolean().default(!0)})).default([]),error:u.z.string().optional()});h.ChatStreamMsg=u.z.object({type:u.z.literal("chat.stream"),requestId:u.z.string(),seq:u.z.number().int().nonnegative(),text:u.z.string().max(8e3)});h.ChatListMsg=u.z.object({type:u.z.literal("chat.list"),requestId:u.z.string(),projectId:u.z.string()});h.ChatListResultMsg=u.z.object({type:u.z.literal("chat.list.result"),requestId:u.z.string(),sessions:u.z.array(u.z.object({sessionId:u.z.string(),title:u.z.string().default(""),updatedAt:u.z.string().default(""),messageCount:u.z.number().int().nonnegative().default(0)})).default([])});h.ChatLoadMsg=u.z.object({type:u.z.literal("chat.load"),requestId:u.z.string(),sessionId:u.z.string()});h.ChatLoadResultMsg=u.z.object({type:u.z.literal("chat.load.result"),requestId:u.z.string(),ok:u.z.boolean(),projectId:u.z.string().default(""),messages:u.z.array(u.z.object({role:u.z.enum(["user","agent"]),text:u.z.string()})).default([]),error:u.z.string().optional()});h.BoardFetchMsg=u.z.object({type:u.z.literal("board.fetch"),requestId:u.z.string(),projectId:u.z.string()});h.BoardFetchResultMsg=u.z.object({type:u.z.literal("board.fetch.result"),requestId:u.z.string(),ok:u.z.boolean(),browseBaseUrl:u.z.string().default(""),columns:u.z.array(u.z.object({name:u.z.string(),issues:u.z.array(u.z.object({key:u.z.string(),summary:u.z.string(),labels:u.z.array(u.z.string()).default([])})).default([])})).default([]),error:u.z.string().optional()});h.BoardTriggerMsg=u.z.object({type:u.z.literal("board.trigger"),requestId:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),comment:u.z.string().max(2e3).default(""),removeLabel:u.z.string().default(""),requestedBy:u.z.string().default(""),requestedByEmail:u.z.string().default(""),reimplement:u.z.boolean().default(!1)});h.BoardTriggerResultMsg=u.z.object({type:u.z.literal("board.trigger.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional()});h.EpicListMsg=u.z.object({type:u.z.literal("epic.list"),requestId:u.z.string(),projectId:u.z.string(),epicKey:u.z.string().default("")});h.EpicChild=u.z.object({key:u.z.string(),summary:u.z.string(),status:u.z.string(),statusCategory:u.z.string(),labels:u.z.array(u.z.string()).default([])});h.EpicListResultMsg=u.z.object({type:u.z.literal("epic.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),epics:u.z.array(u.z.object({key:u.z.string(),summary:u.z.string(),status:u.z.string()})).default([]),children:u.z.array(h.EpicChild).default([])});h.EpicSuggestMsg=u.z.object({type:u.z.literal("epic.suggest"),requestId:u.z.string(),projectId:u.z.string(),epicKey:u.z.string().min(1),model:u.z.string().default("")});h.EpicSuggestResultMsg=u.z.object({type:u.z.literal("epic.suggest.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),issueKey:u.z.string().default(""),reason:u.z.string().default(""),considered:u.z.number().int().default(0)});h.AuditRole=u.z.enum(["security","testing","architecture"]);h.AuditSeverity=u.z.enum(["critical","high","medium","low","info"]);h.AuditScope=u.z.object({kind:u.z.enum(["repo","ticket","branch"]).default("repo"),ref:u.z.string().default("")});h.AuditFinding=u.z.object({id:u.z.string().min(1),title:u.z.string().min(1),ruleId:u.z.string().max(20).default(""),severity:h.AuditSeverity,area:u.z.string().default(""),evidence:u.z.array(u.z.object({file:u.z.string().min(1),line:u.z.number().int().positive().optional(),note:u.z.string().default("")})).min(1),fix:u.z.string().default("")});h.AuditRecord=u.z.object({id:u.z.string(),role:h.AuditRole,createdAt:u.z.string(),model:u.z.string().default(""),summary:u.z.string().default(""),packNames:u.z.array(u.z.string()).default([]),findings:u.z.array(h.AuditFinding).default([]),costUsd:u.z.number().default(0),review:u.z.object({selected:u.z.array(u.z.string()),updatedAt:u.z.string()}).optional(),verdicts:u.z.record(u.z.object({verdict:u.z.enum(["valid","false-positive","wont-fix"]),note:u.z.string().default(""),by:u.z.string().default(""),at:u.z.string().default("")})).default({}),lessonsWritten:u.z.array(u.z.string()).default([]),ticketed:u.z.record(u.z.string()).default({}),scope:h.AuditScope.default({kind:"repo",ref:""}),testRun:u.z.array(u.z.object({command:u.z.string(),exitCode:u.z.number().int(),durationMs:u.z.number().int().default(0),tail:u.z.string().default("")})).optional()});h.AuditStartMsg=u.z.object({type:u.z.literal("audit.start"),requestId:u.z.string(),projectId:u.z.string(),role:h.AuditRole,model:u.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""})});h.AuditStartResultMsg=u.z.object({type:u.z.literal("audit.start.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditListMsg=u.z.object({type:u.z.literal("audit.list"),requestId:u.z.string(),projectId:u.z.string()});h.AuditListResultMsg=u.z.object({type:u.z.literal("audit.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audits:u.z.array(u.z.object({id:u.z.string(),role:h.AuditRole,createdAt:u.z.string(),findingCount:u.z.number().int(),bySeverity:u.z.record(u.z.number().int()).default({})})).default([])});h.AuditGetMsg=u.z.object({type:u.z.literal("audit.get"),requestId:u.z.string(),projectId:u.z.string(),auditId:u.z.string()});h.AuditGetResultMsg=u.z.object({type:u.z.literal("audit.get.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditReviewMsg=u.z.object({type:u.z.literal("audit.review"),requestId:u.z.string(),projectId:u.z.string(),auditId:u.z.string(),selected:u.z.array(u.z.string()).optional(),ticketed:u.z.array(u.z.object({findingId:u.z.string(),issueKey:u.z.string()})).default([]),verdicts:u.z.array(u.z.object({findingId:u.z.string(),verdict:u.z.enum(["valid","false-positive","wont-fix"]),note:u.z.string().max(2e3).default("")})).default([]),verdictBy:u.z.string().default("")});h.AuditReviewResultMsg=u.z.object({type:u.z.literal("audit.review.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:h.AuditRecord.optional()});h.KnowledgeListMsg=u.z.object({type:u.z.literal("knowledge.list"),requestId:u.z.string(),projectId:u.z.string()});h.KnowledgeFile=u.z.object({role:h.AuditRole,level:u.z.enum(["global","org","project"]),source:u.z.enum(["pack","lessons"]),name:u.z.string(),content:u.z.string(),editable:u.z.boolean().default(!1)});h.KnowledgeListResultMsg=u.z.object({type:u.z.literal("knowledge.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),files:u.z.array(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=u.z.object({type:u.z.literal("knowledge.save"),requestId:u.z.string(),projectId:u.z.string(),role:h.AuditRole,level:u.z.enum(["org","project"]),source:u.z.enum(["pack","lessons"]),name:u.z.string().min(1).max(100),content:u.z.string().max(6e4),append:u.z.boolean().default(!1),by:u.z.string().default("")});h.KnowledgeSaveResultMsg=u.z.object({type:u.z.literal("knowledge.save.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional()});h.TeamCredsMsg=u.z.object({type:u.z.literal("team.creds"),requestId:u.z.string(),emails:u.z.array(u.z.string()).max(200)});h.TeamCredsResultMsg=u.z.object({type:u.z.literal("team.creds.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),githubShared:u.z.boolean().default(!1),sharedGithubLogin:u.z.string().default(""),entries:u.z.array(u.z.object({email:u.z.string(),jira:u.z.enum(["own","runner-account","missing"]),jiraAs:u.z.string().default(""),github:u.z.enum(["own","shared","missing"]),githubAs:u.z.string().default("")})).default([])});h.ChatFile=u.z.object({name:u.z.string().min(1).max(255),contentBase64:u.z.string().min(1).max(6e6)});h.ChatTurnMsg=u.z.object({type:u.z.literal("chat.turn"),requestId:u.z.string(),projectId:u.z.string(),sessionId:u.z.string().optional(),message:u.z.string().min(1).max(2e4),userName:u.z.string().default(""),model:u.z.string().default(""),files:u.z.array(h.ChatFile).max(8).default([])});h.ChatTurnResultMsg=u.z.object({type:u.z.literal("chat.turn.result"),requestId:u.z.string(),ok:u.z.boolean(),sessionId:u.z.string().default(""),reply:u.z.string().default(""),error:u.z.string().optional()});h.ChatCreateTicketMsg=u.z.object({type:u.z.literal("chat.create.ticket"),requestId:u.z.string(),projectId:u.z.string(),summary:u.z.string().min(1).max(250),description:u.z.string().default(""),triggerComment:u.z.string().default(""),requestedBy:u.z.string().default(""),requestedByEmail:u.z.string().default(""),asEpic:u.z.boolean().default(!1),children:u.z.array(u.z.object({summary:u.z.string().min(1),description:u.z.string().default("")})).max(20).default([]),files:u.z.array(h.ChatFile).max(8).default([])});h.ChatCreateTicketResultMsg=u.z.object({type:u.z.literal("chat.create.ticket.result"),requestId:u.z.string(),ok:u.z.boolean(),issueKey:u.z.string().default(""),error:u.z.string().optional(),childKeys:u.z.array(u.z.string()).default([])});h.EnvPreflightMsg=u.z.object({type:u.z.literal("env.preflight"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string().default(""),steps:u.z.array(h.DeployStep).default([]),requiredSecrets:u.z.array(u.z.string()).default([]),workdir:u.z.string().default(""),branch:u.z.string().default("")});h.EnvPreflightResultMsg=u.z.object({type:u.z.literal("env.preflight.result"),requestId:u.z.string(),ok:u.z.boolean(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string().default("")})).default([])});h.DeploySuggestResultMsg=u.z.object({type:u.z.literal("deploy.suggest.result"),requestId:u.z.string(),ok:u.z.boolean(),steps:u.z.array(h.DeployStep).default([]),requiredSecrets:u.z.array(u.z.string()).default([]),notes:u.z.string().default(""),error:u.z.string().optional()});h.SetupStatusMsg=u.z.object({type:u.z.literal("setup.status"),requestId:u.z.string(),repoNames:u.z.array(u.z.string()).max(100).default([])});h.SetupStatusResultMsg=u.z.object({type:u.z.literal("setup.status.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),jiraConfigured:u.z.boolean().default(!1),jiraEmail:u.z.string().default(""),claude:u.z.object({installed:u.z.boolean(),version:u.z.string().default(""),loggedIn:u.z.boolean()}).optional(),githubTokenSet:u.z.boolean().default(!1),githubLogin:u.z.string().default(""),deploysEnabled:u.z.boolean().default(!1),jiraUserCount:u.z.number().int().default(0),repos:u.z.array(u.z.object({repoName:u.z.string(),mapped:u.z.boolean(),pathExists:u.z.boolean().default(!1),isGit:u.z.boolean().default(!1),claudeMd:u.z.boolean().default(!1),deployMd:u.z.boolean().default(!1),testMd:u.z.boolean().default(!1)})).default([])});h.RunnerToServerMsg=u.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg,h.SetupStatusResultMsg]);h.HelloAckMsg=u.z.object({type:u.z.literal("hello.ack"),runnerId:u.z.string(),runnerName:u.z.string(),serverTime:u.z.string()});h.ConfigMsg=u.z.object({type:u.z.literal("config"),projects:u.z.array(h.ProjectConfig),rules:u.z.array(h.RuleConfig),environments:u.z.array(h.EnvironmentConfig).default([]),pollingPaused:u.z.boolean().default(!1)});h.RunClaimResultMsg=u.z.object({type:u.z.literal("run.claim.result"),requestId:u.z.string(),accepted:u.z.boolean(),runId:u.z.string().optional(),reason:u.z.string().optional(),claudeProfile:u.z.string().optional(),actorEmail:u.z.string().optional()});h.ProjectTestMsg=u.z.object({type:u.z.literal("project.test"),requestId:u.z.string(),projectId:u.z.string()});h.RuleDiagnoseMsg=u.z.object({type:u.z.literal("rule.diagnose"),requestId:u.z.string(),ruleId:u.z.string()});h.RunCancelMsg=u.z.object({type:u.z.literal("run.cancel"),runId:u.z.string()});h.RunApprovedMsg=u.z.object({type:u.z.literal("run.approved"),runId:u.z.string(),headSha:u.z.string().optional()});h.RunRejectedMsg=u.z.object({type:u.z.literal("run.rejected"),runId:u.z.string()});h.RunRetryPushMsg=u.z.object({type:u.z.literal("run.retryPush"),runId:u.z.string()});h.DeployStartMsg=u.z.object({type:u.z.literal("deploy.start"),runId:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),environment:h.EnvironmentConfig,requestedBy:u.z.string().default(""),attempt:u.z.number().int().positive().default(1)});h.DeploySuggestMsg=u.z.object({type:u.z.literal("deploy.suggest"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string(),notes:u.z.string().default(""),timeoutSeconds:u.z.number().int().positive().max(1800).default(300)});h.JiraUsersMsg=u.z.object({type:u.z.literal("jira.users"),requestId:u.z.string(),query:u.z.string().default("")});h.ServerToRunnerMsg=u.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.EnvPreflightMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg]);h.EnrollRequest=u.z.object({enrollToken:u.z.string().min(10),name:u.z.string().min(1).max(100),platform:u.z.string(),runnerVersion:u.z.string()});h.EnrollResponse=u.z.object({runnerId:u.z.string(),runnerToken:u.z.string(),controlPlaneWsUrl:u.z.string()});function Tp(r){return h.RunnerToServerMsg.parse(r)}function xp(r){return h.ServerToRunnerMsg.parse(r)}h.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository \u2014 do not attempt to modify anything.
|
|
24
24
|
|
|
25
25
|
Ticket {{issueKey}}: {{summary}}
|
|
26
26
|
|
|
@@ -180,6 +180,7 @@ Reply with a single fenced \`\`\`json block and nothing else, in this shape:
|
|
|
180
180
|
Output rules: emit the fenced block and nothing else. Use exactly the key names above. Keep each "name" under 100 characters; explanations go in "notes".
|
|
181
181
|
|
|
182
182
|
Rules for the steps:
|
|
183
|
+
- The runner executes every step ON the machine it is installed on. If the document wraps commands in ssh, check the machine facts above first: when the paths/services the document deploys actually EXIST on this machine, the runner is already sitting on the deploy target \u2014 emit plain local commands WITHOUT the ssh wrapper (and no SSH secrets), and explain why in "notes". Keep the ssh wrapper only when the target is genuinely a different machine.
|
|
183
184
|
- Translate ONLY what the document says. Do NOT invent commands, hosts, paths or tooling the document does not mention \u2014 if the document is missing something a deploy obviously needs, say so in "notes" instead of guessing.
|
|
184
185
|
- If the document describes several environments, extract the "{{envName}}" parts; if it doesn't distinguish, say so in "notes".
|
|
185
186
|
- Each "run" is one bash command line, executed in the repo checkout on the machine the runner is installed on.
|
|
@@ -211,54 +212,54 @@ Rules for the steps:
|
|
|
211
212
|
- Reference secrets as environment variables ($DEPLOY_HOST), never literal values, and list every variable you use in "requiredSecrets".
|
|
212
213
|
- Prefer commands that are safe to re-run; a deploy may be retried.
|
|
213
214
|
- Order matters: install, build, test (if cheap), then release.
|
|
214
|
-
- If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var
|
|
215
|
-
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(re.default.isAbsolute(i)){e.refused.push(`${i} \u2014 absolute paths are not allowed`);continue}let o=re.default.resolve(n,i);if(o!==n&&!o.startsWith(n+re.default.sep)){e.refused.push(`${i} \u2014 escapes the worktree`);continue}let a=re.default.relative(n,o).split(re.default.sep).join("/");if(a===
|
|
216
|
-
`).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=
|
|
215
|
+
- If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var bu={};Yn(bu,{DELETE_MANIFEST_FILE:()=>Wr,MAX_CHANGED_FILES:()=>bs,MAX_CHANGED_LINES:()=>ws,applyDeleteManifest:()=>Ni,branchForIssue:()=>Fi,branchSha:()=>Ts,branchesDiffer:()=>Hi,checkDiffSafety:()=>Ui,commitAll:()=>Ss,deleteStaleBranch:()=>Li,diffAgainstDefault:()=>xs,envCheckoutPath:()=>vu,envCheckoutsRoot:()=>_u,fetchBase:()=>Jr,headSha:()=>Rn,mergeTicketBranch:()=>Ki,originUrl:()=>pr,parseOwnerRepo:()=>mr,prepareEnvCheckout:()=>Zi,pruneWorktrees:()=>Bi,pushBranch:()=>qi,pushEnvBranch:()=>Vi,pushWipBranch:()=>Mi,removeWorktree:()=>Yr,statusSnapshot:()=>Di,worktreeAdd:()=>zi,worktreeFingerprint:()=>ks,worktreesRoot:()=>An});async function Z(r,e,t={}){try{let{stdout:n}=await pu("git",["-C",r,...e],{timeout:t.timeoutMs??12e4,maxBuffer:16777216,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return n}catch(n){let s=n;throw new Error(`git ${e[0]} failed: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Ni(r){let e={deleted:[],refused:[]},t=re.default.join(r,Wr);if(!le.default.existsSync(t))return e;let n=re.default.resolve(r),s=le.default.readFileSync(t,"utf8").split(`
|
|
216
|
+
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(re.default.isAbsolute(i)){e.refused.push(`${i} \u2014 absolute paths are not allowed`);continue}let o=re.default.resolve(n,i);if(o!==n&&!o.startsWith(n+re.default.sep)){e.refused.push(`${i} \u2014 escapes the worktree`);continue}let a=re.default.relative(n,o).split(re.default.sep).join("/");if(a===Wr)continue;if(yu.some(l=>l.test(a))){e.refused.push(`${i} \u2014 protected path (CI/hook files are never touched)`);continue}let c;try{c=le.default.lstatSync(o)}catch{e.refused.push(`${i} \u2014 no such file`);continue}if(c.isDirectory()){e.refused.push(`${i} \u2014 is a directory (list the files inside it instead)`);continue}try{le.default.rmSync(o),e.deleted.push(a)}catch(l){e.refused.push(`${i} \u2014 ${l instanceof Error?l.message:"delete failed"}`)}}return le.default.rmSync(t,{force:!0}),e}async function Mi(r,e){await Z(r,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function ks(r){let e=await Z(r,["status","--porcelain"]),t=await Z(r,["diff","--numstat"]),n=e.split(`
|
|
217
|
+
`).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=le.default.statSync(re.default.join(r,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
|
|
217
218
|
`);return`${e}
|
|
218
219
|
--
|
|
219
220
|
${t}
|
|
220
221
|
--
|
|
221
|
-
${n}`}async function
|
|
222
|
+
${n}`}async function Di(r){let e=(await Z(r,["rev-parse","--abbrev-ref","HEAD"])).trim(),t=(await Z(r,["log","--oneline","-1"])).trim(),n=(await Z(r,["status","--porcelain"])).trim(),s=n?n.split(`
|
|
222
223
|
`):[],i=s.slice(0,15).join(`
|
|
223
224
|
`),o=s.length>15?`
|
|
224
225
|
(\u2026 ${s.length-15} more)`:"";return`branch ${e} @ ${t}
|
|
225
226
|
working tree: ${s.length?`
|
|
226
|
-
${i}${o}`:"clean"}`}function
|
|
227
|
-
`))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(n)&&await Z(r,["worktree","remove","--force",s]);await Z(r,["worktree","prune"])}catch{}try{await Z(r,["branch","-D",e])}catch{}}async function
|
|
228
|
-
`).filter(Boolean),s=n.filter(l=>
|
|
229
|
-
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function ks(r,e,t=6e4){let s=(await Z(r,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await Z(r,["diff","--stat",`${s}...${e}`]),o=await Z(r,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function gc(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(ue.default.existsSync(re.default.join(hr.default.homedir(),".cache","ticketpilot"))?re.default.join(hr.default.homedir(),".cache","ticketpilot"):re.default.join(hr.default.homedir(),".cache","allwright"));return re.default.join(r,"env-checkouts")}function uc(r){return r.replace(/[^\w.-]+/g,"_")}function yc(r,e){return re.default.join(gc(),uc(r),uc(e))}async function qi(r){let e=yc(r.repoName,r.envName);return await Z(r.repoPath,["fetch","origin",r.branch],{timeoutMs:3e5}),ue.default.existsSync(re.default.join(e,".git"))?await Z(e,["fetch","origin",r.branch],{timeoutMs:3e5}):(ue.default.rmSync(e,{recursive:!0,force:!0}),ue.default.mkdirSync(re.default.dirname(e),{recursive:!0,mode:448}),await Z(r.repoPath,["worktree","prune"]).catch(()=>{}),await Z(r.repoPath,["worktree","add","--detach",e,`origin/${r.branch}`])),r.attached?await Z(e,["checkout","-B",r.branch,`origin/${r.branch}`]):await Z(e,["checkout","--force","--detach",`origin/${r.branch}`]),e}async function Bi(r,e,t){try{await Z(r,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin \u2014 nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await Z(r,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await Z(r,["-c",`user.name=${fc}`,"-c",`user.email=${pc}`,"merge","--no-ff","-m",t,`origin/${e}`]),{ok:!0}}catch(n){return await Z(r,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch \u2014 ${n instanceof Error?n.message:n}. Resolve it manually and deploy again.`}}}async function Fi(r,e){try{await Z(r,["push","origin",e],{timeoutMs:3e5})}catch(t){throw new Error(`could not push "${e}" \u2014 ${t instanceof Error?t.message:t}. Someone may have pushed to it since this deploy started; retry.`)}}async function Zi(r,e,t){try{return await hc("git",["-C",r,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(n){let s=n;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function fr(r){return(await Z(r,["config","--get","remote.origin.url"])).trim()}function pr(r){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(r)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(r)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(r);return e?{owner:e[1],repo:e[2]}:null}var ue,hr,re,lc,dc,hc,fc,pc,ys,_s,mc,Hr,mr=ra(()=>{"use strict";ue=$(require("node:fs"),1),hr=$(require("node:os"),1),re=$(require("node:path"),1),lc=require("node:child_process"),dc=require("node:util"),hc=(0,dc.promisify)(lc.execFile),fc="Allwright Agent",pc="agent@ticketpilot.local",ys=200,_s=2e4,mc=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Hr=".ticketpilot-delete"});var Qr={};ri(Qr,{GitHubClient:()=>Oe});var Op,Oe,ut=ra(()=>{"use strict";Op=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Oe=class{constructor(e){this.token=e}token;async request(e,t,n){let s=await fetch(`${Op}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...n!==void 0?{"Content-Type":"application/json"}:{}},body:n===void 0?void 0:JSON.stringify(n)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) \u2014 expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let a=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${t} -> ${s.status}: ${a}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,t,n){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,n);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${n.head}`)}&state=open`);if(o?.length){let a=o[0];return{number:a.number,url:a.html_url,state:a.state,merged:a.merged??!1,headSha:a.head.sha,mergeableState:null}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,headSha:i.head.sha,mergeableState:null}}async getReviews(e,t,n){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,n){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async closePullRequest(e,t,n){await this.request("PATCH",`/repos/${e}/${t}/pulls/${n}`,{state:"closed"})}async deleteBranch(e,t,n){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(n)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var ht=Y((Cv,el)=>{"use strict";var Xu=["nodebuffer","arraybuffer","fragments"],Qu=typeof Blob<"u";Qu&&Xu.push("blob");el.exports={BINARY_TYPES:Xu,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Qu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var zn=Y((Ev,zs)=>{"use strict";var{EMPTY_BUFFER:vm}=ht(),To=Buffer[Symbol.species];function bm(r,e){if(r.length===0)return vm;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new To(t.buffer,t.byteOffset,n):t}function tl(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function rl(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function wm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function xo(r){if(xo.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new To(r):ArrayBuffer.isView(r)?e=new To(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),xo.readOnly=!1),e}zs.exports={concat:bm,mask:tl,toArrayBuffer:wm,toBuffer:xo,unmask:rl};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");zs.exports.mask=function(e,t,n,s,i){i<48?tl(e,t,n,s,i):r.mask(e,t,n,s,i)},zs.exports.unmask=function(e,t){e.length<32?rl(e,t):r.unmask(e,t)}}catch{}});var il=Y((Iv,sl)=>{"use strict";var nl=Symbol("kDone"),Co=Symbol("kRun"),Eo=class{constructor(e){this[nl]=()=>{this.pending--,this[Co]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Co]()}[Co](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[nl])}}};sl.exports=Eo});var an=Y((Av,ul)=>{"use strict";var Un=require("zlib"),ol=zn(),km=il(),{kStatusCode:al}=ht(),Sm=Buffer[Symbol.species],Tm=Buffer.from([0,0,255,255]),qs=Symbol("permessage-deflate"),ft=Symbol("total-length"),sn=Symbol("callback"),$t=Symbol("buffers"),on=Symbol("error"),Us,Io=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Us){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Us=new km(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[sn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){Us.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Us.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Un.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Un.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[qs]=this,this._inflate[ft]=0,this._inflate[$t]=[],this._inflate.on("error",Cm),this._inflate.on("data",cl)}this._inflate[sn]=n,this._inflate.write(e),t&&this._inflate.write(Tm),this._inflate.flush(()=>{let i=this._inflate[on];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=ol.concat(this._inflate[$t],this._inflate[ft]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ft]=0,this._inflate[$t]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Un.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Un.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ft]=0,this._deflate[$t]=[],this._deflate.on("data",xm)}this._deflate[sn]=n,this._deflate.write(e),this._deflate.flush(Un.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ol.concat(this._deflate[$t],this._deflate[ft]);t&&(i=new Sm(i.buffer,i.byteOffset,i.length-4)),this._deflate[sn]=null,this._deflate[ft]=0,this._deflate[$t]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};ul.exports=Io;function xm(r){this[$t].push(r),this[ft]+=r.length}function cl(r){if(this[ft]+=r.length,this[qs]._maxPayload<1||this[ft]<=this[qs]._maxPayload){this[$t].push(r);return}this[on]=new RangeError("Max payload size exceeded"),this[on].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[on][al]=1009,this.removeListener("data",cl),this.reset()}function Cm(r){if(this[qs]._inflate=null,this[on]){this[sn](this[on]);return}r[al]=1007,this[sn](r)}});var cn=Y((Rv,Bs)=>{"use strict";var{isUtf8:ll}=require("buffer"),{hasBlob:Em}=ht(),Im=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Am(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Ao(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Rm(r){return Em&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Bs.exports={isBlob:Rm,isValidStatusCode:Am,isValidUTF8:Ao,tokenChars:Im};if(ll)Bs.exports.isValidUTF8=function(r){return r.length<24?Ao(r):ll(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Bs.exports.isValidUTF8=function(e){return e.length<32?Ao(e):r(e)}}catch{}});var Oo=Y(($v,yl)=>{"use strict";var{Writable:$m}=require("stream"),dl=an(),{BINARY_TYPES:Pm,EMPTY_BUFFER:hl,kStatusCode:jm,kWebSocket:Om}=ht(),{concat:Ro,toArrayBuffer:Nm,unmask:Mm}=zn(),{isValidStatusCode:Dm,isValidUTF8:fl}=cn(),Fs=Buffer[Symbol.species],Ne=0,pl=1,ml=2,gl=3,$o=4,Po=5,Zs=6,jo=class extends $m{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Pm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Om]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ne}_write(e,t,n){if(this._opcode===8&&this._state==Ne)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Fs(n.buffer,n.byteOffset+e,n.length-e),new Fs(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Fs(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Ne:this.getInfo(e);break;case pl:this.getPayloadLength16(e);break;case ml:this.getPayloadLength64(e);break;case gl:this.getMask();break;case $o:this.getData(e);break;case Po:case Zs:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[dl.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=pl:this._payloadLength===127?this._state=ml:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=gl:this._state=$o}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=$o}getData(e){let t=hl;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Mm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this._compressed){this._state=Po,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[dl.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===Ne&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ne;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Ro(n,t):this._binaryType==="arraybuffer"?s=Nm(Ro(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Ne):(this._state=Zs,setImmediate(()=>{this.emit("message",s,!0),this._state=Ne,this.startLoop(e)}))}else{let s=Ro(n,t);if(!this._skipUTF8Validation&&!fl(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Po||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Ne):(this._state=Zs,setImmediate(()=>{this.emit("message",s,!1),this._state=Ne,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,hl),this.end();else{let n=e.readUInt16BE(0);if(!Dm(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Fs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!fl(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=Ne;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne):(this._state=Zs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[jm]=s,o}};yl.exports=jo});var Do=Y((jv,bl)=>{"use strict";var{Duplex:Pv}=require("stream"),{randomFillSync:Lm}=require("crypto"),{types:{isUint8Array:zm}}=require("util"),_l=an(),{EMPTY_BUFFER:Um,kWebSocket:qm,NOOP:Bm}=ht(),{isBlob:un,isValidStatusCode:Fm}=cn(),{mask:vl,toBuffer:Sr}=zn(),Me=Symbol("kByteLength"),Zm=Buffer.alloc(4),Ks=8*1024,Tr,ln=Ks,Be=0,Km=1,Vm=2,No=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Be,this.onerror=Bm,this[qm]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||Zm,t.generateMask?t.generateMask(n):(ln===Ks&&(Tr===void 0&&(Tr=Buffer.alloc(Ks)),Lm(Tr,0,Ks),ln=0),n[0]=Tr[ln++],n[1]=Tr[ln++],n[2]=Tr[ln++],n[3]=Tr[ln++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Me]!==void 0?a=t[Me]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let u=a;a>=65536?(i+=8,u=127):a>125&&(i+=2,u=126);let l=Buffer.allocUnsafe(s?a+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=u,u===126?l.writeUInt16BE(a,2):u===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),t.mask?(l[1]|=128,l[i-4]=n[0],l[i-3]=n[1],l[i-2]=n[2],l[i-1]=n[3],o?[l,e]:s?(vl(e,n,l,i,a),[l]):(vl(e,n,e,0,a),[l,e])):[l,e]}close(e,t,n,s){let i;if(e===void 0)i=Um;else{if(typeof e!="number"||!Fm(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(zm(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Me]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Be?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):un(e)?(s=e.size,i=!1):(e=Sr(e),s=e.length,i=Sr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};un(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):un(e)?(s=e.size,i=!1):(e=Sr(e),s=e.length,i=Sr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};un(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[_l.extensionName],i=t.binary?2:1,o=t.compress,a,u;typeof e=="string"?(a=Buffer.byteLength(e),u=!1):un(e)?(a=e.size,u=!1):(e=Sr(e),a=e.length,u=Sr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[Me]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:o};un(e)?this._state!==Be?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==Be?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[Me],this._state=Vm,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Mo,this,a,s);return}this._bufferedBytes-=n[Me];let o=Sr(i);t?this.dispatch(o,t,n,s):(this._state=Be,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(Hm,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[_l.extensionName];this._bufferedBytes+=n[Me],this._state=Km,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Mo(this,u,s);return}this._bufferedBytes-=n[Me],this._state=Be,n.readOnly=!1,this.sendFrame(r.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===Be&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};bl.exports=No;function Mo(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function Hm(r,e,t){Mo(r,e,t),r.onerror(e)}});var Al=Y((Ov,Il)=>{"use strict";var{kForOnEventAttribute:qn,kListener:Lo}=ht(),wl=Symbol("kCode"),kl=Symbol("kData"),Sl=Symbol("kError"),Tl=Symbol("kMessage"),xl=Symbol("kReason"),dn=Symbol("kTarget"),Cl=Symbol("kType"),El=Symbol("kWasClean"),pt=class{constructor(e){this[dn]=null,this[Cl]=e}get target(){return this[dn]}get type(){return this[Cl]}};Object.defineProperty(pt.prototype,"target",{enumerable:!0});Object.defineProperty(pt.prototype,"type",{enumerable:!0});var xr=class extends pt{constructor(e,t={}){super(e),this[wl]=t.code===void 0?0:t.code,this[xl]=t.reason===void 0?"":t.reason,this[El]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[wl]}get reason(){return this[xl]}get wasClean(){return this[El]}};Object.defineProperty(xr.prototype,"code",{enumerable:!0});Object.defineProperty(xr.prototype,"reason",{enumerable:!0});Object.defineProperty(xr.prototype,"wasClean",{enumerable:!0});var hn=class extends pt{constructor(e,t={}){super(e),this[Sl]=t.error===void 0?null:t.error,this[Tl]=t.message===void 0?"":t.message}get error(){return this[Sl]}get message(){return this[Tl]}};Object.defineProperty(hn.prototype,"error",{enumerable:!0});Object.defineProperty(hn.prototype,"message",{enumerable:!0});var Bn=class extends pt{constructor(e,t={}){super(e),this[kl]=t.data===void 0?null:t.data}get data(){return this[kl]}};Object.defineProperty(Bn.prototype,"data",{enumerable:!0});var Gm={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[qn]&&s[Lo]===e&&!s[qn])return;let n;if(r==="message")n=function(i,o){let a=new Bn("message",{data:o?i:i.toString()});a[dn]=this,Vs(e,this,a)};else if(r==="close")n=function(i,o){let a=new xr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[dn]=this,Vs(e,this,a)};else if(r==="error")n=function(i){let o=new hn("error",{error:i,message:i.message});o[dn]=this,Vs(e,this,o)};else if(r==="open")n=function(){let i=new pt("open");i[dn]=this,Vs(e,this,i)};else return;n[qn]=!!t[qn],n[Lo]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[Lo]===e&&!t[qn]){this.removeListener(r,t);break}}};Il.exports={CloseEvent:xr,ErrorEvent:hn,Event:pt,EventTarget:Gm,MessageEvent:Bn};function Vs(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Hs=Y((Nv,Rl)=>{"use strict";var{tokenChars:Fn}=cn();function Ye(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Wm(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,a,u=-1,l=-1,d=-1,p=0;for(;p<r.length;p++)if(l=r.charCodeAt(p),o===void 0)if(d===-1&&Fn[l]===1)u===-1&&(u=p);else if(p!==0&&(l===32||l===9))d===-1&&u!==-1&&(d=p);else if(l===59||l===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let S=r.slice(u,d);l===44?(Ye(e,S,t),t=Object.create(null)):o=S,u=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(d===-1&&Fn[l]===1)u===-1&&(u=p);else if(l===32||l===9)d===-1&&u!==-1&&(d=p);else if(l===59||l===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p),Ye(t,r.slice(u,d),!0),l===44&&(Ye(e,o,t),t=Object.create(null),o=void 0),u=d=-1}else if(l===61&&u!==-1&&d===-1)a=r.slice(u,p),u=d=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Fn[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:n||(n=!0),s=!1}else if(i)if(Fn[l]===1)u===-1&&(u=p);else if(l===34&&u!==-1)i=!1,d=p;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&r.charCodeAt(p-1)===61)i=!0;else if(d===-1&&Fn[l]===1)u===-1&&(u=p);else if(u!==-1&&(l===32||l===9))d===-1&&(d=p);else if(l===59||l===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let S=r.slice(u,d);n&&(S=S.replace(/\\/g,""),n=!1),Ye(t,a,S),l===44&&(Ye(e,o,t),t=Object.create(null),o=void 0),a=void 0,u=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(u===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=p);let v=r.slice(u,d);return o===void 0?Ye(e,v,t):(a===void 0?Ye(t,v,!0):n?Ye(t,a,v.replace(/\\/g,"")):Ye(t,a,v),Ye(e,o,t)),e}function Jm(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Rl.exports={format:Jm,parse:Wm}});var Ys=Y((Lv,Bl)=>{"use strict";var Ym=require("events"),Xm=require("https"),Qm=require("http"),jl=require("net"),eg=require("tls"),{randomBytes:tg,createHash:rg}=require("crypto"),{Duplex:Mv,Readable:Dv}=require("stream"),{URL:zo}=require("url"),Pt=an(),ng=Oo(),sg=Do(),{isBlob:ig}=cn(),{BINARY_TYPES:$l,CLOSE_TIMEOUT:og,EMPTY_BUFFER:Gs,GUID:ag,kForOnEventAttribute:Uo,kListener:cg,kStatusCode:ug,kWebSocket:oe,NOOP:Ol}=ht(),{EventTarget:{addEventListener:lg,removeEventListener:dg}}=Al(),{format:hg,parse:fg}=Hs(),{toBuffer:pg}=zn(),Nl=Symbol("kAborted"),qo=[8,13],mt=["CONNECTING","OPEN","CLOSING","CLOSED"],mg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ne=class r extends Ym{constructor(e,t,n){super(),this._binaryType=$l[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Gs,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Ml(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){$l.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new ng({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new sg(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[oe]=this,i[oe]=this,e[oe]=this,s.on("conclude",_g),s.on("drain",vg),s.on("error",bg),s.on("message",wg),s.on("ping",kg),s.on("pong",Sg),i.onerror=Tg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",zl),e.on("data",Js),e.on("end",Ul),e.on("error",ql),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Pt.extensionName]&&this._extensions[Pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ll(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Bo(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Gs,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Bo(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Gs,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Bo(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Pt.extensionName]||(s.compress=!1),this._sender.send(e||Gs,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(ne,"CONNECTING",{enumerable:!0,value:mt.indexOf("CONNECTING")});Object.defineProperty(ne.prototype,"CONNECTING",{enumerable:!0,value:mt.indexOf("CONNECTING")});Object.defineProperty(ne,"OPEN",{enumerable:!0,value:mt.indexOf("OPEN")});Object.defineProperty(ne.prototype,"OPEN",{enumerable:!0,value:mt.indexOf("OPEN")});Object.defineProperty(ne,"CLOSING",{enumerable:!0,value:mt.indexOf("CLOSING")});Object.defineProperty(ne.prototype,"CLOSING",{enumerable:!0,value:mt.indexOf("CLOSING")});Object.defineProperty(ne,"CLOSED",{enumerable:!0,value:mt.indexOf("CLOSED")});Object.defineProperty(ne.prototype,"CLOSED",{enumerable:!0,value:mt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(ne.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(ne.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Uo])return e[cg];return null},set(e){for(let t of this.listeners(r))if(t[Uo]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Uo]:!0})}})});ne.prototype.addEventListener=lg;ne.prototype.removeEventListener=dg;Bl.exports=ne;function Ml(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:og,protocolVersion:qo[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!qo.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${qo.join(", ")})`);let i;if(e instanceof zo)i=e;else try{i=new zo(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!o&&!a?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?u="The URL's pathname is empty":i.hash&&(u="The URL contains a fragment identifier"),u){let w=new SyntaxError(u);if(r._redirects===0)throw w;Ws(r,w);return}let l=o?443:80,d=tg(16).toString("base64"),p=o?Xm.request:Qm.request,v=new Set,S;if(s.createConnection=s.createConnection||(o?yg:gg),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(S=new Pt({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=hg({[Pt.extensionName]:S.offer()})),t.length){for(let w of t){if(typeof w!="string"||!mg.test(w)||v.has(w))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(w)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let w=s.path.split(":");s.socketPath=w[0],s.path=w[1]}let x;if(s.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?s.socketPath:i.host;let w=n&&n.headers;if(n={...n,headers:{}},w)for(let[j,U]of Object.entries(w))n.headers[j.toLowerCase()]=U}else if(r.listenerCount("redirect")===0){let w=a?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!w||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,w||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),x=r._req=p(s),r._redirects&&r.emit("redirect",r.url,x)}else x=r._req=p(s);s.timeout&&x.on("timeout",()=>{xe(r,x,"Opening handshake has timed out")}),x.on("error",w=>{x===null||x[Nl]||(x=r._req=null,Ws(r,w))}),x.on("response",w=>{let j=w.headers.location,U=w.statusCode;if(j&&s.followRedirects&&U>=300&&U<400){if(++r._redirects>s.maxRedirects){xe(r,x,"Maximum redirects exceeded");return}x.abort();let f;try{f=new zo(j,e)}catch{let b=new SyntaxError(`Invalid URL: ${j}`);Ws(r,b);return}Ml(r,f,t,n)}else r.emit("unexpected-response",x,w)||xe(r,x,`Unexpected server response: ${w.statusCode}`)}),x.on("upgrade",(w,j,U)=>{if(r.emit("upgrade",w),r.readyState!==ne.CONNECTING)return;x=r._req=null;let f=w.headers.upgrade;if(f===void 0||f.toLowerCase()!=="websocket"){xe(r,j,"Invalid Upgrade header");return}let g=rg("sha1").update(d+ag).digest("base64");if(w.headers["sec-websocket-accept"]!==g){xe(r,j,"Invalid Sec-WebSocket-Accept header");return}let b=w.headers["sec-websocket-protocol"],I;if(b!==void 0?v.size?v.has(b)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":v.size&&(I="Server sent no subprotocol"),I){xe(r,j,I);return}b&&(r._protocol=b);let N=w.headers["sec-websocket-extensions"];if(N!==void 0){if(!S){xe(r,j,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let V;try{V=fg(N)}catch{xe(r,j,"Invalid Sec-WebSocket-Extensions header");return}let W=Object.keys(V);if(W.length!==1||W[0]!==Pt.extensionName){xe(r,j,"Server indicated an extension that was not requested");return}try{S.accept(V[Pt.extensionName])}catch{xe(r,j,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Pt.extensionName]=S}r.setSocket(j,U,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(x,r):x.end()}function Ws(r,e){r._readyState=ne.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function gg(r){return r.path=r.socketPath,jl.connect(r)}function yg(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=jl.isIP(r.host)?"":r.host),eg.connect(r)}function xe(r,e,t){r._readyState=ne.CLOSING;let n=new Error(t);Error.captureStackTrace(n,xe),e.setHeader?(e[Nl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ws,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Bo(r,e,t){if(e){let n=ig(e)?e.size:pg(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${mt[r.readyState]})`);process.nextTick(t,n)}}function _g(r,e){let t=this[oe];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[oe]!==void 0&&(t._socket.removeListener("data",Js),process.nextTick(Dl,t._socket),r===1005?t.close():t.close(r,e))}function vg(){let r=this[oe];r.isPaused||r._socket.resume()}function bg(r){let e=this[oe];e._socket[oe]!==void 0&&(e._socket.removeListener("data",Js),process.nextTick(Dl,e._socket),e.close(r[ug])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Pl(){this[oe].emitClose()}function wg(r,e){this[oe].emit("message",r,e)}function kg(r){let e=this[oe];e._autoPong&&e.pong(r,!this._isServer,Ol),e.emit("ping",r)}function Sg(r){this[oe].emit("pong",r)}function Dl(r){r.resume()}function Tg(r){let e=this[oe];e.readyState!==ne.CLOSED&&(e.readyState===ne.OPEN&&(e._readyState=ne.CLOSING,Ll(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Ll(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function zl(){let r=this[oe];if(this.removeListener("close",zl),this.removeListener("data",Js),this.removeListener("end",Ul),r._readyState=ne.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[oe]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Pl),r._receiver.on("finish",Pl))}function Js(r){this[oe]._receiver.write(r)||this.pause()}function Ul(){let r=this[oe];r._readyState=ne.CLOSING,r._receiver.end(),this.end()}function ql(){let r=this[oe];this.removeListener("error",ql),this.on("error",Ol),r&&(r._readyState=ne.CLOSING,this.destroy())}});var Vl=Y((Uv,Kl)=>{"use strict";var zv=Ys(),{Duplex:xg}=require("stream");function Fl(r){r.emit("close")}function Cg(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Zl(r){this.removeListener("error",Zl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Eg(r,e){let t=!0,n=new xg({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(Fl,n);return}let o=!1;r.once("error",function(u){o=!0,i(u)}),r.once("close",function(){o||i(s),process.nextTick(Fl,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Cg),n.on("error",Zl),n}Kl.exports=Eg});var Fo=Y((qv,Hl)=>{"use strict";var{tokenChars:Ig}=cn();function Ag(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&Ig[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=r.slice(t,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Hl.exports={parse:Ag}});var ed=Y((Fv,Ql)=>{"use strict";var Rg=require("events"),Xs=require("http"),{Duplex:Bv}=require("stream"),{createHash:$g}=require("crypto"),Gl=Hs(),Cr=an(),Pg=Fo(),jg=Ys(),{CLOSE_TIMEOUT:Og,GUID:Ng,kWebSocket:Mg}=ht(),Dg=/^[+/0-9A-Za-z]{22}==$/,Wl=0,Jl=1,Xl=2,Zo=class extends Rg{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Og,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:jg,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Xs.createServer((n,s)=>{let i=Xs.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Lg(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Wl}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Xl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Zn,this);return}if(e&&this.once("close",e),this._state!==Jl)if(this._state=Jl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Zn,this):process.nextTick(Zn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Zn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Yl);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Er(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Er(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Dg.test(i)){Er(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Er(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Kn(t,400);return}let u=e.headers["sec-websocket-protocol"],l=new Set;if(u!==void 0)try{l=Pg.parse(u)}catch{Er(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&d!==void 0){let v=new Cr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let S=Gl.parse(d);S[Cr.extensionName]&&(v.accept(S[Cr.extensionName]),p[Cr.extensionName]=v)}catch{Er(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(S,x,w,j)=>{if(!S)return Kn(t,x||401,w,j);this.completeUpgrade(p,i,l,e,t,n,s)});return}if(!this.options.verifyClient(v))return Kn(t,401)}this.completeUpgrade(p,i,l,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Mg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Wl)return Kn(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${$g("sha1").update(t+Ng).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),d._protocol=p)}if(e[Cr.extensionName]){let p=e[Cr.extensionName].params,v=Gl.format({[Cr.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${v}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
|
|
227
|
+
${i}${o}`:"clean"}`}function An(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(le.default.existsSync(re.default.join(fr.default.homedir(),".cache","ticketpilot"))?re.default.join(fr.default.homedir(),".cache","ticketpilot"):re.default.join(fr.default.homedir(),".cache","allwright"));return re.default.join(r,"worktrees")}async function Jr(r,e){try{await Z(r,["fetch","origin",e])}catch(t){throw new Error(`could not fetch base branch "${e}" from origin \u2014 check the rule's base branch and that this machine can reach the remote (${t instanceof Error?t.message:t})`)}}async function Li(r,e){try{let t=await Z(r,["worktree","list","--porcelain"]),n=An(),s=null;for(let i of t.split(`
|
|
228
|
+
`))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(n)&&await Z(r,["worktree","remove","--force",s]);await Z(r,["worktree","prune"])}catch{}try{await Z(r,["branch","-D",e])}catch{}}async function zi(r,e,t,n){le.default.mkdirSync(re.default.dirname(e),{recursive:!0,mode:448}),await Z(r,["worktree","add","-b",t,e,`origin/${n}`])}async function Ss(r,e){if(await Z(r,["add","-A"]),!(await Z(r,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes \u2014 nothing to commit");await Z(r,["-c",`user.name=${mu}`,"-c",`user.email=${gu}`,"commit","-m",e])}async function Ui(r,e){let n=(await Z(r,["diff","--name-only",`origin/${e}...HEAD`])).split(`
|
|
229
|
+
`).filter(Boolean),s=n.filter(l=>yu.some(d=>d.test(l))),i=await Z(r,["diff","--shortstat",`origin/${e}...HEAD`]),o=Number(/(\d+) insertion/.exec(i)?.[1]??0),a=Number(/(\d+) deletion/.exec(i)?.[1]??0);return{ok:s.length===0&&n.length<=bs&&o+a<=ws,files:n.length,insertions:o,deletions:a,forbidden:s}}async function qi(r,e){await Z(r,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>Z(r,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await Z(r,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function Rn(r){return(await Z(r,["rev-parse","HEAD"])).trim()}async function Ts(r,e){try{return(await Z(r,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function Yr(r,e){try{await Z(r,["worktree","remove","--force",e])}catch{le.default.rmSync(e,{recursive:!0,force:!0})}}async function Bi(r,e=[]){let t=new Set(e.map(s=>re.default.basename(re.default.resolve(s))).filter(s=>s.length>0)),n=An();if(le.default.existsSync(n))for(let s of le.default.readdirSync(n))t.has(s)||le.default.rmSync(re.default.join(n,s),{recursive:!0,force:!0});for(let s of r)try{await Z(s,["worktree","prune"])}catch{}}async function Fi(r,e){return await Z(r,["fetch","origin","--prune"]).catch(()=>{}),(await Z(r,["branch","-r","--list",`*${e}*`])).split(`
|
|
230
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function xs(r,e,t=6e4){let s=(await Z(r,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await Z(r,["diff","--stat",`${s}...${e}`]),o=await Z(r,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function _u(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(le.default.existsSync(re.default.join(fr.default.homedir(),".cache","ticketpilot"))?re.default.join(fr.default.homedir(),".cache","ticketpilot"):re.default.join(fr.default.homedir(),".cache","allwright"));return re.default.join(r,"env-checkouts")}function du(r){return r.replace(/[^\w.-]+/g,"_")}function vu(r,e){return re.default.join(_u(),du(r),du(e))}async function Zi(r){let e=vu(r.repoName,r.envName);return await Z(r.repoPath,["fetch","origin",r.branch],{timeoutMs:3e5}),le.default.existsSync(re.default.join(e,".git"))?await Z(e,["fetch","origin",r.branch],{timeoutMs:3e5}):(le.default.rmSync(e,{recursive:!0,force:!0}),le.default.mkdirSync(re.default.dirname(e),{recursive:!0,mode:448}),await Z(r.repoPath,["worktree","prune"]).catch(()=>{}),await Z(r.repoPath,["worktree","add","--detach",e,`origin/${r.branch}`])),r.attached?await Z(e,["checkout","-B",r.branch,`origin/${r.branch}`]):await Z(e,["checkout","--force","--detach",`origin/${r.branch}`]),e}async function Ki(r,e,t){try{await Z(r,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin \u2014 nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await Z(r,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await Z(r,["-c",`user.name=${mu}`,"-c",`user.email=${gu}`,"merge","--no-ff","-m",t,`origin/${e}`]),{ok:!0}}catch(n){return await Z(r,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch \u2014 ${n instanceof Error?n.message:n}. Resolve it manually and deploy again.`}}}async function Vi(r,e){try{await Z(r,["push","origin",e],{timeoutMs:3e5})}catch(t){throw new Error(`could not push "${e}" \u2014 ${t instanceof Error?t.message:t}. Someone may have pushed to it since this deploy started; retry.`)}}async function Hi(r,e,t){try{return await pu("git",["-C",r,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(n){let s=n;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function pr(r){return(await Z(r,["config","--get","remote.origin.url"])).trim()}function mr(r){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(r)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(r)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(r);return e?{owner:e[1],repo:e[2]}:null}var le,fr,re,hu,fu,pu,mu,gu,bs,ws,yu,Wr,gr=ii(()=>{"use strict";le=$(require("node:fs"),1),fr=$(require("node:os"),1),re=$(require("node:path"),1),hu=require("node:child_process"),fu=require("node:util"),pu=(0,fu.promisify)(hu.execFile),mu="Allwright Agent",gu="agent@ticketpilot.local",bs=200,ws=2e4,yu=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Wr=".ticketpilot-delete"});var tn={};Yn(tn,{GitHubClient:()=>Oe});var Bp,Oe,ct=ii(()=>{"use strict";Bp=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Oe=class{constructor(e){this.token=e}token;async request(e,t,n){let s=await fetch(`${Bp}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...n!==void 0?{"Content-Type":"application/json"}:{}},body:n===void 0?void 0:JSON.stringify(n)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) \u2014 expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let a=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${t} -> ${s.status}: ${a}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,t,n){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,n);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${n.head}`)}&state=open`);if(o?.length){let a=o[0];return{number:a.number,url:a.html_url,state:a.state,merged:a.merged??!1,headSha:a.head.sha,mergeableState:null}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,headSha:i.head.sha,mergeableState:null}}async getReviews(e,t,n){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,n){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async closePullRequest(e,t,n){await this.request("PATCH",`/repos/${e}/${t}/pulls/${n}`,{state:"closed"})}async deleteBranch(e,t,n){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(n)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var ht=Y((Dv,rl)=>{"use strict";var el=["nodebuffer","arraybuffer","fragments"],tl=typeof Blob<"u";tl&&el.push("blob");rl.exports={BINARY_TYPES:el,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:tl,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var qn=Y((Lv,Bs)=>{"use strict";var{EMPTY_BUFFER:Im}=ht(),Eo=Buffer[Symbol.species];function Am(r,e){if(r.length===0)return Im;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new Eo(t.buffer,t.byteOffset,n):t}function nl(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function sl(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Rm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Io(r){if(Io.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Eo(r):ArrayBuffer.isView(r)?e=new Eo(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Io.readOnly=!1),e}Bs.exports={concat:Am,mask:nl,toArrayBuffer:Rm,toBuffer:Io,unmask:sl};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Bs.exports.mask=function(e,t,n,s,i){i<48?nl(e,t,n,s,i):r.mask(e,t,n,s,i)},Bs.exports.unmask=function(e,t){e.length<32?sl(e,t):r.unmask(e,t)}}catch{}});var al=Y((zv,ol)=>{"use strict";var il=Symbol("kDone"),Ao=Symbol("kRun"),Ro=class{constructor(e){this[il]=()=>{this.pending--,this[Ao]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ao]()}[Ao](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[il])}}};ol.exports=Ro});var ln=Y((Uv,dl)=>{"use strict";var Bn=require("zlib"),ul=qn(),$m=al(),{kStatusCode:cl}=ht(),Pm=Buffer[Symbol.species],jm=Buffer.from([0,0,255,255]),Zs=Symbol("permessage-deflate"),ft=Symbol("total-length"),un=Symbol("callback"),$t=Symbol("buffers"),cn=Symbol("error"),Fs,$o=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Fs){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Fs=new $m(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[un];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){Fs.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Fs.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Bn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Bn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Zs]=this,this._inflate[ft]=0,this._inflate[$t]=[],this._inflate.on("error",Nm),this._inflate.on("data",ll)}this._inflate[un]=n,this._inflate.write(e),t&&this._inflate.write(jm),this._inflate.flush(()=>{let i=this._inflate[cn];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=ul.concat(this._inflate[$t],this._inflate[ft]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ft]=0,this._inflate[$t]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Bn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Bn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ft]=0,this._deflate[$t]=[],this._deflate.on("data",Om)}this._deflate[un]=n,this._deflate.write(e),this._deflate.flush(Bn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ul.concat(this._deflate[$t],this._deflate[ft]);t&&(i=new Pm(i.buffer,i.byteOffset,i.length-4)),this._deflate[un]=null,this._deflate[ft]=0,this._deflate[$t]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};dl.exports=$o;function Om(r){this[$t].push(r),this[ft]+=r.length}function ll(r){if(this[ft]+=r.length,this[Zs]._maxPayload<1||this[ft]<=this[Zs]._maxPayload){this[$t].push(r);return}this[cn]=new RangeError("Max payload size exceeded"),this[cn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[cn][cl]=1009,this.removeListener("data",ll),this.reset()}function Nm(r){if(this[Zs]._inflate=null,this[cn]){this[un](this[cn]);return}r[cl]=1007,this[un](r)}});var dn=Y((qv,Ks)=>{"use strict";var{isUtf8:hl}=require("buffer"),{hasBlob:Mm}=ht(),Dm=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Lm(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Po(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function zm(r){return Mm&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Ks.exports={isBlob:zm,isValidStatusCode:Lm,isValidUTF8:Po,tokenChars:Dm};if(hl)Ks.exports.isValidUTF8=function(r){return r.length<24?Po(r):hl(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Ks.exports.isValidUTF8=function(e){return e.length<32?Po(e):r(e)}}catch{}});var Do=Y((Bv,vl)=>{"use strict";var{Writable:Um}=require("stream"),fl=ln(),{BINARY_TYPES:qm,EMPTY_BUFFER:pl,kStatusCode:Bm,kWebSocket:Fm}=ht(),{concat:jo,toArrayBuffer:Zm,unmask:Km}=qn(),{isValidStatusCode:Vm,isValidUTF8:ml}=dn(),Vs=Buffer[Symbol.species],Ne=0,gl=1,yl=2,_l=3,Oo=4,No=5,Hs=6,Mo=class extends Um{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||qm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Fm]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ne}_write(e,t,n){if(this._opcode===8&&this._state==Ne)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Vs(n.buffer,n.byteOffset+e,n.length-e),new Vs(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Vs(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Ne:this.getInfo(e);break;case gl:this.getPayloadLength16(e);break;case yl:this.getPayloadLength64(e);break;case _l:this.getMask();break;case Oo:this.getData(e);break;case No:case Hs:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[fl.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=gl:this._payloadLength===127?this._state=yl:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=_l:this._state=Oo}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Oo}getData(e){let t=pl;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Km(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this._compressed){this._state=No,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[fl.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===Ne&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ne;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=jo(n,t):this._binaryType==="arraybuffer"?s=Zm(jo(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Ne):(this._state=Hs,setImmediate(()=>{this.emit("message",s,!0),this._state=Ne,this.startLoop(e)}))}else{let s=jo(n,t);if(!this._skipUTF8Validation&&!ml(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===No||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Ne):(this._state=Hs,setImmediate(()=>{this.emit("message",s,!1),this._state=Ne,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,pl),this.end();else{let n=e.readUInt16BE(0);if(!Vm(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Vs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ml(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=Ne;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne):(this._state=Hs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Bm]=s,o}};vl.exports=Mo});var Uo=Y((Zv,kl)=>{"use strict";var{Duplex:Fv}=require("stream"),{randomFillSync:Hm}=require("crypto"),{types:{isUint8Array:Gm}}=require("util"),bl=ln(),{EMPTY_BUFFER:Wm,kWebSocket:Jm,NOOP:Ym}=ht(),{isBlob:hn,isValidStatusCode:Xm}=dn(),{mask:wl,toBuffer:Tr}=qn(),Me=Symbol("kByteLength"),Qm=Buffer.alloc(4),Gs=8*1024,xr,fn=Gs,Be=0,eg=1,tg=2,Lo=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Be,this.onerror=Ym,this[Jm]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||Qm,t.generateMask?t.generateMask(n):(fn===Gs&&(xr===void 0&&(xr=Buffer.alloc(Gs)),Hm(xr,0,Gs),fn=0),n[0]=xr[fn++],n[1]=xr[fn++],n[2]=xr[fn++],n[3]=xr[fn++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Me]!==void 0?a=t[Me]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let l=Buffer.allocUnsafe(s?a+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),t.mask?(l[1]|=128,l[i-4]=n[0],l[i-3]=n[1],l[i-2]=n[2],l[i-1]=n[3],o?[l,e]:s?(wl(e,n,l,i,a),[l]):(wl(e,n,e,0,a),[l,e])):[l,e]}close(e,t,n,s){let i;if(e===void 0)i=Wm;else{if(typeof e!="number"||!Xm(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(Gm(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Me]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Be?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):hn(e)?(s=e.size,i=!1):(e=Tr(e),s=e.length,i=Tr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};hn(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):hn(e)?(s=e.size,i=!1):(e=Tr(e),s=e.length,i=Tr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};hn(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[bl.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):hn(e)?(a=e.size,c=!1):(e=Tr(e),a=e.length,c=Tr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[Me]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};hn(e)?this._state!==Be?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==Be?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[Me],this._state=tg,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(zo,this,a,s);return}this._bufferedBytes-=n[Me];let o=Tr(i);t?this.dispatch(o,t,n,s):(this._state=Be,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(rg,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[bl.extensionName];this._bufferedBytes+=n[Me],this._state=eg,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");zo(this,c,s);return}this._bufferedBytes-=n[Me],this._state=Be,n.readOnly=!1,this.sendFrame(r.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===Be&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};kl.exports=Lo;function zo(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function rg(r,e,t){zo(r,e,t),r.onerror(e)}});var $l=Y((Kv,Rl)=>{"use strict";var{kForOnEventAttribute:Fn,kListener:qo}=ht(),Sl=Symbol("kCode"),Tl=Symbol("kData"),xl=Symbol("kError"),Cl=Symbol("kMessage"),El=Symbol("kReason"),pn=Symbol("kTarget"),Il=Symbol("kType"),Al=Symbol("kWasClean"),pt=class{constructor(e){this[pn]=null,this[Il]=e}get target(){return this[pn]}get type(){return this[Il]}};Object.defineProperty(pt.prototype,"target",{enumerable:!0});Object.defineProperty(pt.prototype,"type",{enumerable:!0});var Cr=class extends pt{constructor(e,t={}){super(e),this[Sl]=t.code===void 0?0:t.code,this[El]=t.reason===void 0?"":t.reason,this[Al]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Sl]}get reason(){return this[El]}get wasClean(){return this[Al]}};Object.defineProperty(Cr.prototype,"code",{enumerable:!0});Object.defineProperty(Cr.prototype,"reason",{enumerable:!0});Object.defineProperty(Cr.prototype,"wasClean",{enumerable:!0});var mn=class extends pt{constructor(e,t={}){super(e),this[xl]=t.error===void 0?null:t.error,this[Cl]=t.message===void 0?"":t.message}get error(){return this[xl]}get message(){return this[Cl]}};Object.defineProperty(mn.prototype,"error",{enumerable:!0});Object.defineProperty(mn.prototype,"message",{enumerable:!0});var Zn=class extends pt{constructor(e,t={}){super(e),this[Tl]=t.data===void 0?null:t.data}get data(){return this[Tl]}};Object.defineProperty(Zn.prototype,"data",{enumerable:!0});var ng={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[Fn]&&s[qo]===e&&!s[Fn])return;let n;if(r==="message")n=function(i,o){let a=new Zn("message",{data:o?i:i.toString()});a[pn]=this,Ws(e,this,a)};else if(r==="close")n=function(i,o){let a=new Cr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[pn]=this,Ws(e,this,a)};else if(r==="error")n=function(i){let o=new mn("error",{error:i,message:i.message});o[pn]=this,Ws(e,this,o)};else if(r==="open")n=function(){let i=new pt("open");i[pn]=this,Ws(e,this,i)};else return;n[Fn]=!!t[Fn],n[qo]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[qo]===e&&!t[Fn]){this.removeListener(r,t);break}}};Rl.exports={CloseEvent:Cr,ErrorEvent:mn,Event:pt,EventTarget:ng,MessageEvent:Zn};function Ws(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Js=Y((Vv,Pl)=>{"use strict";var{tokenChars:Kn}=dn();function Ye(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function sg(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,a,c=-1,l=-1,d=-1,p=0;for(;p<r.length;p++)if(l=r.charCodeAt(p),o===void 0)if(d===-1&&Kn[l]===1)c===-1&&(c=p);else if(p!==0&&(l===32||l===9))d===-1&&c!==-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let S=r.slice(c,d);l===44?(Ye(e,S,t),t=Object.create(null)):o=S,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(d===-1&&Kn[l]===1)c===-1&&(c=p);else if(l===32||l===9)d===-1&&c!==-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p),Ye(t,r.slice(c,d),!0),l===44&&(Ye(e,o,t),t=Object.create(null),o=void 0),c=d=-1}else if(l===61&&c!==-1&&d===-1)a=r.slice(c,p),c=d=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Kn[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:n||(n=!0),s=!1}else if(i)if(Kn[l]===1)c===-1&&(c=p);else if(l===34&&c!==-1)i=!1,d=p;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&r.charCodeAt(p-1)===61)i=!0;else if(d===-1&&Kn[l]===1)c===-1&&(c=p);else if(c!==-1&&(l===32||l===9))d===-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let S=r.slice(c,d);n&&(S=S.replace(/\\/g,""),n=!1),Ye(t,a,S),l===44&&(Ye(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=p);let v=r.slice(c,d);return o===void 0?Ye(e,v,t):(a===void 0?Ye(t,v,!0):n?Ye(t,a,v.replace(/\\/g,"")):Ye(t,a,v),Ye(e,o,t)),e}function ig(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Pl.exports={format:ig,parse:sg}});var ei=Y((Wv,Zl)=>{"use strict";var og=require("events"),ag=require("https"),ug=require("http"),Nl=require("net"),cg=require("tls"),{randomBytes:lg,createHash:dg}=require("crypto"),{Duplex:Hv,Readable:Gv}=require("stream"),{URL:Bo}=require("url"),Pt=ln(),hg=Do(),fg=Uo(),{isBlob:pg}=dn(),{BINARY_TYPES:jl,CLOSE_TIMEOUT:mg,EMPTY_BUFFER:Ys,GUID:gg,kForOnEventAttribute:Fo,kListener:yg,kStatusCode:_g,kWebSocket:oe,NOOP:Ml}=ht(),{EventTarget:{addEventListener:vg,removeEventListener:bg}}=$l(),{format:wg,parse:kg}=Js(),{toBuffer:Sg}=qn(),Dl=Symbol("kAborted"),Zo=[8,13],mt=["CONNECTING","OPEN","CLOSING","CLOSED"],Tg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ne=class r extends og{constructor(e,t,n){super(),this._binaryType=jl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ys,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Ll(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){jl.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new hg({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new fg(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[oe]=this,i[oe]=this,e[oe]=this,s.on("conclude",Eg),s.on("drain",Ig),s.on("error",Ag),s.on("message",Rg),s.on("ping",$g),s.on("pong",Pg),i.onerror=jg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",ql),e.on("data",Qs),e.on("end",Bl),e.on("error",Fl),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Pt.extensionName]&&this._extensions[Pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ul(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ko(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Ys,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ko(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Ys,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ko(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Pt.extensionName]||(s.compress=!1),this._sender.send(e||Ys,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(ne,"CONNECTING",{enumerable:!0,value:mt.indexOf("CONNECTING")});Object.defineProperty(ne.prototype,"CONNECTING",{enumerable:!0,value:mt.indexOf("CONNECTING")});Object.defineProperty(ne,"OPEN",{enumerable:!0,value:mt.indexOf("OPEN")});Object.defineProperty(ne.prototype,"OPEN",{enumerable:!0,value:mt.indexOf("OPEN")});Object.defineProperty(ne,"CLOSING",{enumerable:!0,value:mt.indexOf("CLOSING")});Object.defineProperty(ne.prototype,"CLOSING",{enumerable:!0,value:mt.indexOf("CLOSING")});Object.defineProperty(ne,"CLOSED",{enumerable:!0,value:mt.indexOf("CLOSED")});Object.defineProperty(ne.prototype,"CLOSED",{enumerable:!0,value:mt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(ne.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(ne.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Fo])return e[yg];return null},set(e){for(let t of this.listeners(r))if(t[Fo]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Fo]:!0})}})});ne.prototype.addEventListener=vg;ne.prototype.removeEventListener=bg;Zl.exports=ne;function Ll(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:mg,protocolVersion:Zo[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!Zo.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Zo.join(", ")})`);let i;if(e instanceof Bo)i=e;else try{i=new Bo(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let w=new SyntaxError(c);if(r._redirects===0)throw w;Xs(r,w);return}let l=o?443:80,d=lg(16).toString("base64"),p=o?ag.request:ug.request,v=new Set,S;if(s.createConnection=s.createConnection||(o?Cg:xg),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(S=new Pt({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=wg({[Pt.extensionName]:S.offer()})),t.length){for(let w of t){if(typeof w!="string"||!Tg.test(w)||v.has(w))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(w)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let w=s.path.split(":");s.socketPath=w[0],s.path=w[1]}let x;if(s.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?s.socketPath:i.host;let w=n&&n.headers;if(n={...n,headers:{}},w)for(let[j,U]of Object.entries(w))n.headers[j.toLowerCase()]=U}else if(r.listenerCount("redirect")===0){let w=a?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!w||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,w||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),x=r._req=p(s),r._redirects&&r.emit("redirect",r.url,x)}else x=r._req=p(s);s.timeout&&x.on("timeout",()=>{xe(r,x,"Opening handshake has timed out")}),x.on("error",w=>{x===null||x[Dl]||(x=r._req=null,Xs(r,w))}),x.on("response",w=>{let j=w.headers.location,U=w.statusCode;if(j&&s.followRedirects&&U>=300&&U<400){if(++r._redirects>s.maxRedirects){xe(r,x,"Maximum redirects exceeded");return}x.abort();let f;try{f=new Bo(j,e)}catch{let b=new SyntaxError(`Invalid URL: ${j}`);Xs(r,b);return}Ll(r,f,t,n)}else r.emit("unexpected-response",x,w)||xe(r,x,`Unexpected server response: ${w.statusCode}`)}),x.on("upgrade",(w,j,U)=>{if(r.emit("upgrade",w),r.readyState!==ne.CONNECTING)return;x=r._req=null;let f=w.headers.upgrade;if(f===void 0||f.toLowerCase()!=="websocket"){xe(r,j,"Invalid Upgrade header");return}let g=dg("sha1").update(d+gg).digest("base64");if(w.headers["sec-websocket-accept"]!==g){xe(r,j,"Invalid Sec-WebSocket-Accept header");return}let b=w.headers["sec-websocket-protocol"],I;if(b!==void 0?v.size?v.has(b)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":v.size&&(I="Server sent no subprotocol"),I){xe(r,j,I);return}b&&(r._protocol=b);let N=w.headers["sec-websocket-extensions"];if(N!==void 0){if(!S){xe(r,j,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let V;try{V=kg(N)}catch{xe(r,j,"Invalid Sec-WebSocket-Extensions header");return}let W=Object.keys(V);if(W.length!==1||W[0]!==Pt.extensionName){xe(r,j,"Server indicated an extension that was not requested");return}try{S.accept(V[Pt.extensionName])}catch{xe(r,j,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Pt.extensionName]=S}r.setSocket(j,U,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(x,r):x.end()}function Xs(r,e){r._readyState=ne.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function xg(r){return r.path=r.socketPath,Nl.connect(r)}function Cg(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Nl.isIP(r.host)?"":r.host),cg.connect(r)}function xe(r,e,t){r._readyState=ne.CLOSING;let n=new Error(t);Error.captureStackTrace(n,xe),e.setHeader?(e[Dl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Xs,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Ko(r,e,t){if(e){let n=pg(e)?e.size:Sg(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${mt[r.readyState]})`);process.nextTick(t,n)}}function Eg(r,e){let t=this[oe];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[oe]!==void 0&&(t._socket.removeListener("data",Qs),process.nextTick(zl,t._socket),r===1005?t.close():t.close(r,e))}function Ig(){let r=this[oe];r.isPaused||r._socket.resume()}function Ag(r){let e=this[oe];e._socket[oe]!==void 0&&(e._socket.removeListener("data",Qs),process.nextTick(zl,e._socket),e.close(r[_g])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Ol(){this[oe].emitClose()}function Rg(r,e){this[oe].emit("message",r,e)}function $g(r){let e=this[oe];e._autoPong&&e.pong(r,!this._isServer,Ml),e.emit("ping",r)}function Pg(r){this[oe].emit("pong",r)}function zl(r){r.resume()}function jg(r){let e=this[oe];e.readyState!==ne.CLOSED&&(e.readyState===ne.OPEN&&(e._readyState=ne.CLOSING,Ul(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Ul(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function ql(){let r=this[oe];if(this.removeListener("close",ql),this.removeListener("data",Qs),this.removeListener("end",Bl),r._readyState=ne.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[oe]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Ol),r._receiver.on("finish",Ol))}function Qs(r){this[oe]._receiver.write(r)||this.pause()}function Bl(){let r=this[oe];r._readyState=ne.CLOSING,r._receiver.end(),this.end()}function Fl(){let r=this[oe];this.removeListener("error",Fl),this.on("error",Ml),r&&(r._readyState=ne.CLOSING,this.destroy())}});var Gl=Y((Yv,Hl)=>{"use strict";var Jv=ei(),{Duplex:Og}=require("stream");function Kl(r){r.emit("close")}function Ng(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vl(r){this.removeListener("error",Vl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Mg(r,e){let t=!0,n=new Og({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(Kl,n);return}let o=!1;r.once("error",function(c){o=!0,i(c)}),r.once("close",function(){o||i(s),process.nextTick(Kl,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Ng),n.on("error",Vl),n}Hl.exports=Mg});var Vo=Y((Xv,Wl)=>{"use strict";var{tokenChars:Dg}=dn();function Lg(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&Dg[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=r.slice(t,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Wl.exports={parse:Lg}});var rd=Y((eb,td)=>{"use strict";var zg=require("events"),ti=require("http"),{Duplex:Qv}=require("stream"),{createHash:Ug}=require("crypto"),Jl=Js(),Er=ln(),qg=Vo(),Bg=ei(),{CLOSE_TIMEOUT:Fg,GUID:Zg,kWebSocket:Kg}=ht(),Vg=/^[+/0-9A-Za-z]{22}==$/,Yl=0,Xl=1,ed=2,Ho=class extends zg{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Fg,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Bg,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ti.createServer((n,s)=>{let i=ti.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Hg(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Yl}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===ed){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Vn,this);return}if(e&&this.once("close",e),this._state!==Xl)if(this._state=Xl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Vn,this):process.nextTick(Vn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Vn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Ql);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ir(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Ir(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Vg.test(i)){Ir(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ir(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Hn(t,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=qg.parse(c)}catch{Ir(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&d!==void 0){let v=new Er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let S=Jl.parse(d);S[Er.extensionName]&&(v.accept(S[Er.extensionName]),p[Er.extensionName]=v)}catch{Ir(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(S,x,w,j)=>{if(!S)return Hn(t,x||401,w,j);this.completeUpgrade(p,i,l,e,t,n,s)});return}if(!this.options.verifyClient(v))return Hn(t,401)}this.completeUpgrade(p,i,l,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Kg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Yl)return Hn(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ug("sha1").update(t+Zg).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),d._protocol=p)}if(e[Er.extensionName]){let p=e[Er.extensionName].params,v=Jl.format({[Er.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${v}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
|
|
230
231
|
`).join(`\r
|
|
231
|
-
`)),i.removeListener("error",
|
|
232
|
+
`)),i.removeListener("error",Ql),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Vn,this)})),a(d,s)}};td.exports=Ho;function Hg(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function Vn(r){r._state=ed,r.emit("close")}function Ql(){this.destroy()}function Hn(r,e,t,n){t=t||ti.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${ti.STATUS_CODES[e]}\r
|
|
232
233
|
`+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
|
|
233
234
|
`)+`\r
|
|
234
235
|
\r
|
|
235
|
-
`+t)}function Er(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Er),r.emit("wsClientError",o,t,e)}else Kn(t,n,s,i)}});var pn=$(require("node:fs"),1),id=$(require("node:os"),1),od=$(require("node:path"),1),Hn=require("node:child_process"),Wo=require("node:crypto"),Ir=$(require("node:readline/promises"),1);var ma=$(pa(),1),{program:oy,createCommand:ay,createArgument:cy,createOption:uy,CommanderError:ly,InvalidArgumentError:dy,InvalidOptionArgumentError:hy,Command:ga,Argument:fy,Option:py,Help:my}=ma.default;var st=$(require("node:fs"),1),rs=$(require("node:os"),1),ns=$(require("node:path"),1);var k={};ri(k,{BRAND:()=>eh,DIRTY:()=>jt,EMPTY_PATH:()=>Pd,INVALID:()=>M,NEVER:()=>Lh,OK:()=>de,ParseStatus:()=>ce,Schema:()=>K,ZodAny:()=>vt,ZodArray:()=>nt,ZodBigInt:()=>Nt,ZodBoolean:()=>Mt,ZodBranded:()=>_n,ZodCatch:()=>Ht,ZodDate:()=>Dt,ZodDefault:()=>Vt,ZodDiscriminatedUnion:()=>Qn,ZodEffects:()=>Re,ZodEnum:()=>Zt,ZodError:()=>ge,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>ts,ZodIntersection:()=>qt,ZodIssueCode:()=>T,ZodLazy:()=>Bt,ZodLiteral:()=>Ft,ZodMap:()=>Or,ZodNaN:()=>Mr,ZodNativeEnum:()=>Kt,ZodNever:()=>De,ZodNull:()=>zt,ZodNullable:()=>Ke,ZodNumber:()=>Ot,ZodObject:()=>ye,ZodOptional:()=>Ie,ZodParsedType:()=>R,ZodPipeline:()=>vn,ZodPromise:()=>bt,ZodReadonly:()=>Gt,ZodRecord:()=>es,ZodSchema:()=>K,ZodSet:()=>Nr,ZodString:()=>_t,ZodSymbol:()=>Pr,ZodTransformer:()=>Re,ZodTuple:()=>Ze,ZodType:()=>K,ZodUndefined:()=>Lt,ZodUnion:()=>Ut,ZodUnknown:()=>rt,ZodVoid:()=>jr,addIssueToContext:()=>A,any:()=>uh,array:()=>fh,bigint:()=>sh,boolean:()=>Ea,coerce:()=>Dh,custom:()=>Ta,date:()=>ih,datetimeRegex:()=>ka,defaultErrorMap:()=>et,discriminatedUnion:()=>yh,effect:()=>Ah,enum:()=>Ch,function:()=>Sh,getErrorMap:()=>Ar,getParsedType:()=>Fe,instanceof:()=>rh,intersection:()=>_h,isAborted:()=>Yn,isAsync:()=>Rr,isDirty:()=>Xn,isValid:()=>yt,late:()=>th,lazy:()=>Th,literal:()=>xh,makeIssue:()=>yn,map:()=>wh,nan:()=>nh,nativeEnum:()=>Eh,never:()=>dh,null:()=>ch,nullable:()=>$h,number:()=>Ca,object:()=>ph,objectUtil:()=>_i,oboolean:()=>Mh,onumber:()=>Nh,optional:()=>Rh,ostring:()=>Oh,pipeline:()=>jh,preprocess:()=>Ph,promise:()=>Ih,quotelessJson:()=>Ad,record:()=>bh,set:()=>kh,setErrorMap:()=>$d,strictObject:()=>mh,string:()=>xa,symbol:()=>oh,transformer:()=>Ah,tuple:()=>vh,undefined:()=>ah,union:()=>gh,unknown:()=>lh,util:()=>G,void:()=>hh});var G;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(G||(G={}));var _i;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(_i||(_i={}));var R=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Fe=r=>{switch(typeof r){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(r)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(r)?R.array:r===null?R.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?R.promise:typeof Map<"u"&&r instanceof Map?R.map:typeof Set<"u"&&r instanceof Set?R.set:typeof Date<"u"&&r instanceof Date?R.date:R.object;default:return R.unknown}};var T=G.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ad=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),ge=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};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(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,u=0;for(;u<o.path.length;){let l=o.path[u];u===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],u++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};ge.create=r=>new ge(r);var Rd=(r,e)=>{let t;switch(r.code){case T.invalid_type:r.received===R.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case T.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,G.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:t=`Unrecognized key(s) in object: ${G.joinValues(r.keys,", ")}`;break;case T.invalid_union:t="Invalid input";break;case T.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${G.joinValues(r.options)}`;break;case T.invalid_enum_value:t=`Invalid enum value. Expected ${G.joinValues(r.options)}, received '${r.received}'`;break;case T.invalid_arguments:t="Invalid function arguments";break;case T.invalid_return_type:t="Invalid function return type";break;case T.invalid_date:t="Invalid date";break;case T.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:G.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case T.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case T.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case T.custom:t="Invalid input";break;case T.invalid_intersection_types:t="Intersection results could not be merged";break;case T.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case T.not_finite:t="Number must be finite";break;default:t=e.defaultError,G.assertNever(r)}return{message:t}},et=Rd;var ya=et;function $d(r){ya=r}function Ar(){return ya}var yn=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",u=n.filter(l=>!!l).slice().reverse();for(let l of u)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Pd=[];function A(r,e){let t=Ar(),n=yn({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===et?void 0:et].filter(s=>!!s)});r.common.issues.push(n)}var ce=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return M;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return M;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}},M=Object.freeze({status:"aborted"}),jt=r=>({status:"dirty",value:r}),de=r=>({status:"valid",value:r}),Yn=r=>r.status==="aborted",Xn=r=>r.status==="dirty",yt=r=>r.status==="valid",Rr=r=>typeof Promise<"u"&&r instanceof Promise;var P;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));var Ae=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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}},_a=(r,e)=>{if(yt(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new ge(r.common.issues);return this._error=t,this._error}}};function q(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:u}=r;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??t??a.defaultError}},description:s}}var K=class{get description(){return this._def.description}_getType(e){return Fe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Fe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ce,ctx:{common:e.parent.common,data:e.data,parsedType:Fe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Rr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let 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:Fe(e)},s=this._parseSync({data:e,path:n.path,parent:n});return _a(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fe(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return yt(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>yt(n)?{value:n.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:Fe(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Rr(s)?s:Promise.resolve(s));return _a(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:T.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new Re({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ie.create(this,this._def)}nullable(){return Ke.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nt.create(this)}promise(){return bt.create(this,this._def)}or(e){return Ut.create([this,e],this._def)}and(e){return qt.create(this,e,this._def)}transform(e){return new Re({...q(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Vt({...q(this._def),innerType:this,defaultValue:t,typeName:D.ZodDefault})}brand(){return new _n({typeName:D.ZodBranded,type:this,...q(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Ht({...q(this._def),innerType:this,catchValue:t,typeName:D.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return vn.create(this,e)}readonly(){return Gt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},jd=/^c[^\s-]{8,}$/i,Od=/^[0-9a-z]+$/,Nd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Md=/^[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,Dd=/^[a-z0-9_-]{21}$/i,Ld=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zd=/^[-+]?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)?)??$/,Ud=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,qd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vi,Bd=/^(?:(?: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])$/,Fd=/^(?:(?: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])$/,Zd=/^(([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]))$/,Kd=/^(([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])$/,Vd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ba="((\\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])))",Gd=new RegExp(`^${ba}$`);function wa(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Wd(r){return new RegExp(`^${wa(r)}$`)}function ka(r){let e=`${ba}T${wa(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Jd(r,e){return!!((e==="v4"||!e)&&Bd.test(r)||(e==="v6"||!e)&&Zd.test(r))}function Yd(r,e){if(!Ld.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Xd(r,e){return!!((e==="v4"||!e)&&Fd.test(r)||(e==="v6"||!e)&&Kd.test(r))}var _t=class r extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.string,received:i.parsedType}),M}let n=new ce,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?A(s,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&A(s,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Ud.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"email",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")vi||(vi=new RegExp(qd,"u")),vi.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"emoji",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Md.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"uuid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Dd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"nanoid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")jd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Od.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid2",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Nd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ulid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),A(s,{validation:"url",code:T.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"regex",code:T.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?ka(i).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Gd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Wd(i).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?zd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"duration",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Jd(e.data,i.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ip",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Yd(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"jwt",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Xd(e.data,i.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cidr",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Vd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Hd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64url",code:T.invalid_string,message:i.message}),n.dirty()):G.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:T.invalid_string,...P.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...P.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...P.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...P.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...P.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...P.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...P.errToObj(t)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};_t.create=r=>new _t({checks:[],typeName:D.ZodString,coerce:r?.coerce??!1,...q(r)});function Qd(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Ot=class r extends K{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)!==R.number){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.number,received:i.parsedType}),M}let n,s=new ce;for(let i of this._def.checks)i.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Qd(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_finite,message:i.message}),s.dirty()):G.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&G.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;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)}};Ot.create=r=>new Ot({checks:[],typeName:D.ZodNumber,coerce:r?.coerce||!1,...q(r)});var Nt=class r extends K{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)!==R.bigint)return this._getInvalidInput(e);let n,s=new ce;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):G.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return A(t,{code:T.invalid_type,expected:R.bigint,received:t.parsedType}),M}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:P.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}};Nt.create=r=>new Nt({checks:[],typeName:D.ZodBigInt,coerce:r?.coerce??!1,...q(r)});var Mt=class extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.boolean,received:n.parsedType}),M}return de(e.data)}};Mt.create=r=>new Mt({typeName:D.ZodBoolean,coerce:r?.coerce||!1,...q(r)});var Dt=class r extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.date,received:i.parsedType}),M}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_date}),M}let n=new ce,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):G.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:P.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Dt.create=r=>new Dt({checks:[],coerce:r?.coerce||!1,typeName:D.ZodDate,...q(r)});var Pr=class extends K{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.symbol,received:n.parsedType}),M}return de(e.data)}};Pr.create=r=>new Pr({typeName:D.ZodSymbol,...q(r)});var Lt=class extends K{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.undefined,received:n.parsedType}),M}return de(e.data)}};Lt.create=r=>new Lt({typeName:D.ZodUndefined,...q(r)});var zt=class extends K{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.null,received:n.parsedType}),M}return de(e.data)}};zt.create=r=>new zt({typeName:D.ZodNull,...q(r)});var vt=class extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return de(e.data)}};vt.create=r=>new vt({typeName:D.ZodAny,...q(r)});var rt=class extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return de(e.data)}};rt.create=r=>new rt({typeName:D.ZodUnknown,...q(r)});var De=class extends K{_parse(e){let t=this._getOrReturnCtx(e);return A(t,{code:T.invalid_type,expected:R.never,received:t.parsedType}),M}};De.create=r=>new De({typeName:D.ZodNever,...q(r)});var jr=class extends K{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.void,received:n.parsedType}),M}return de(e.data)}};jr.create=r=>new jr({typeName:D.ZodVoid,...q(r)});var nt=class r extends K{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==R.array)return A(t,{code:T.invalid_type,expected:R.array,received:t.parsedType}),M;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&(A(t,{code:o?T.too_big:T.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(A(t,{code:T.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(A(t,{code:T.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Ae(t,o,t.path,a)))).then(o=>ce.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Ae(t,o,t.path,a)));return ce.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:P.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:P.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:P.toString(t)}})}nonempty(e){return this.min(1,e)}};nt.create=(r,e)=>new nt({type:r,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...q(e)});function $r(r){if(r instanceof ye){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Ie.create($r(n))}return new ye({...r._def,shape:()=>e})}else return r instanceof nt?new nt({...r._def,type:$r(r.element)}):r instanceof Ie?Ie.create($r(r.unwrap())):r instanceof Ke?Ke.create($r(r.unwrap())):r instanceof Ze?Ze.create(r.items.map(e=>$r(e))):r}var ye=class r extends K{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=G.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==R.object){let l=this._getOrReturnCtx(e);return A(l,{code:T.invalid_type,expected:R.object,received:l.parsedType}),M}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof De&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let u=[];for(let l of o){let d=i[l],p=s.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new Ae(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof De){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of a)u.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")a.length>0&&(A(s,{code:T.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of a){let p=s.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new Ae(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of u){let p=await d.key,v=await d.value;l.push({key:p,value:v,alwaysSet:d.alwaysSet})}return l}).then(l=>ce.mergeObjectSync(n,l)):ce.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:P.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of G.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of G.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return $r(this)}partial(e){let t={};for(let n of G.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of G.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Ie;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Sa(G.objectKeys(this.shape))}};ye.create=(r,e)=>new ye({shape:()=>r,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...q(e)});ye.strictCreate=(r,e)=>new ye({shape:()=>r,unknownKeys:"strict",catchall:De.create(),typeName:D.ZodObject,...q(e)});ye.lazycreate=(r,e)=>new ye({shape:r,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...q(e)});var Ut=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new ge(a.ctx.common.issues));return A(t,{code:T.invalid_union,unionErrors:o}),M}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of n){let l={...t,common:{...t.common,issues:[]},parent:null},d=u._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(u=>new ge(u));return A(t,{code:T.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}};Ut.create=(r,e)=>new Ut({options:r,typeName:D.ZodUnion,...q(e)});var tt=r=>r instanceof Bt?tt(r.schema):r instanceof Re?tt(r.innerType()):r instanceof Ft?[r.value]:r instanceof Zt?r.options:r instanceof Kt?G.objectValues(r.enum):r instanceof Vt?tt(r._def.innerType):r instanceof Lt?[void 0]:r instanceof zt?[null]:r instanceof Ie?[void 0,...tt(r.unwrap())]:r instanceof Ke?[null,...tt(r.unwrap())]:r instanceof _n||r instanceof Gt?tt(r.unwrap()):r instanceof Ht?tt(r._def.innerType):[],Qn=class r extends K{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.object)return A(t,{code:T.invalid_type,expected:R.object,received:t.parsedType}),M;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);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}):(A(t,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=tt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...q(n)})}};function bi(r,e){let t=Fe(r),n=Fe(e);if(r===e)return{valid:!0,data:r};if(t===R.object&&n===R.object){let s=G.objectKeys(e),i=G.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let u=bi(r[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===R.array&&n===R.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],u=bi(o,a);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===R.date&&n===R.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var qt=class extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(Yn(i)||Yn(o))return M;let a=bi(i.value,o.value);return a.valid?((Xn(i)||Xn(o))&&t.dirty(),{status:t.value,value:a.data}):(A(n,{code:T.invalid_intersection_types}),M)};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(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};qt.create=(r,e,t)=>new qt({left:r,right:e,typeName:D.ZodIntersection,...q(t)});var Ze=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return A(n,{code:T.invalid_type,expected:R.array,received:n.parsedType}),M;if(n.data.length<this._def.items.length)return A(n,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&n.data.length>this._def.items.length&&(A(n,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Ae(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>ce.mergeArray(t,o)):ce.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};Ze.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ze({items:r,typeName:D.ZodTuple,rest:null,...q(e)})};var es=class r extends K{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!==R.object)return A(n,{code:T.invalid_type,expected:R.object,received:n.parsedType}),M;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Ae(n,a,n.path,a)),value:o._parse(new Ae(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ce.mergeObjectAsync(t,s):ce.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof K?new r({keyType:e,valueType:t,typeName:D.ZodRecord,...q(n)}):new r({keyType:_t.create(),valueType:e,typeName:D.ZodRecord,...q(t)})}},Or=class extends K{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!==R.map)return A(n,{code:T.invalid_type,expected:R.map,received:n.parsedType}),M;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,u],l)=>({key:s._parse(new Ae(n,a,n.path,[l,"key"])),value:i._parse(new Ae(n,u,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of o){let l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return M;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let u of o){let l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return M;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}}}};Or.create=(r,e,t)=>new Or({valueType:e,keyType:r,typeName:D.ZodMap,...q(t)});var Nr=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return A(n,{code:T.invalid_type,expected:R.set,received:n.parsedType}),M;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(A(n,{code:T.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(A(n,{code:T.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(u){let l=new Set;for(let d of u){if(d.status==="aborted")return M;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((u,l)=>i._parse(new Ae(n,u,n.path,l)));return n.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:P.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:P.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Nr.create=(r,e)=>new Nr({valueType:r,minSize:null,maxSize:null,typeName:D.ZodSet,...q(e)});var ts=class r extends K{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.function)return A(t,{code:T.invalid_type,expected:R.function,received:t.parsedType}),M;function n(a,u){return yn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ar(),et].filter(l=>!!l),issueData:{code:T.invalid_arguments,argumentsError:u}})}function s(a,u){return yn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ar(),et].filter(l=>!!l),issueData:{code:T.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof bt){let a=this;return de(async function(...u){let l=new ge([]),d=await a._def.args.parseAsync(u,i).catch(S=>{throw l.addIssue(n(u,S)),l}),p=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw l.addIssue(s(p,S)),l})})}else{let a=this;return de(function(...u){let l=a._def.args.safeParse(u,i);if(!l.success)throw new ge([n(u,l.error)]);let d=Reflect.apply(o,this,l.data),p=a._def.returns.safeParse(d,i);if(!p.success)throw new ge([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ze.create(e).rest(rt.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Ze.create([]).rest(rt.create()),returns:t||rt.create(),typeName:D.ZodFunction,...q(n)})}},Bt=class extends K{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})}};Bt.create=(r,e)=>new Bt({getter:r,typeName:D.ZodLazy,...q(e)});var Ft=class extends K{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return A(t,{received:t.data,code:T.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ft.create=(r,e)=>new Ft({value:r,typeName:D.ZodLiteral,...q(e)});function Sa(r,e){return new Zt({values:r,typeName:D.ZodEnum,...q(e)})}var Zt=class r extends K{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return A(t,{expected:G.joinValues(n),received:t.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return A(t,{received:t.data,code:T.invalid_enum_value,options:n}),M}return de(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Zt.create=Sa;var Kt=class extends K{_parse(e){let t=G.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let s=G.objectValues(t);return A(n,{expected:G.joinValues(s),received:n.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=G.objectValues(t);return A(n,{received:n.data,code:T.invalid_enum_value,options:s}),M}return de(e.data)}get enum(){return this._def.values}};Kt.create=(r,e)=>new Kt({values:r,typeName:D.ZodNativeEnum,...q(e)});var bt=class extends K{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.promise&&t.common.async===!1)return A(t,{code:T.invalid_type,expected:R.promise,received:t.parsedType}),M;let n=t.parsedType===R.promise?t.data:Promise.resolve(t.data);return de(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};bt.create=(r,e)=>new bt({type:r,typeName:D.ZodPromise,...q(e)});var Re=class extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{A(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return M;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?M:u.status==="dirty"?jt(u.value):t.value==="dirty"?jt(u.value):u});{if(t.value==="aborted")return M;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?M:a.status==="dirty"?jt(a.value):t.value==="dirty"?jt(a.value):a}}if(s.type==="refinement"){let o=a=>{let u=s.refinement(a,i);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?M:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?M:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!yt(o))return M;let a=s.transform(o.value,i);if(a instanceof Promise)throw new 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(o=>yt(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):M);G.assertNever(s)}};Re.create=(r,e,t)=>new Re({schema:r,typeName:D.ZodEffects,effect:e,...q(t)});Re.createWithPreprocess=(r,e,t)=>new Re({schema:e,effect:{type:"preprocess",transform:r},typeName:D.ZodEffects,...q(t)});var Ie=class extends K{_parse(e){return this._getType(e)===R.undefined?de(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ie.create=(r,e)=>new Ie({innerType:r,typeName:D.ZodOptional,...q(e)});var Ke=class extends K{_parse(e){return this._getType(e)===R.null?de(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ke.create=(r,e)=>new Ke({innerType:r,typeName:D.ZodNullable,...q(e)});var Vt=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Vt.create=(r,e)=>new Vt({innerType:r,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...q(e)});var Ht=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Rr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ge(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ge(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ht.create=(r,e)=>new Ht({innerType:r,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...q(e)});var Mr=class extends K{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.nan,received:n.parsedType}),M}return{status:"valid",value:e.data}}};Mr.create=r=>new Mr({typeName:D.ZodNaN,...q(r)});var eh=Symbol("zod_brand"),_n=class extends K{_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}},vn=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?M:i.status==="dirty"?(t.dirty(),jt(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?M:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:D.ZodPipeline})}},Gt=class extends K{_parse(e){let t=this._def.innerType._parse(e),n=s=>(yt(s)&&(s.value=Object.freeze(s.value)),s);return Rr(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Gt.create=(r,e)=>new Gt({innerType:r,typeName:D.ZodReadonly,...q(e)});function va(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Ta(r,e={},t){return r?vt.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=va(e,n),u=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:u})}});if(!i){let o=va(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):vt.create()}var th={object:ye.lazycreate},D;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(D||(D={}));var rh=(r,e={message:`Input not instance of ${r.name}`})=>Ta(t=>t instanceof r,e),xa=_t.create,Ca=Ot.create,nh=Mr.create,sh=Nt.create,Ea=Mt.create,ih=Dt.create,oh=Pr.create,ah=Lt.create,ch=zt.create,uh=vt.create,lh=rt.create,dh=De.create,hh=jr.create,fh=nt.create,ph=ye.create,mh=ye.strictCreate,gh=Ut.create,yh=Qn.create,_h=qt.create,vh=Ze.create,bh=es.create,wh=Or.create,kh=Nr.create,Sh=ts.create,Th=Bt.create,xh=Ft.create,Ch=Zt.create,Eh=Kt.create,Ih=bt.create,Ah=Re.create,Rh=Ie.create,$h=Ke.create,Ph=Re.createWithPreprocess,jh=vn.create,Oh=()=>xa().optional(),Nh=()=>Ca().optional(),Mh=()=>Ea().optional(),Dh={string:(r=>_t.create({...r,coerce:!0})),number:(r=>Ot.create({...r,coerce:!0})),boolean:(r=>Mt.create({...r,coerce:!0})),bigint:(r=>Nt.create({...r,coerce:!0})),date:(r=>Dt.create({...r,coerce:!0}))};var Lh=M;var Ia=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),wi=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(rs.default.hostname()),jira:Ia.optional(),repos:k.record(k.object({path:k.string(),jira:Ia.optional(),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional()})).default({}),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional(),githubUsers:k.record(k.object({token:k.string().min(1),login:k.string().optional()})).default({}),deploy:k.object({enabled:k.boolean().default(!1)}).default({enabled:!1}),environments:k.record(k.object({secrets:k.record(k.string()).default({})})).default({}),claudeProfiles:k.record(k.object({configDir:k.string()})).default({}),claudeBin:k.string().default("claude"),agents:k.record(k.object({bin:k.string()})).default({}),jiraUsers:k.record(k.object({email:k.string().email(),apiToken:k.string().min(1)})).default({}),auditSchedules:k.array(k.object({repoName:k.string(),role:k.enum(["security","testing"]),intervalHours:k.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:k.number().int().min(10).max(600).default(30)});function ee(){let r=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(r)return r;let e=ns.default.join(rs.default.homedir(),".config","allwright"),t=ns.default.join(rs.default.homedir(),".config","ticketpilot");return!st.default.existsSync(e)&&st.default.existsSync(t)?t:e}function wt(){return ns.default.join(ee(),"runner.json")}function he(){let r=wt();if(!st.default.existsSync(r))return null;let e=JSON.parse(st.default.readFileSync(r,"utf8"));return wi.parse(e)}function ie(r){let e=ee();st.default.mkdirSync(e,{recursive:!0,mode:448});let t=wt(),n=t+".tmp";st.default.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
236
|
-
`,{mode:384}),st.default.renameSync(n,t),st.default.chmodSync(t,384)}function
|
|
237
|
-
`).filter(Boolean);for(let i of t)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import \u2014 unsafe path in archive: ${i}`);let n=ee(),s;we.default.existsSync(n)&&we.default.readdirSync(n).length&&(s=`${n}.bak-${Date.now()}`,we.default.renameSync(n,s)),we.default.mkdirSync(n,{recursive:!0,mode:448}),(0,
|
|
236
|
+
`+t)}function Ir(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Ir),r.emit("wsClientError",o,t,e)}else Hn(t,n,s,i)}});var dd={};Yn(dd,{buildSetupReport:()=>ay,claudeLoggedIn:()=>ld});function ld(r=ud.default.homedir()){if(jt.default.existsSync(Ar.default.join(r,".claude",".credentials.json")))return!0;try{return!!JSON.parse(jt.default.readFileSync(Ar.default.join(r,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function ay(r,e){let t=!1,n="";try{let{stdout:o}=await oy(r.claudeBin,["--version"],{timeout:1e4});t=!0,n=o.trim().slice(0,60)}catch{t=!1}let s=e.map(o=>{let a=r.repos[o];if(!a)return{repoName:o,mapped:!1,pathExists:!1,isGit:!1,claudeMd:!1,deployMd:!1,testMd:!1};let c=jt.default.existsSync(a.path);return{repoName:o,mapped:!0,pathExists:c,isGit:c&&jt.default.existsSync(Ar.default.join(a.path,".git")),claudeMd:c&&jt.default.existsSync(Ar.default.join(a.path,"CLAUDE.md")),deployMd:c&&jt.default.existsSync(Ar.default.join(a.path,"DEPLOY.md")),testMd:c&&jt.default.existsSync(Ar.default.join(a.path,"TEST.md"))}}),i=Object.values(r.repos).find(o=>o.github?.token);return{jiraConfigured:!!r.jira,jiraEmail:r.jira?.email??"",claude:{installed:t,version:n,loggedIn:ld()},githubTokenSet:!!(r.github?.token||i),githubLogin:r.github?.login??i?.github?.login??"",deploysEnabled:r.deploy.enabled,jiraUserCount:Object.keys(r.jiraUsers).length,repos:s}}var ad,jt,ud,Ar,cd,oy,hd=ii(()=>{"use strict";ad=require("node:child_process"),jt=$(require("node:fs"),1),ud=$(require("node:os"),1),Ar=$(require("node:path"),1),cd=require("node:util"),oy=(0,cd.promisify)(ad.execFile)});var yn=$(require("node:fs"),1),fd=$(require("node:os"),1),pd=$(require("node:path"),1),Wn=require("node:child_process"),Xo=require("node:crypto"),Rr=$(require("node:readline/promises"),1);var ya=$(ga(),1),{program:yy,createCommand:_y,createArgument:vy,createOption:by,CommanderError:wy,InvalidArgumentError:ky,InvalidOptionArgumentError:Sy,Command:_a,Argument:Ty,Option:xy,Help:Cy}=ya.default;var st=$(require("node:fs"),1),is=$(require("node:os"),1),os=$(require("node:path"),1);var k={};Yn(k,{BRAND:()=>uh,DIRTY:()=>Ot,EMPTY_PATH:()=>Ud,INVALID:()=>M,NEVER:()=>Vh,OK:()=>he,ParseStatus:()=>ue,Schema:()=>K,ZodAny:()=>vt,ZodArray:()=>nt,ZodBigInt:()=>Mt,ZodBoolean:()=>Dt,ZodBranded:()=>wn,ZodCatch:()=>Gt,ZodDate:()=>Lt,ZodDefault:()=>Ht,ZodDiscriminatedUnion:()=>rs,ZodEffects:()=>Re,ZodEnum:()=>Kt,ZodError:()=>ge,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>ss,ZodIntersection:()=>Bt,ZodIssueCode:()=>T,ZodLazy:()=>Ft,ZodLiteral:()=>Zt,ZodMap:()=>Mr,ZodNaN:()=>Lr,ZodNativeEnum:()=>Vt,ZodNever:()=>De,ZodNull:()=>Ut,ZodNullable:()=>Ke,ZodNumber:()=>Nt,ZodObject:()=>ye,ZodOptional:()=>Ie,ZodParsedType:()=>R,ZodPipeline:()=>kn,ZodPromise:()=>bt,ZodReadonly:()=>Wt,ZodRecord:()=>ns,ZodSchema:()=>K,ZodSet:()=>Dr,ZodString:()=>_t,ZodSymbol:()=>Or,ZodTransformer:()=>Re,ZodTuple:()=>Ze,ZodType:()=>K,ZodUndefined:()=>zt,ZodUnion:()=>qt,ZodUnknown:()=>rt,ZodVoid:()=>Nr,addIssueToContext:()=>A,any:()=>yh,array:()=>wh,bigint:()=>hh,boolean:()=>Aa,coerce:()=>Kh,custom:()=>Ca,date:()=>fh,datetimeRegex:()=>Ta,defaultErrorMap:()=>et,discriminatedUnion:()=>xh,effect:()=>Dh,enum:()=>Oh,function:()=>$h,getErrorMap:()=>$r,getParsedType:()=>Fe,instanceof:()=>lh,intersection:()=>Ch,isAborted:()=>es,isAsync:()=>Pr,isDirty:()=>ts,isValid:()=>yt,late:()=>ch,lazy:()=>Ph,literal:()=>jh,makeIssue:()=>bn,map:()=>Ah,nan:()=>dh,nativeEnum:()=>Nh,never:()=>vh,null:()=>gh,nullable:()=>zh,number:()=>Ia,object:()=>kh,objectUtil:()=>wi,oboolean:()=>Zh,onumber:()=>Fh,optional:()=>Lh,ostring:()=>Bh,pipeline:()=>qh,preprocess:()=>Uh,promise:()=>Mh,quotelessJson:()=>Dd,record:()=>Ih,set:()=>Rh,setErrorMap:()=>zd,strictObject:()=>Sh,string:()=>Ea,symbol:()=>ph,transformer:()=>Dh,tuple:()=>Eh,undefined:()=>mh,union:()=>Th,unknown:()=>_h,util:()=>G,void:()=>bh});var G;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(G||(G={}));var wi;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(wi||(wi={}));var R=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Fe=r=>{switch(typeof r){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(r)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(r)?R.array:r===null?R.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?R.promise:typeof Map<"u"&&r instanceof Map?R.map:typeof Set<"u"&&r instanceof Set?R.set:typeof Date<"u"&&r instanceof Date?R.date:R.object;default:return R.unknown}};var T=G.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Dd=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),ge=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};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(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};ge.create=r=>new ge(r);var Ld=(r,e)=>{let t;switch(r.code){case T.invalid_type:r.received===R.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case T.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,G.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:t=`Unrecognized key(s) in object: ${G.joinValues(r.keys,", ")}`;break;case T.invalid_union:t="Invalid input";break;case T.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${G.joinValues(r.options)}`;break;case T.invalid_enum_value:t=`Invalid enum value. Expected ${G.joinValues(r.options)}, received '${r.received}'`;break;case T.invalid_arguments:t="Invalid function arguments";break;case T.invalid_return_type:t="Invalid function return type";break;case T.invalid_date:t="Invalid date";break;case T.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:G.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case T.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case T.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case T.custom:t="Invalid input";break;case T.invalid_intersection_types:t="Intersection results could not be merged";break;case T.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case T.not_finite:t="Number must be finite";break;default:t=e.defaultError,G.assertNever(r)}return{message:t}},et=Ld;var va=et;function zd(r){va=r}function $r(){return va}var bn=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Ud=[];function A(r,e){let t=$r(),n=bn({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===et?void 0:et].filter(s=>!!s)});r.common.issues.push(n)}var ue=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return M;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return M;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}},M=Object.freeze({status:"aborted"}),Ot=r=>({status:"dirty",value:r}),he=r=>({status:"valid",value:r}),es=r=>r.status==="aborted",ts=r=>r.status==="dirty",yt=r=>r.status==="valid",Pr=r=>typeof Promise<"u"&&r instanceof Promise;var P;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));var Ae=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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}},ba=(r,e)=>{if(yt(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new ge(r.common.issues);return this._error=t,this._error}}};function q(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:c}=r;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??t??a.defaultError}},description:s}}var K=class{get description(){return this._def.description}_getType(e){return Fe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Fe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ue,ctx:{common:e.parent.common,data:e.data,parsedType:Fe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Pr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let 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:Fe(e)},s=this._parseSync({data:e,path:n.path,parent:n});return ba(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fe(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return yt(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>yt(n)?{value:n.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:Fe(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Pr(s)?s:Promise.resolve(s));return ba(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:T.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new Re({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ie.create(this,this._def)}nullable(){return Ke.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nt.create(this)}promise(){return bt.create(this,this._def)}or(e){return qt.create([this,e],this._def)}and(e){return Bt.create(this,e,this._def)}transform(e){return new Re({...q(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Ht({...q(this._def),innerType:this,defaultValue:t,typeName:D.ZodDefault})}brand(){return new wn({typeName:D.ZodBranded,type:this,...q(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Gt({...q(this._def),innerType:this,catchValue:t,typeName:D.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return kn.create(this,e)}readonly(){return Wt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qd=/^c[^\s-]{8,}$/i,Bd=/^[0-9a-z]+$/,Fd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zd=/^[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,Kd=/^[a-z0-9_-]{21}$/i,Vd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Hd=/^[-+]?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)?)??$/,Gd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Wd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ki,Jd=/^(?:(?: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])$/,Yd=/^(?:(?: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])$/,Xd=/^(([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]))$/,Qd=/^(([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])$/,eh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,th=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ka="((\\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])))",rh=new RegExp(`^${ka}$`);function Sa(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function nh(r){return new RegExp(`^${Sa(r)}$`)}function Ta(r){let e=`${ka}T${Sa(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function sh(r,e){return!!((e==="v4"||!e)&&Jd.test(r)||(e==="v6"||!e)&&Xd.test(r))}function ih(r,e){if(!Vd.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function oh(r,e){return!!((e==="v4"||!e)&&Yd.test(r)||(e==="v6"||!e)&&Qd.test(r))}var _t=class r extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.string,received:i.parsedType}),M}let n=new ue,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?A(s,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&A(s,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Gd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"email",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")ki||(ki=new RegExp(Wd,"u")),ki.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"emoji",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Zd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"uuid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Kd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"nanoid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")qd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Bd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid2",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Fd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ulid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),A(s,{validation:"url",code:T.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"regex",code:T.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Ta(i).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?rh.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?nh(i).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Hd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"duration",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?sh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ip",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?ih(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"jwt",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?oh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cidr",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?eh.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?th.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64url",code:T.invalid_string,message:i.message}),n.dirty()):G.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:T.invalid_string,...P.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...P.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...P.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...P.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...P.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...P.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...P.errToObj(t)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};_t.create=r=>new _t({checks:[],typeName:D.ZodString,coerce:r?.coerce??!1,...q(r)});function ah(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Nt=class r extends K{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)!==R.number){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.number,received:i.parsedType}),M}let n,s=new ue;for(let i of this._def.checks)i.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?ah(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_finite,message:i.message}),s.dirty()):G.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&G.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;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)}};Nt.create=r=>new Nt({checks:[],typeName:D.ZodNumber,coerce:r?.coerce||!1,...q(r)});var Mt=class r extends K{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)!==R.bigint)return this._getInvalidInput(e);let n,s=new ue;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):G.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return A(t,{code:T.invalid_type,expected:R.bigint,received:t.parsedType}),M}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:P.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}};Mt.create=r=>new Mt({checks:[],typeName:D.ZodBigInt,coerce:r?.coerce??!1,...q(r)});var Dt=class extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.boolean,received:n.parsedType}),M}return he(e.data)}};Dt.create=r=>new Dt({typeName:D.ZodBoolean,coerce:r?.coerce||!1,...q(r)});var Lt=class r extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.date,received:i.parsedType}),M}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_date}),M}let n=new ue,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):G.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:P.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Lt.create=r=>new Lt({checks:[],coerce:r?.coerce||!1,typeName:D.ZodDate,...q(r)});var Or=class extends K{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.symbol,received:n.parsedType}),M}return he(e.data)}};Or.create=r=>new Or({typeName:D.ZodSymbol,...q(r)});var zt=class extends K{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.undefined,received:n.parsedType}),M}return he(e.data)}};zt.create=r=>new zt({typeName:D.ZodUndefined,...q(r)});var Ut=class extends K{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.null,received:n.parsedType}),M}return he(e.data)}};Ut.create=r=>new Ut({typeName:D.ZodNull,...q(r)});var vt=class extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return he(e.data)}};vt.create=r=>new vt({typeName:D.ZodAny,...q(r)});var rt=class extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return he(e.data)}};rt.create=r=>new rt({typeName:D.ZodUnknown,...q(r)});var De=class extends K{_parse(e){let t=this._getOrReturnCtx(e);return A(t,{code:T.invalid_type,expected:R.never,received:t.parsedType}),M}};De.create=r=>new De({typeName:D.ZodNever,...q(r)});var Nr=class extends K{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.void,received:n.parsedType}),M}return he(e.data)}};Nr.create=r=>new Nr({typeName:D.ZodVoid,...q(r)});var nt=class r extends K{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==R.array)return A(t,{code:T.invalid_type,expected:R.array,received:t.parsedType}),M;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&(A(t,{code:o?T.too_big:T.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(A(t,{code:T.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(A(t,{code:T.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Ae(t,o,t.path,a)))).then(o=>ue.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Ae(t,o,t.path,a)));return ue.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:P.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:P.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:P.toString(t)}})}nonempty(e){return this.min(1,e)}};nt.create=(r,e)=>new nt({type:r,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...q(e)});function jr(r){if(r instanceof ye){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Ie.create(jr(n))}return new ye({...r._def,shape:()=>e})}else return r instanceof nt?new nt({...r._def,type:jr(r.element)}):r instanceof Ie?Ie.create(jr(r.unwrap())):r instanceof Ke?Ke.create(jr(r.unwrap())):r instanceof Ze?Ze.create(r.items.map(e=>jr(e))):r}var ye=class r extends K{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=G.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==R.object){let l=this._getOrReturnCtx(e);return A(l,{code:T.invalid_type,expected:R.object,received:l.parsedType}),M}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof De&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let d=i[l],p=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new Ae(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof De){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")a.length>0&&(A(s,{code:T.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of a){let p=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new Ae(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of c){let p=await d.key,v=await d.value;l.push({key:p,value:v,alwaysSet:d.alwaysSet})}return l}).then(l=>ue.mergeObjectSync(n,l)):ue.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:P.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of G.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of G.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return jr(this)}partial(e){let t={};for(let n of G.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of G.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Ie;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return xa(G.objectKeys(this.shape))}};ye.create=(r,e)=>new ye({shape:()=>r,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...q(e)});ye.strictCreate=(r,e)=>new ye({shape:()=>r,unknownKeys:"strict",catchall:De.create(),typeName:D.ZodObject,...q(e)});ye.lazycreate=(r,e)=>new ye({shape:r,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...q(e)});var qt=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new ge(a.ctx.common.issues));return A(t,{code:T.invalid_union,unionErrors:o}),M}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of n){let l={...t,common:{...t.common,issues:[]},parent:null},d=c._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new ge(c));return A(t,{code:T.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}};qt.create=(r,e)=>new qt({options:r,typeName:D.ZodUnion,...q(e)});var tt=r=>r instanceof Ft?tt(r.schema):r instanceof Re?tt(r.innerType()):r instanceof Zt?[r.value]:r instanceof Kt?r.options:r instanceof Vt?G.objectValues(r.enum):r instanceof Ht?tt(r._def.innerType):r instanceof zt?[void 0]:r instanceof Ut?[null]:r instanceof Ie?[void 0,...tt(r.unwrap())]:r instanceof Ke?[null,...tt(r.unwrap())]:r instanceof wn||r instanceof Wt?tt(r.unwrap()):r instanceof Gt?tt(r._def.innerType):[],rs=class r extends K{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.object)return A(t,{code:T.invalid_type,expected:R.object,received:t.parsedType}),M;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);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}):(A(t,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=tt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...q(n)})}};function Si(r,e){let t=Fe(r),n=Fe(e);if(r===e)return{valid:!0,data:r};if(t===R.object&&n===R.object){let s=G.objectKeys(e),i=G.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let c=Si(r[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(t===R.array&&n===R.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],c=Si(o,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===R.date&&n===R.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Bt=class extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(es(i)||es(o))return M;let a=Si(i.value,o.value);return a.valid?((ts(i)||ts(o))&&t.dirty(),{status:t.value,value:a.data}):(A(n,{code:T.invalid_intersection_types}),M)};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(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Bt.create=(r,e,t)=>new Bt({left:r,right:e,typeName:D.ZodIntersection,...q(t)});var Ze=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return A(n,{code:T.invalid_type,expected:R.array,received:n.parsedType}),M;if(n.data.length<this._def.items.length)return A(n,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&n.data.length>this._def.items.length&&(A(n,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ae(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>ue.mergeArray(t,o)):ue.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};Ze.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ze({items:r,typeName:D.ZodTuple,rest:null,...q(e)})};var ns=class r extends K{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!==R.object)return A(n,{code:T.invalid_type,expected:R.object,received:n.parsedType}),M;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Ae(n,a,n.path,a)),value:o._parse(new Ae(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ue.mergeObjectAsync(t,s):ue.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof K?new r({keyType:e,valueType:t,typeName:D.ZodRecord,...q(n)}):new r({keyType:_t.create(),valueType:e,typeName:D.ZodRecord,...q(t)})}},Mr=class extends K{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!==R.map)return A(n,{code:T.invalid_type,expected:R.map,received:n.parsedType}),M;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,c],l)=>({key:s._parse(new Ae(n,a,n.path,[l,"key"])),value:i._parse(new Ae(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return M;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return M;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}}}};Mr.create=(r,e,t)=>new Mr({valueType:e,keyType:r,typeName:D.ZodMap,...q(t)});var Dr=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return A(n,{code:T.invalid_type,expected:R.set,received:n.parsedType}),M;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(A(n,{code:T.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(A(n,{code:T.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(c){let l=new Set;for(let d of c){if(d.status==="aborted")return M;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((c,l)=>i._parse(new Ae(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:P.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:P.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Dr.create=(r,e)=>new Dr({valueType:r,minSize:null,maxSize:null,typeName:D.ZodSet,...q(e)});var ss=class r extends K{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.function)return A(t,{code:T.invalid_type,expected:R.function,received:t.parsedType}),M;function n(a,c){return bn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,$r(),et].filter(l=>!!l),issueData:{code:T.invalid_arguments,argumentsError:c}})}function s(a,c){return bn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,$r(),et].filter(l=>!!l),issueData:{code:T.invalid_return_type,returnTypeError:c}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof bt){let a=this;return he(async function(...c){let l=new ge([]),d=await a._def.args.parseAsync(c,i).catch(S=>{throw l.addIssue(n(c,S)),l}),p=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw l.addIssue(s(p,S)),l})})}else{let a=this;return he(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new ge([n(c,l.error)]);let d=Reflect.apply(o,this,l.data),p=a._def.returns.safeParse(d,i);if(!p.success)throw new ge([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ze.create(e).rest(rt.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Ze.create([]).rest(rt.create()),returns:t||rt.create(),typeName:D.ZodFunction,...q(n)})}},Ft=class extends K{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})}};Ft.create=(r,e)=>new Ft({getter:r,typeName:D.ZodLazy,...q(e)});var Zt=class extends K{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return A(t,{received:t.data,code:T.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};Zt.create=(r,e)=>new Zt({value:r,typeName:D.ZodLiteral,...q(e)});function xa(r,e){return new Kt({values:r,typeName:D.ZodEnum,...q(e)})}var Kt=class r extends K{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return A(t,{expected:G.joinValues(n),received:t.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return A(t,{received:t.data,code:T.invalid_enum_value,options:n}),M}return he(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Kt.create=xa;var Vt=class extends K{_parse(e){let t=G.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let s=G.objectValues(t);return A(n,{expected:G.joinValues(s),received:n.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=G.objectValues(t);return A(n,{received:n.data,code:T.invalid_enum_value,options:s}),M}return he(e.data)}get enum(){return this._def.values}};Vt.create=(r,e)=>new Vt({values:r,typeName:D.ZodNativeEnum,...q(e)});var bt=class extends K{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.promise&&t.common.async===!1)return A(t,{code:T.invalid_type,expected:R.promise,received:t.parsedType}),M;let n=t.parsedType===R.promise?t.data:Promise.resolve(t.data);return he(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};bt.create=(r,e)=>new bt({type:r,typeName:D.ZodPromise,...q(e)});var Re=class extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{A(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return M;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?M:c.status==="dirty"?Ot(c.value):t.value==="dirty"?Ot(c.value):c});{if(t.value==="aborted")return M;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?M:a.status==="dirty"?Ot(a.value):t.value==="dirty"?Ot(a.value):a}}if(s.type==="refinement"){let o=a=>{let c=s.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?M:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?M:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!yt(o))return M;let a=s.transform(o.value,i);if(a instanceof Promise)throw new 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(o=>yt(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):M);G.assertNever(s)}};Re.create=(r,e,t)=>new Re({schema:r,typeName:D.ZodEffects,effect:e,...q(t)});Re.createWithPreprocess=(r,e,t)=>new Re({schema:e,effect:{type:"preprocess",transform:r},typeName:D.ZodEffects,...q(t)});var Ie=class extends K{_parse(e){return this._getType(e)===R.undefined?he(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ie.create=(r,e)=>new Ie({innerType:r,typeName:D.ZodOptional,...q(e)});var Ke=class extends K{_parse(e){return this._getType(e)===R.null?he(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ke.create=(r,e)=>new Ke({innerType:r,typeName:D.ZodNullable,...q(e)});var Ht=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ht.create=(r,e)=>new Ht({innerType:r,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...q(e)});var Gt=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Pr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ge(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ge(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Gt.create=(r,e)=>new Gt({innerType:r,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...q(e)});var Lr=class extends K{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.nan,received:n.parsedType}),M}return{status:"valid",value:e.data}}};Lr.create=r=>new Lr({typeName:D.ZodNaN,...q(r)});var uh=Symbol("zod_brand"),wn=class extends K{_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}},kn=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?M:i.status==="dirty"?(t.dirty(),Ot(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?M:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:D.ZodPipeline})}},Wt=class extends K{_parse(e){let t=this._def.innerType._parse(e),n=s=>(yt(s)&&(s.value=Object.freeze(s.value)),s);return Pr(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Wt.create=(r,e)=>new Wt({innerType:r,typeName:D.ZodReadonly,...q(e)});function wa(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Ca(r,e={},t){return r?vt.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=wa(e,n),c=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=wa(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):vt.create()}var ch={object:ye.lazycreate},D;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(D||(D={}));var lh=(r,e={message:`Input not instance of ${r.name}`})=>Ca(t=>t instanceof r,e),Ea=_t.create,Ia=Nt.create,dh=Lr.create,hh=Mt.create,Aa=Dt.create,fh=Lt.create,ph=Or.create,mh=zt.create,gh=Ut.create,yh=vt.create,_h=rt.create,vh=De.create,bh=Nr.create,wh=nt.create,kh=ye.create,Sh=ye.strictCreate,Th=qt.create,xh=rs.create,Ch=Bt.create,Eh=Ze.create,Ih=ns.create,Ah=Mr.create,Rh=Dr.create,$h=ss.create,Ph=Ft.create,jh=Zt.create,Oh=Kt.create,Nh=Vt.create,Mh=bt.create,Dh=Re.create,Lh=Ie.create,zh=Ke.create,Uh=Re.createWithPreprocess,qh=kn.create,Bh=()=>Ea().optional(),Fh=()=>Ia().optional(),Zh=()=>Aa().optional(),Kh={string:(r=>_t.create({...r,coerce:!0})),number:(r=>Nt.create({...r,coerce:!0})),boolean:(r=>Dt.create({...r,coerce:!0})),bigint:(r=>Mt.create({...r,coerce:!0})),date:(r=>Lt.create({...r,coerce:!0}))};var Vh=M;var Ra=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),Ti=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(is.default.hostname()),jira:Ra.optional(),repos:k.record(k.object({path:k.string(),jira:Ra.optional(),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional()})).default({}),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional(),githubUsers:k.record(k.object({token:k.string().min(1),login:k.string().optional()})).default({}),deploy:k.object({enabled:k.boolean().default(!1)}).default({enabled:!1}),environments:k.record(k.object({secrets:k.record(k.string()).default({})})).default({}),claudeProfiles:k.record(k.object({configDir:k.string()})).default({}),claudeBin:k.string().default("claude"),agents:k.record(k.object({bin:k.string()})).default({}),jiraUsers:k.record(k.object({email:k.string().email(),apiToken:k.string().min(1)})).default({}),auditSchedules:k.array(k.object({repoName:k.string(),role:k.enum(["security","testing"]),intervalHours:k.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:k.number().int().min(10).max(600).default(30)});function ee(){let r=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(r)return r;let e=os.default.join(is.default.homedir(),".config","allwright"),t=os.default.join(is.default.homedir(),".config","ticketpilot");return!st.default.existsSync(e)&&st.default.existsSync(t)?t:e}function wt(){return os.default.join(ee(),"runner.json")}function ce(){let r=wt();if(!st.default.existsSync(r))return null;let e=JSON.parse(st.default.readFileSync(r,"utf8"));return Ti.parse(e)}function ie(r){let e=ee();st.default.mkdirSync(e,{recursive:!0,mode:448});let t=wt(),n=t+".tmp";st.default.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
237
|
+
`,{mode:384}),st.default.renameSync(n,t),st.default.chmodSync(t,384)}function as(r,e){return`${r}:${e}`}function Jt(r,e,t){return r.environments[as(e,t)]?.secrets??{}}function Q(){let r=ce();if(!r)throw new Error(`No runner config found at ${wt()}. Run \`allwright init\` first.`);return r}var us=require("node:child_process"),we=$(require("node:fs"),1),cs=$(require("node:path"),1);var Hh=new Set(["runner.log","runner.pid"]);function Gh(r){return we.default.readdirSync(r).filter(e=>!Hh.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function $a(r){let e=ee();if(!we.default.existsSync(e))throw new Error(`nothing to export \u2014 ${e} does not exist`);let t=Gh(e);if(!t.length)throw new Error(`nothing to export \u2014 ${e} is empty`);let n=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=cs.default.resolve(r||`ticketpilot-backup-${n}.tgz`);return we.default.writeFileSync(s,"",{mode:384}),(0,us.execFileSync)("tar",["-czf",s,"-C",e,...t]),we.default.chmodSync(s,384),{file:s,entries:t}}function Pa(r){let e=cs.default.resolve(r);if(!we.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let t=(0,us.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
|
|
238
|
+
`).filter(Boolean);for(let i of t)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import \u2014 unsafe path in archive: ${i}`);let n=ee(),s;we.default.existsSync(n)&&we.default.readdirSync(n).length&&(s=`${n}.bak-${Date.now()}`,we.default.renameSync(n,s)),we.default.mkdirSync(n,{recursive:!0,mode:448}),(0,us.execFileSync)("tar",["-xzf",e,"-C",n]);for(let i of we.default.readdirSync(n)){let o=cs.default.join(n,i);we.default.statSync(o).isFile()&&we.default.chmodSync(o,384)}return{restored:t.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var zr=$(require("node:fs"),1),kt=$(require("node:path"),1),ls=".ticketpilot-attachments",Wh=15*1024*1024,Jh=50*1024*1024,ja=20;function Oa(r,e){let t=kt.default.basename(r).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",n=t,s=1;for(;e.has(n);)n=`${s++}-${t}`;return e.add(n),n}async function Ur(r,e,t,n){if(!e.length)return"";let s=kt.default.join(t,ls);zr.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],a=0;for(let c of e){if(o.length>=ja){n("warn",`attachment cap reached (${ja} files) \u2014 skipping the rest`);break}if(c.size>Wh){n("warn",`skipping attachment "${c.filename}" \u2014 ${Qh(c.size)} MB exceeds the 15 MB limit`);continue}if(a+c.size>Jh){n("warn",`attachment size budget reached \u2014 skipping "${c.filename}" and the rest`);break}try{let l=await r.downloadAttachment(c.contentUrl),d=Oa(c.filename,i);zr.default.writeFileSync(kt.default.join(s,d),l),a+=l.length,o.push(`- ${ls}/${d} (${c.mimeType||"unknown type"}, ${xi(l.length)} KB)`),n("info",`Downloaded attachment "${c.filename}" (${xi(l.length)} KB)`)}catch(l){n("warn",`could not download attachment "${c.filename}": ${l instanceof Error?l.message:l}`)}}return o.length?`
|
|
238
239
|
|
|
239
240
|
Files attached to the Jira ticket, downloaded locally for this run. They are reference material and NOT part of the repository \u2014 never commit, copy, or edit them:
|
|
240
241
|
${o.join(`
|
|
241
242
|
`)}
|
|
242
|
-
Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(St(t),"")}function St(r){
|
|
243
|
+
Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(St(t),"")}function St(r){zr.default.rmSync(kt.default.join(r,ls),{recursive:!0,force:!0})}var Yh=4*1024*1024,Xh=16*1024*1024;function Na(r,e,t){let n=kt.default.join(r,ls,`chat-${e.replace(/[^\w-]/g,"")}`);if(!t.length)return{section:"",dir:n};zr.default.mkdirSync(n,{recursive:!0});let s=new Set,i=[],o=0,a=kt.default.relative(r,n);for(let l of t){let d=Buffer.from(l.contentBase64,"base64");if(d.length>Yh||o+d.length>Xh){i.push(`- (skipped "${l.name}" \u2014 over the upload size budget)`);continue}let p=Oa(l.name,s);zr.default.writeFileSync(kt.default.join(n,p),d),o+=d.length,i.push(`- ${a}/${p} (${xi(d.length)} KB)`)}return{section:`
|
|
243
244
|
|
|
244
245
|
The user attached file(s) with this message, staged locally for you. They are reference material and NOT part of the repository \u2014 never commit, copy, or edit them. If a ticket is created from this chat, these files are attached to it automatically, so reference them by filename instead of pasting their content:
|
|
245
246
|
${i.join(`
|
|
246
247
|
`)}
|
|
247
|
-
Read them with the Read tool; images can be viewed directly.`,dir:n}}var
|
|
248
|
+
Read them with the Read tool; images can be viewed directly.`,dir:n}}var xi=r=>Math.max(1,Math.round(r/1024)),Qh=r=>Math.round(r/(1024*1024)*10)/10;var it=$(require("node:fs"),1),Ci=$(require("node:path"),1);function Sn(){return Ci.default.join(ee(),"runner.pid")}function ds(){return Ci.default.join(ee(),"runner.log")}function Ma(){it.default.mkdirSync(ee(),{recursive:!0,mode:448});let r=it.default.openSync(ds(),"a",384);try{it.default.chmodSync(ds(),384)}catch{}return r}function qr(){let r=Sn();if(!it.default.existsSync(r))return null;let e=Number(it.default.readFileSync(r,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function Tn(r){try{return process.kill(r,0),!0}catch{return!1}}function Da(r){it.default.mkdirSync(ee(),{recursive:!0,mode:448}),it.default.writeFileSync(Sn(),String(r),{mode:384})}function La(r){qr()===r&&it.default.rmSync(Sn(),{force:!0})}var cu=$(Se(),1);async function lu(r,e){let t=await fetch(new URL("/api/runners/enroll",r.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:r.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:vs})});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`enrollment failed (${t.status}): ${i.slice(0,300)}`)}let n=cu.EnrollResponse.parse(await t.json()),s={...r,runnerId:n.runnerId,runnerToken:n.runnerToken};return ie(s),s}var vs="1.1.0";gr();var ku="Posted automatically by Allwright",Cp=["Posted automatically by TicketPilot"],Ge=r=>r.includes(ku)||Cp.some(e=>r.includes(e));var ze=class{constructor(e){this.auth=e}auth;headers(){return{Authorization:`Basic ${Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64")}`,Accept:"application/json","Content-Type":"application/json"}}async request(e,t,n){let s=new URL(t,this.auth.baseUrl).toString(),i=await fetch(s,{method:e,headers:this.headers(),body:n===void 0?void 0:JSON.stringify(n)});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Jira ${e} ${t} -> ${i.status}: ${o.slice(0,500)}`)}if(i.status!==204)return await i.json()}async myself(){return this.request("GET","/rest/api/3/myself")}async searchUsers(e,t=20){let n=await this.userSearch(e,t);return n.length||!e.includes("@")?n:this.userSearch(e.slice(0,e.indexOf("@")),t)}async userSearch(e,t){return e.trim()?(await this.request("GET",`/rest/api/3/user/search?query=${encodeURIComponent(e)}&maxResults=${t}`)??[]).filter(s=>s.accountId&&(s.accountType??"atlassian")==="atlassian").map(s=>({accountId:s.accountId,displayName:s.displayName??"(no name)",email:s.emailAddress??"",active:s.active??!0})):[]}async search(e,t=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:t,fields:["summary","components"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",components:(s.fields?.components??[]).map(i=>i.name??"").filter(Boolean)}))}async projectStatuses(e){let t=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),n=new Map;for(let i of t??[])for(let o of i.statuses??[])o.name&&!n.has(o.name)&&n.set(o.name,o.statusCategory?.key??"indeterminate");let s=i=>i==="new"?0:i==="done"?2:1;return[...n.entries()].sort((i,o)=>s(i[1])-s(o[1])).map(([i])=>i)}async searchEpics(e,t=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:`project = "${e}" AND issuetype = Epic AND statusCategory != Done ORDER BY created DESC`,maxResults:t,fields:["summary","status"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??""}))}async epicChildren(e,t=50){return((await this.request("POST","/rest/api/3/search/jql",{jql:`parent = "${e}" ORDER BY created ASC`,maxResults:t,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"",statusCategory:s.fields?.status?.statusCategory?.key??"indeterminate",labels:s.fields?.labels??[]}))}async searchBoard(e,t=100){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:t,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"(no status)",statusId:s.fields?.status?.id??"",labels:s.fields?.labels??[]}))}async boardColumns(e){try{let n=(await this.request("GET",`/rest/agile/1.0/board?projectKeyOrId=${encodeURIComponent(e)}`)).values?.[0]?.id;if(!n)return null;let i=((await this.request("GET",`/rest/agile/1.0/board/${n}/configuration`)).columnConfig?.columns??[]).filter(o=>(o.statuses??[]).length>0&&o.name).map(o=>({name:o.name,statusIds:(o.statuses??[]).map(a=>a.id??"").filter(Boolean)}));return i.length?i:null}catch{return null}}async getIssue(e){let t=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?fields=summary,description,labels,comment,status,attachment`),n;try{n=await this.listAllComments(e)}catch{n=t.fields.comment?.comments??[]}let s=n.map(o=>({id:o.id??"",author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null,created:o.created,body:wu(o.body)})),i=(t.fields.attachment??[]).filter(o=>o.id&&o.filename&&o.content).map(o=>({id:o.id,filename:o.filename,mimeType:o.mimeType??"",size:o.size??0,contentUrl:o.content}));return{key:t.key,summary:t.fields.summary??"",description:wu(t.fields.description),labels:t.fields.labels??[],status:t.fields.status?.name??"",comments:s,attachments:i}}async listAllComments(e){let t=await this.fetchCommentPage(e,0),n=t.total??t.comments.length;if(n<=t.comments.length)return t.comments;let s=Math.max(0,n-200),i=s===0?[...t.comments]:[];for(;i.length<Math.min(n,200);){let o=await this.fetchCommentPage(e,s+i.length);if(!o.comments.length)break;i.push(...o.comments)}return i.slice(-200)}async fetchCommentPage(e,t){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${t}&maxResults=100`);return{comments:n.comments??[],total:n.total}}async downloadAttachment(e){let t=await fetch(e,{headers:this.headers()});if(!t.ok)throw new Error(`attachment download failed: ${t.status}`);return Buffer.from(await t.arrayBuffer())}async lastEnteredStatus(e,t){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?expand=changelog&fields=status`),s=t.toLowerCase(),i=null;for(let o of n.changelog?.histories??[])(o.items??[]).some(c=>(c.field==="status"||c.fieldId==="status")&&(c.toString??"").toLowerCase()===s)&&(!i||new Date(o.created)>new Date(i.at))&&(i={at:o.created,author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null});return i}async createIssue(e,t,n,s="Task",i){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:t.slice(0,250),description:Gi(n),...i?{parent:{key:i}}:{}}})).key}}async addAttachments(e,t){if(!t.length)return;let n=new FormData;for(let a of t)n.append("file",new Blob([new Uint8Array(a.content)]),a.name.slice(0,255));let s=new URL(`/rest/api/3/issue/${encodeURIComponent(e)}/attachments`,this.auth.baseUrl).toString(),i=Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64"),o=await fetch(s,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","X-Atlassian-Token":"no-check"},body:n});if(!o.ok)throw new Error(`Jira attachment upload failed: HTTP ${o.status}`)}async addTriggerComment(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Gi(t)})}async addComment(e,t){let n=`${t}
|
|
248
249
|
|
|
249
250
|
---
|
|
250
|
-
_${
|
|
251
|
+
_${ku} \u2014 never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Gi(n)})}async editLabels(e,t){let n=[...(t.add??[]).map(s=>({add:s})),...(t.remove??[]).map(s=>({remove:s}))];await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{update:{labels:n}})}async getTransitions(e){return((await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`)).transitions??[]).map(n=>({id:n.id,name:n.name}))}async transition(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{transition:{id:t}})}async transitionByName(e,t){let s=(await this.getTransitions(e)).find(i=>i.name.toLowerCase()===t.toLowerCase());return s?(await this.transition(e,s.id),!0):!1}};function wu(r){if(!r)return"";let e=[],t=n=>{n.text&&e.push(n.text),n.type==="hardBreak"&&e.push(`
|
|
251
252
|
`);for(let s of n.content??[])t(s);n.type&&["paragraph","heading","listItem","codeBlock","blockquote"].includes(n.type)&&e.push(`
|
|
252
253
|
`)};return t(r),e.join("").replace(/\n{3,}/g,`
|
|
253
254
|
|
|
254
|
-
`).trim()}function
|
|
255
|
+
`).trim()}function Gi(r){let e=r.replace(/\r\n/g,`
|
|
255
256
|
`).split(`
|
|
256
|
-
`),t=[],n=0,s=i=>{let o=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g,
|
|
257
|
-
`)||" "}]});continue}let a=i.match(/^(#{1,6})\s+(.*)$/);if(a){t.push({type:"heading",attrs:{level:a[1].length},content:s(a[2])}),n++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let p=[];for(;n<e.length;){let v=e[n].match(/^\s*[-*]\s+(.*)$/);if(!v)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(v[1])}]}),n++}t.push({type:"bulletList",content:p});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let p=[];for(;n<e.length;){let v=e[n].match(/^\s*\d+[.)]\s+(.*)$/);if(!v)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(v[1])}]}),n++}t.push({type:"orderedList",content:p});continue}let d=[i];for(n++;n<e.length&&e[n].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[n]);)d.push(e[n]),n++;t.push({type:"paragraph",content:s(d.join(" "))})}return{type:"doc",version:1,content:t}}function
|
|
257
|
+
`),t=[],n=0,s=i=>{let o=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g,c=0,l;for(;(l=a.exec(i))!==null;){l.index>c&&o.push({type:"text",text:i.slice(c,l.index)});let d=l[0];d.startsWith("**")?o.push({type:"text",text:d.slice(2,-2),marks:[{type:"strong"}]}):o.push({type:"text",text:d.slice(1,-1),marks:[{type:"code"}]}),c=l.index+d.length}return c<i.length&&o.push({type:"text",text:i.slice(c)}),o.length?o:[{type:"text",text:" "}]};for(;n<e.length;){let i=e[n];if(i.trim()===""){n++;continue}let o=i.match(/^```(\w*)\s*$/);if(o){let p=[];for(n++;n<e.length&&!/^```\s*$/.test(e[n]);)p.push(e[n]),n++;n++,t.push({type:"codeBlock",attrs:o[1]?{language:o[1]}:{},content:[{type:"text",text:p.join(`
|
|
258
|
+
`)||" "}]});continue}let a=i.match(/^(#{1,6})\s+(.*)$/);if(a){t.push({type:"heading",attrs:{level:a[1].length},content:s(a[2])}),n++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let p=[];for(;n<e.length;){let v=e[n].match(/^\s*[-*]\s+(.*)$/);if(!v)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(v[1])}]}),n++}t.push({type:"bulletList",content:p});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let p=[];for(;n<e.length;){let v=e[n].match(/^\s*\d+[.)]\s+(.*)$/);if(!v)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(v[1])}]}),n++}t.push({type:"orderedList",content:p});continue}let d=[i];for(n++;n<e.length&&e[n].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[n]);)d.push(e[n]),n++;t.push({type:"paragraph",content:s(d.join(" "))})}return{type:"doc",version:1,content:t}}function Su(r,e,t){let n=r.repos[e]?.jira??r.jira;if(!n)return{kind:"legacy"};let s=t.trim().toLowerCase();if(!s)return{kind:"legacy"};if(s===n.email.toLowerCase())return{kind:"self"};let i=r.jiraUsers[s];return i?{kind:"user",creds:{baseUrl:n.baseUrl,email:i.email,apiToken:i.apiToken}}:{kind:"missing",error:`Jira actions from Allwright post under YOUR OWN Atlassian identity, and no Jira credential is set up for ${s} on the runner yet. Ask your admin to run this on the runner machine:
|
|
258
259
|
|
|
259
260
|
allwright jira user-add ${s}
|
|
260
261
|
|
|
261
|
-
It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately \u2014 then just retry this action.`}}function
|
|
262
|
+
It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately \u2014 then just retry this action.`}}function Cs(r,e,t){let n=(t??"").trim().toLowerCase(),s=n?r.githubUsers[n]?.token:void 0;if(s)return{token:s,source:"user"};let i=r.repos[e]?.github?.token;return i?{token:i,source:"repo"}:r.github?.token?{token:r.github.token,source:"global"}:null}function At(r,e){return r.repos[e]?.github?.token??r.github?.token??null}function Tu(r,e){let t=[r.jira,...Object.values(r.repos).map(a=>a.jira)].filter(a=>!!a),n=new Set(t.map(a=>a.email.toLowerCase())),s=!!r.github?.token||Object.values(r.repos).some(a=>a.github?.token),i=r.github?.login??Object.values(r.repos).find(a=>a.github?.login)?.github?.login??"",o=e.map(a=>{let c=a.trim().toLowerCase(),l=r.jiraUsers[c]?"own":n.has(c)?"runner-account":"missing",d=l==="own"?r.jiraUsers[c].email:l==="runner-account"?c:"",p=r.githubUsers[c]?"own":s?"shared":"missing",v=p==="own"?r.githubUsers[c].login??"":p==="shared"?i:"";return{email:c,jira:l,jiraAs:d,github:p,githubAs:v}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var $n=require("node:child_process"),Xr=$(require("node:fs"),1),Wi=$(require("node:os"),1),Ji=$(require("node:path"),1),Es="allwright",xu=`/etc/systemd/system/${Es}.service`,Ep="ticketpilot-runner";function Yi(){let r=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=r||Wi.default.userInfo().username,t=r?Ji.default.join("/home",r):Wi.default.homedir();return{nodePath:process.execPath,scriptPath:Xr.default.realpathSync(process.argv[1]),user:e,home:t}}function Xi(r){let e=Ji.default.dirname(r.nodePath);return`[Unit]
|
|
262
263
|
Description=Allwright runner
|
|
263
264
|
After=network-online.target
|
|
264
265
|
|
|
@@ -273,8 +274,8 @@ RestartSec=5
|
|
|
273
274
|
|
|
274
275
|
[Install]
|
|
275
276
|
WantedBy=multi-user.target
|
|
276
|
-
`}function
|
|
277
|
-
`+t);return}
|
|
277
|
+
`}function Cu(){return process.platform==="linux"&&Xr.default.existsSync("/run/systemd/system")}function Eu(r){if(!Cu())throw new Error(process.platform==="win32"?"Windows service install isn't built in yet \u2014 use NSSM: nssm install allwright <node> <this script> start --foreground":"no systemd on this machine \u2014 run `allwright start` (background mode) instead");let e=Yi(),t=Xi(e);if(typeof process.getuid=="function"&&process.getuid()!==0){r.info("Root is needed to write the unit. Re-run as:"),r.info(' sudo env "PATH=$PATH" allwright service install'),r.info("(the env PATH part matters when node is installed via nvm \u2014 plain sudo can't find it)"),r.info(""),r.info(`This is exactly what it will write to ${xu}:`),r.info(`
|
|
278
|
+
`+t);return}Xr.default.writeFileSync(xu,t),(0,$n.execFileSync)("systemctl",["daemon-reload"]),(0,$n.execFileSync)("systemctl",["enable","--now",Es]),r.info(`Installed and started (runs as ${e.user}, survives reboots).`),r.info(`Watch it: journalctl -u ${Es} -f`),r.info("Status: allwright service status")}function Iu(r){if(!Cu())throw new Error("no systemd on this machine");if(typeof process.getuid=="function"&&process.getuid()!==0)throw new Error("root is needed \u2014 run: sudo allwright service uninstall");for(let e of[Es,Ep]){try{(0,$n.execFileSync)("systemctl",["disable","--now",e])}catch{}let t=`/etc/systemd/system/${e}.service`;Xr.default.existsSync(t)&&Xr.default.rmSync(t)}(0,$n.execFileSync)("systemctl",["daemon-reload"]),r.info("Service removed. The runner config and credentials were not touched.")}var Au=$(Se(),1);function Ru(r){return r.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(Au.NEEDS_INPUT_LABEL))}function $u(r,e,t){let n=t.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
|
|
278
279
|
${i.replace(/\n+/g," ")}`:""}`}).join(`
|
|
279
280
|
`);return`You are looking at this repository to help sequence work on the Jira epic ${r} ("${e}"). These child tickets are still pending:
|
|
280
281
|
|
|
@@ -285,9 +286,9 @@ Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1)
|
|
|
285
286
|
Answer with ONLY a fenced json block, nothing after it:
|
|
286
287
|
\`\`\`json
|
|
287
288
|
{"issueKey": "<one of the keys above>", "reason": "<2-3 sentences: why this one first, and what it unblocks>"}
|
|
288
|
-
\`\`\``}function
|
|
289
|
+
\`\`\``}function Pu(r,e){let n=r.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)?.[1]??r.match(/\{[\s\S]*"issueKey"[\s\S]*?\}/)?.[0];if(!n)return{error:"the agent's answer contained no JSON recommendation"};try{let s=JSON.parse(n),i=typeof s.issueKey=="string"?s.issueKey.trim():"",o=typeof s.reason=="string"?s.reason.trim():"";return e.includes(i)?{issueKey:i,reason:o||"(no reasoning given)"}:{error:`the agent recommended "${i}", which is not a pending child of this epic`}}catch{return{error:"the agent's JSON recommendation did not parse"}}}var oo=require("node:crypto"),uc=$(require("node:fs"),1);var Qi=$(require("node:fs"),1),ju=$(require("node:os"),1),Is=$(require("node:path"),1),Ou=require("node:child_process"),Nu=$(require("node:readline"),1),Mu=$(Se(),1),Ip={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Ap(r){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=r??Is.default.join(ju.default.homedir(),".claude");try{if(Qi.default.existsSync(Is.default.join(e,".credentials.json"))||Qi.default.existsSync(Is.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function Rp(r){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",Ip[r.mode].join(","),"--max-turns",String(r.maxTurns??60),...r.model?["--model",r.model]:[],...r.resume?["--resume",r.sessionId]:["--session-id",r.sessionId]],t=Ap(r.configDir);return t!=="unknown"&&r.onLog("info",t==="subscription"?"Billing: Claude subscription \u2014 costs shown are notional list prices, not money charged":"Billing: Anthropic API key \u2014 costs shown are actual metered spend"),new Promise(n=>{let s=(0,Ou.spawn)(r.bin,e,{cwd:r.repoPath,env:r.configDir?{...process.env,CLAUDE_CONFIG_DIR:r.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,billingMode:t==="subscription"?"subscription":t==="API key"?"api":"unknown"},o=!1,a=()=>{o||(o=!0,clearTimeout(c),n(i))},c=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${r.timeoutSeconds}s wall-clock limit`,r.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},r.timeoutSeconds*1e3);s.stdin.write(r.prompt),s.stdin.end(),Nu.default.createInterface({input:s.stdout}).on("line",p=>{if(!p.trim())return;let v;try{v=JSON.parse(p)}catch{r.onLog("agent",p.slice(0,1e3));return}if(v.type==="system"&&v.subtype==="init")i.model=typeof v.model=="string"?v.model:void 0,r.onLog("info",`Claude Code session started (model: ${v.model??"default"})`);else if(v.type==="assistant"){for(let S of v.message?.content??[])if(S.type==="text"&&S.text?.trim())r.onLog("agent",S.text.trim().slice(0,4e3));else if(S.type==="tool_use"){let x=JSON.stringify(S.input??{}).slice(0,300);r.onLog("info",`tool ${S.name} ${x}`)}}else v.type==="result"&&(i.costUsd=Number(v.total_cost_usd??0),i.inputTokens=Number(v.usage?.input_tokens??0),i.outputTokens=Number(v.usage?.output_tokens??0),v.subtype==="success"&&!v.is_error?(i.ok=!0,i.resultText=String(v.result??"")):v.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${r.maxTurns??60}-turn limit before finishing`):(i.error=String(v.result??v.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account \u2014 the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let d="";s.stderr.on("data",p=>{d=(d+p.toString()).slice(-2e3)}),s.on("error",p=>{i.error=`failed to start ${r.bin}: ${p.message}`,r.onLog("error",i.error),a()}),s.on("close",p=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${p}${d?`: ${d.slice(-500)}`:""}`),a()})})}var Ue={id:"claude-code",displayName:"Claude Code",capabilities:Mu.REGISTERED_AGENTS.find(r=>r.id==="claude-code").capabilities,run:Rp};var As=$(Se(),1),$p={security:"You are a security auditor. You can READ this repository; you can never run or change anything. Audit it against the knowledge packs below and report real, exploitable-here problems \u2014 not checklist theatre.",testing:"You are a test-coverage auditor. You can READ this repository (code and tests); you can never run anything. Find what is untested and fragile against the knowledge packs below \u2014 gaps that would actually bite this product, not generic coverage philosophy.",architecture:"You are a software architecture auditor. You can READ this repository; you can never run or change anything. Judge whether it is structurally HEALTHY for what it is trying to be, against the knowledge packs below \u2014 real structural pain for this team, not textbook purity."};function Lu(r,e,t,n={}){let s=e.map(c=>`### Pack: ${c.name}
|
|
289
290
|
|
|
290
|
-
${
|
|
291
|
+
${c.content}`).join(`
|
|
291
292
|
|
|
292
293
|
`),i=t.trim()?`
|
|
293
294
|
|
|
@@ -305,7 +306,7 @@ Read whatever surrounding code you need for context, but every finding must be a
|
|
|
305
306
|
|
|
306
307
|
${n.testResults}
|
|
307
308
|
|
|
308
|
-
Fold what these results show \u2014 failures, flaky exits, suspiciously green suites \u2014 into your findings with the rest of the audit.`:"";return`${
|
|
309
|
+
Fold what these results show \u2014 failures, flaky exits, suspiciously green suites \u2014 into your findings with the rest of the audit.`:"";return`${$p[r]}
|
|
309
310
|
|
|
310
311
|
Knowledge below is LAYERED: global (product) -> org (this company) -> project (this repo). More specific levels OVERRIDE general ones; entries referencing a rule id (SEC-001 style) modify or disable that rule.
|
|
311
312
|
|
|
@@ -319,7 +320,7 @@ Explore the repository first \u2014 entry points, routes, storage, tests \u2014
|
|
|
319
320
|
"evidence": [{"file": "<repo-relative path>", "line": <number, omit if n/a>, "note": "<what is there>"}],
|
|
320
321
|
"fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
|
|
321
322
|
\`\`\`
|
|
322
|
-
Rules: every finding needs at least one evidence file you actually read \u2014 findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`}function
|
|
323
|
+
Rules: every finding needs at least one evidence file you actually read \u2014 findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`}function zu(r){let t=r.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??r.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!t)return{error:"the agent's report contained no JSON block"};let n;try{n=JSON.parse(t)}catch{return{error:"the agent's JSON report did not parse"}}if(!Array.isArray(n.findings))return{error:"the report has no findings array"};let s=[],i=0,o=new Set;for(let a of n.findings.slice(0,25)){let c=Pp(a),l=c?As.AuditFinding.safeParse(c):null;if(!l?.success){i++;continue}let d=l.data.id;for(;o.has(d);)d=`${d}-2`;o.add(d),s.push({...l.data,id:d})}return{summary:typeof n.summary=="string"?n.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function Pp(r){if(typeof r!="object"||r===null)return null;let e=r,t=typeof e.severity=="string"?e.severity.toLowerCase():"",n=Array.isArray(e.evidence)?e.evidence.filter(i=>typeof i=="object"&&i!==null).map(i=>({file:typeof i.file=="string"?i.file:"",...Du(i.line)?{line:Du(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:jp(typeof e.id=="string"&&e.id?e.id:String(e.title??"")),ruleId:/^[A-Z]{2,8}-\d{1,4}$/.test(s)?s:"",title:typeof e.title=="string"?e.title.slice(0,200):"",severity:As.AuditSeverity.options.includes(t)?t:void 0,area:typeof e.area=="string"?e.area.slice(0,60):"",evidence:n,fix:typeof e.fix=="string"?e.fix.slice(0,2e3):""}}function Du(r){let e=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function jp(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}var Pn=$(require("node:fs"),1),eo=$(require("node:path"),1),Uu=$(Se(),1);var Op=20;function qu(){return eo.default.join(ee(),"audits.json")}function jn(){try{return{byProject:JSON.parse(Pn.default.readFileSync(qu(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function Bu(r){let e=qu();Pn.default.mkdirSync(eo.default.dirname(e),{recursive:!0,mode:448});let t=e+".tmp";Pn.default.writeFileSync(t,JSON.stringify(r,null,2),{mode:384}),Pn.default.renameSync(t,e)}function Fu(r,e){let t=jn(),n=t.byProject[r]??[];n.unshift(Uu.AuditRecord.parse(e)),t.byProject[r]=n.slice(0,Op),Bu(t)}function Zu(r){return(jn().byProject[r]??[]).map(e=>{let t={};for(let n of e.findings)t[n.severity]=(t[n.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:t}})}function to(r,e,t){let n=jn(),i=(n.byProject[r]??[]).find(a=>a.id===e);if(!i)return null;i.ticketed??={},i.verdicts??={},i.lessonsWritten??=[];let o=new Set(i.findings.map(a=>a.id));t.selected&&(i.review={selected:t.selected.filter(a=>o.has(a)),updatedAt:new Date().toISOString()});for(let a of t.ticketed??[])o.has(a.findingId)&&(i.ticketed={...i.ticketed,[a.findingId]:a.issueKey});for(let a of t.verdicts??[])o.has(a.findingId)&&(i.verdicts={...i.verdicts,[a.findingId]:{verdict:a.verdict,note:a.note,by:t.verdictBy??"",at:new Date().toISOString()}});for(let a of t.markLessonsWritten??[])o.has(a)&&!i.lessonsWritten.includes(a)&&i.lessonsWritten.push(a);return Bu(n),i}function Ku(r,e){return(jn().byProject[r]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function Vu(r,e){return(jn().byProject[r]??[]).find(t=>t.id===e)??null}gr();var pe=$(require("node:fs"),1),We=$(require("node:path"),1),Gu=$(Se(),1);var Np=`# Security baseline \u2014 what to check in any repo
|
|
323
324
|
|
|
324
325
|
Every rule has a stable id. Findings must cite the id they violate.
|
|
325
326
|
|
|
@@ -362,7 +363,7 @@ Every rule has a stable id. Findings must cite the id they violate.
|
|
|
362
363
|
- **SEC-042** TLS/redirect handling that downgrades to http.
|
|
363
364
|
|
|
364
365
|
Prioritize by real exploitability in THIS codebase, not by rule order.
|
|
365
|
-
`,
|
|
366
|
+
`,Mp=`# Test gaps \u2014 what to check in any repo
|
|
366
367
|
|
|
367
368
|
Every rule has a stable id. Findings must cite the id they violate.
|
|
368
369
|
|
|
@@ -392,7 +393,7 @@ Every rule has a stable id. Findings must cite the id they violate.
|
|
|
392
393
|
flaky suspects.
|
|
393
394
|
|
|
394
395
|
Report the GAP and why it is risky here, not generic coverage philosophy.
|
|
395
|
-
`,
|
|
396
|
+
`,Dp=`# GDPR readiness \u2014 data-protection audit for repos with EU exposure
|
|
396
397
|
|
|
397
398
|
FIRST decide exposure: if this product clearly has no EU users, no personal
|
|
398
399
|
data, or is a purely static/internal tool, say so in ONE summary sentence and
|
|
@@ -436,7 +437,7 @@ rules below. Cite the rule id AND map the area to the closest GDPR article
|
|
|
436
437
|
|
|
437
438
|
Severity: many users' data exposed or a missing legal-basis mechanism is
|
|
438
439
|
high/critical; hygiene and documentation gaps are medium/low.
|
|
439
|
-
`,
|
|
440
|
+
`,Lp=`# Architecture health \u2014 is this repository structurally sound?
|
|
440
441
|
|
|
441
442
|
Every rule has a stable id. Findings must cite the id they violate. Judge
|
|
442
443
|
against what THIS codebase is trying to be (a static site does not need
|
|
@@ -475,20 +476,20 @@ deviations.
|
|
|
475
476
|
|
|
476
477
|
Summarize with an overall verdict: is this repository HEALTHY for its
|
|
477
478
|
purpose, and what are the 2-3 structural moves with the best payoff?
|
|
478
|
-
`,
|
|
479
|
+
`,Hu={security:[{name:"baseline.md",content:Np},{name:"gdpr.md",content:Dp}],testing:[{name:"test-gaps.md",content:Mp}],architecture:[{name:"architecture-health.md",content:Lp}]},zp=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function ro(r){return We.default.join(ee(),"knowledge",r)}function Wu(r,e){return We.default.join(r,".ticketpilot","knowledge",`${e}.md`)}function no(r,e){return We.default.join(r,".ticketpilot","lessons",`${e}.md`)}function Ju(r,e){let t=[],n=ro(r),s=[];if(pe.default.existsSync(n)){for(let c of pe.default.readdirSync(n)){if(!c.endsWith(".md"))continue;let l=We.default.join(n,c),d=pe.default.readFileSync(l,"utf8");if(zp.some(p=>d.includes(p))&&Hu[r].map(v=>v.name).includes(c)&&!d.includes("SEC-0")&&!d.includes("TEST-0")&&!d.includes("GDPR-0")){pe.default.rmSync(l);continue}s.push(c)}s.sort()}let i=new Set(s);for(let c of Hu[r])i.has(c.name)||t.push({level:"global",source:"pack",name:c.name,content:c.content,editable:!1});for(let c of s)t.push({level:"org",source:"pack",name:c,content:pe.default.readFileSync(We.default.join(n,c),"utf8").slice(0,3e4),editable:!0});let o=Wu(e,r);pe.default.existsSync(o)&&t.push({level:"project",source:"pack",name:`${r}.md`,content:pe.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let a=no(e,r);return pe.default.existsSync(a)&&t.push({level:"project",source:"lessons",name:`${r}.md`,content:pe.default.readFileSync(a,"utf8").slice(0,2e4),editable:!0}),t}function Yu(r,e){let t=Ju(r,e);return{packs:t.filter(n=>n.source==="pack").map(n=>({name:`${n.level}/${n.name}`,content:n.content})),lessons:t.find(n=>n.source==="lessons")?.content??"",layers:t}}function so(r,e,t,n="project"){let s=n==="org"?We.default.join(ro(e),"org-lessons.md"):no(r,e);pe.default.mkdirSync(We.default.dirname(s),{recursive:!0});let i=pe.default.existsSync(s)?"":`# ${e} lessons (${n} level)
|
|
479
480
|
|
|
480
481
|
Human-confirmed corrections and rules. Every ${e} audit reads this FIRST. Reference rule ids (SEC-001 style) when overriding a rule.
|
|
481
482
|
|
|
482
483
|
`;pe.default.appendFileSync(s,i+t.trimEnd()+`
|
|
483
484
|
|
|
484
|
-
`)}function
|
|
485
|
+
`)}function Xu(r,e,t,n){let s=new Date().toISOString().slice(0,10),i=r.evidence[0]?` (${r.evidence[0].file}${r.evidence[0].line?`:${r.evidence[0].line}`:""})`:"",o=r.ruleId?` \xB7 rule ${r.ruleId}`:"";return`## ${s} \xB7 ${e}${o} \xB7 ${r.title}${i}
|
|
485
486
|
Finding \`${r.id}\` [${r.severity}] was marked **${e}**`+(n?` by ${n}`:"")+`.${t?` Reason: ${t}`:""}
|
|
486
|
-
`+(e==="false-positive"?"Do not raise this class of finding here again unless the code meaningfully changes.":"Known and accepted \u2014 do not re-raise; mention only if its risk materially grows.")}function
|
|
487
|
-
${r.trim()}`}function
|
|
488
|
-
`)){let s=n.trim();!s||s.startsWith("#")||e.push(s)}return e.slice(0,10)}async function
|
|
489
|
-
[killed: timed out]`},s);l.on("close",S=>{clearTimeout(v),
|
|
487
|
+
`+(e==="false-positive"?"Do not raise this class of finding here again unless the code meaningfully changes.":"Known and accepted \u2014 do not re-raise; mention only if its risk materially grows.")}function Qu(r,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
|
|
488
|
+
${r.trim()}`}function ec(r){let e=[];for(let t of Gu.AuditRole.options)for(let n of Ju(t,r))e.push({role:t,...n});return e}function tc(r,e,t,n,s,i){if(!/^[a-zA-Z0-9._-]+\.md$/.test(s))throw new Error("file name must be a simple .md name");let o=t==="org"?We.default.join(ro(e),s):n==="lessons"?no(r,e):Wu(r,e);pe.default.mkdirSync(We.default.dirname(o),{recursive:!0}),pe.default.writeFileSync(o,i,{mode:t==="org"?384:420})}var io=()=>new Date().toISOString(),m={info:r=>console.log(`${io()} [info] ${r}`),warn:r=>console.warn(`${io()} [warn] ${r}`),error:r=>console.error(`${io()} [error] ${r}`)};var rc=require("node:child_process"),nc=$(require("node:fs"),1),sc=$(require("node:path"),1);function ic(r){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let t=sc.default.join(r,e);if(nc.default.existsSync(t))return t}return null}function oc(r){let e=[];for(let t of r.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g))for(let n of t[1].split(`
|
|
489
|
+
`)){let s=n.trim();!s||s.startsWith("#")||e.push(s)}return e.slice(0,10)}async function ac(r,e,t={}){let n=[],s=t.perCommandTimeoutMs??6e5;for(let i of e){t.onProgress?.(`running: ${i}`);let o=Date.now(),a=await new Promise(c=>{let l=(0,rc.spawn)("bash",["-lc",i],{cwd:r,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),d="",p=S=>{d+=S.toString(),d.length>2e5&&(d=d.slice(-1e5))};l.stdout.on("data",p),l.stderr.on("data",p);let v=setTimeout(()=>{l.kill("SIGKILL"),d+=`
|
|
490
|
+
[killed: timed out]`},s);l.on("close",S=>{clearTimeout(v),c({command:i,exitCode:S??-1,durationMs:Date.now()-o,tail:d.slice(-4e3)})}),l.on("error",S=>{clearTimeout(v),c({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(S)})})});t.onProgress?.(`exit ${a.exitCode} in ${Math.round(a.durationMs/1e3)}s: ${i}`),n.push(a)}return n}async function Qr(r){let{packs:e,lessons:t}=Yu(r.role,r.repoPath);if(!e.length)return{ok:!1,error:`no knowledge packs found for the ${r.role} role \u2014 add markdown files under ~/.config/ticketpilot/knowledge/${r.role}/ on the runner`};let n="";if(r.scope.kind==="ticket"&&r.scope.ref){let d=r.scope.ref,p="";try{let S=await r.jira.getIssue(d);p=`Ticket ${d}: ${S.summary}
|
|
490
491
|
|
|
491
|
-
${S.description}`.slice(0,4e3)}catch{p=`Ticket ${d} (could not fetch its text from Jira).`}let v=await
|
|
492
|
+
${S.description}`.slice(0,4e3)}catch{p=`Ticket ${d} (could not fetch its text from Jira).`}let v=await Fi(r.repoPath,d).catch(()=>null);if(v){let{base:S,stat:x,diff:w}=await xs(r.repoPath,v).catch(()=>({base:"",stat:"",diff:""}));n=`${p}
|
|
492
493
|
|
|
493
494
|
Its implementation branch \`${v}\` vs \`${S}\`:
|
|
494
495
|
\`\`\`
|
|
@@ -497,93 +498,93 @@ ${x}\`\`\`
|
|
|
497
498
|
${w}
|
|
498
499
|
\`\`\``}else n=`${p}
|
|
499
500
|
|
|
500
|
-
No implementation branch found for ${d} \u2014 audit the parts of the codebase this ticket touches or would touch.`}else if(r.scope.kind==="branch"&&r.scope.ref){let{base:d,stat:p,diff:v}=await
|
|
501
|
+
No implementation branch found for ${d} \u2014 audit the parts of the codebase this ticket touches or would touch.`}else if(r.scope.kind==="branch"&&r.scope.ref){let{base:d,stat:p,diff:v}=await xs(r.repoPath,r.scope.ref);n=`The diff of \`${r.scope.ref}\` vs \`${d}\`:
|
|
501
502
|
\`\`\`
|
|
502
503
|
${p}\`\`\`
|
|
503
504
|
\`\`\`diff
|
|
504
505
|
${v}
|
|
505
|
-
\`\`\``}let s,i;if(r.role==="testing"){let d=
|
|
506
|
+
\`\`\``}let s,i;if(r.role==="testing"){let d=ic(r.repoPath),p=d?oc(uc.default.readFileSync(d,"utf8")):[];p.length&&(m.info(`Audit (testing): executing ${p.length} TEST.md command(s)`),i=await ac(r.repoPath,p,{onProgress:v=>m.info(`[test-run] ${v}`)}),s=i.map(v=>`$ ${v.command}
|
|
506
507
|
(exit ${v.exitCode}, ${Math.round(v.durationMs/1e3)}s)
|
|
507
508
|
${v.tail.slice(-2e3)}`).join(`
|
|
508
509
|
|
|
509
510
|
---
|
|
510
511
|
|
|
511
|
-
`))}let o=r.model||"claude-fable-5",a=await Ue.run({repoPath:r.repoPath,prompt:
|
|
512
|
-
`,{mode:384}),me.default.renameSync(t,r),me.default.chmodSync(r,384)}function
|
|
512
|
+
`))}let o=r.model||"claude-fable-5",a=await Ue.run({repoPath:r.repoPath,prompt:Lu(r.role,e,t,{scopeNote:n,testResults:s}),timeoutSeconds:480,bin:r.claudeBin,mode:"read_only",maxTurns:120,sessionId:(0,oo.randomUUID)(),model:o,onLog:(d,p)=>{d==="agent"&&m.info(`[audit:${r.role}] ${p.slice(0,160)}`)}}),c=zu(a.resultText);if("error"in c)return{ok:!1,error:c.error};let l={id:(0,oo.randomUUID)(),role:r.role,createdAt:new Date().toISOString(),model:a.model||o,summary:c.summary,packNames:e.map(d=>d.name),findings:c.findings,costUsd:a.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:r.scope,...i?{testRun:i}:{}};return Fu(r.projectId,l),m.info(`Audit (${r.role}${r.scope.kind!=="repo"?` \xB7 ${r.scope.kind}:${r.scope.ref}`:""}) done: ${c.findings.length} finding(s)`+(c.dropped?`, ${c.dropped} dropped for missing evidence`:"")),{ok:!0,audit:l}}var kr=$(Se(),1);var vc=$(require("node:path"),1),Ns=require("node:crypto"),Te=$(Se(),1);var On=$(Se(),1);var cc=require("node:child_process"),lc=$(require("node:readline"),1),dc=$(Se(),1);async function Up(r){if(r.mode!=="read_only")return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,error:"the codex adapter only supports read-only runs \u2014 its write sandbox cannot exclude shell, and Allwright never weakens a guarantee silently"};if(r.resume)return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,error:"the codex adapter cannot resume sessions"};let e=["exec","--json","--sandbox","read-only","--skip-git-repo-check","--cd",r.repoPath,...r.model?["--model",r.model]:[],"-"];return new Promise(t=>{let n=(0,cc.spawn)(r.bin,e,{cwd:r.repoPath,env:process.env,stdio:["pipe","pipe","pipe"]}),s={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0},i="",o=!1,a=()=>{o||(o=!0,clearTimeout(c),t(s))},c=setTimeout(()=>{s.timedOut=!0,s.error=`run exceeded ${r.timeoutSeconds}s wall-clock limit`,r.onLog("error",s.error),n.kill("SIGTERM"),setTimeout(()=>n.kill("SIGKILL"),5e3).unref()},r.timeoutSeconds*1e3);n.stdin.write(r.prompt),n.stdin.end(),lc.default.createInterface({input:n.stdout}).on("line",p=>{if(!p.trim())return;let v;try{v=JSON.parse(p)}catch{r.onLog("agent",p.slice(0,1e3));return}let S=v.item??v.msg??v,x=S?.type??v.type,w=S?.text??S?.message??"";x==="agent_message"&&typeof w=="string"&&w.trim()?(i=w,r.onLog("agent",w.trim().slice(0,4e3))):x==="command_execution"||x==="exec_command_begin"?r.onLog("info",`tool ${String(S?.command??"").slice(0,300)}`):x==="error"&&typeof w=="string"&&w&&r.onLog("error",w.slice(0,1e3))});let d="";n.stderr.on("data",p=>{d=(d+p.toString()).slice(-2e3)}),n.on("error",p=>{s.error=`failed to start ${r.bin}: ${p.message} \u2014 is the Codex CLI installed and logged in?`,r.onLog("error",s.error),a()}),n.on("close",p=>{p===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${p}`+(i?"":" and produced no answer")+(d?`: ${d.slice(-500)}`:"")),a()})})}var ao={id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:dc.REGISTERED_AGENTS.find(r=>r.id==="codex").capabilities,run:Up};var qp={[Ue.id]:Ue,[ao.id]:ao};function yr(r){return qp[r||On.DEFAULT_AGENT_ID]??null}function en(r,e){return!e||e===Ue.id?r.claudeBin:r.agents[e]?.bin??e}function Rs(r,e){let t=yr(r);if(!t)return`no agent adapter named "${r}" on this runner \u2014 update the runner, or set the rule's agent to "${On.DEFAULT_AGENT_ID}"`;let n=(0,On.missingAgentCapabilities)(t.id,e);return n&&n.length?`agent "${t.displayName}" cannot run ${e} rules: it cannot guarantee ${n.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function Rt(r,e){return r.replace(/\{\{(\w+)\}\}/g,(t,n)=>n in e?e[n]:t)}ct();gr();var me=$(require("node:fs"),1),rn=$(require("node:path"),1);var Fp=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),branch:k.string(),headSha:k.string(),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),changesRequestedNotified:k.boolean().optional(),conflictNotified:k.boolean().optional()}),Zp=k.record(Fp),Kp=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),projectId:k.string(),repoName:k.string(),environmentName:k.string(),requestedBy:k.string().default(""),createdAt:k.string()}),Vp=k.record(Kp),Hp=k.object({runId:k.string(),issueKey:k.string(),kind:k.enum(["plan","implement"]),repoPath:k.string(),sessionId:k.string(),doneLabel:k.string(),failedLabel:k.string(),timeoutSeconds:k.number(),createdAt:k.string(),questionsPostedAt:k.string(),rounds:k.number().int().default(1),nextLogSeq:k.number().int().nonnegative().default(0),baseRepoPath:k.string().optional(),repoName:k.string().optional(),branch:k.string().optional(),baseBranch:k.string().optional(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),requireApproval:k.boolean().optional(),maxTurns:k.number().int().optional(),issueSummary:k.string().default(""),claudeConfigDir:k.string().optional(),agent:k.string().optional(),model:k.string().optional(),actorEmail:k.string().optional()}),Gp=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),repoName:k.string(),baseRepoPath:k.string(),branch:k.string(),baseBranch:k.string(),headSha:k.string(),requireApproval:k.boolean(),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),actorEmail:k.string().optional(),resultSummary:k.string().default(""),costUsd:k.number().default(0),nextLogSeq:k.number().int().default(1e5),createdAt:k.string()}),Wp=k.record(Gp),Jp=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),jiraTransitionOnMerge:k.string().default(""),createdAt:k.string()}),Yp=k.record(Jp),Xp=k.record(Hp);function hc(){return rn.default.join(ee(),"pending-runs.json")}function uo(){return rn.default.join(ee(),"pending-deploys.json")}function co(){return rn.default.join(ee(),"pending-inputs.json")}function lo(){return rn.default.join(ee(),"merge-watch.json")}function ho(){return rn.default.join(ee(),"pending-pushes.json")}function fo(){let r=ho();if(!me.default.existsSync(r))return{};try{return Wp.parse(JSON.parse(me.default.readFileSync(r,"utf8")))}catch{return{}}}function po(r){let e=fo();e[r.runId]=r,lt(ho(),e)}function $s(r){return fo()[r]??null}function mo(r){let e=fo();r in e&&(delete e[r],lt(ho(),e))}function Ps(){let r=lo();if(!me.default.existsSync(r))return{};try{return Yp.parse(JSON.parse(me.default.readFileSync(r,"utf8")))}catch{return{}}}function fc(r){let e=Ps();e[r.runId]=r,lt(lo(),e)}function Nn(r){let e=Ps();r in e&&(delete e[r],lt(lo(),e))}function Mn(){let r=hc();if(!me.default.existsSync(r))return{};try{return Zp.parse(JSON.parse(me.default.readFileSync(r,"utf8")))}catch{return{}}}function lt(r,e){me.default.mkdirSync(ee(),{recursive:!0,mode:448});let t=r+".tmp";me.default.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
513
|
+
`,{mode:384}),me.default.renameSync(t,r),me.default.chmodSync(r,384)}function pc(r){lt(hc(),r)}function nn(r){let e=Mn();e[r.runId]=r,pc(e)}function go(r){return Mn()[r]??null}function _r(r){let e=Mn();r in e&&(delete e[r],pc(e))}function yo(){let r=uo();if(!me.default.existsSync(r))return{};try{return Vp.parse(JSON.parse(me.default.readFileSync(r,"utf8")))}catch{return{}}}function mc(r){let e=yo();e[r.runId]=r,lt(uo(),e)}function js(r){return yo()[r]??null}function Os(r){let e=yo();r in e&&(delete e[r],lt(uo(),e))}function sn(){let r=co();if(!me.default.existsSync(r))return{};try{return Xp.parse(JSON.parse(me.default.readFileSync(r,"utf8")))}catch{return{}}}function gc(r){let e=sn();e[r.runId]=r,lt(co(),e)}function Je(r){let e=sn();r in e&&(delete e[r],lt(co(),e))}var bc=5,yc=2,Qp=8,_c=2,em="You stopped because the session hit its turn limit \u2014 nothing failed. Continue exactly where you left off. Do not re-read files you already know or redo completed work; be economical with tool calls and finish the remaining work. Then end with your final summary exactly as the original instructions asked.";async function Ln(r,e,t,n){let s=Date.now(),i="";n&&(i=await n().catch(()=>""));let o=await r.run(e),a=0,c="",l=n?Qp:yc;for(;!o.ok&&o.turnLimitHit&&r.capabilities.sessionResume;){if(a>=l){c=`resume cap (${l}) reached`;break}if(n&&a>=yc){let p=await n().catch(()=>""),v=p!==""&&p!==i;if(i=p,!v){c="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*_c*1e3){c=`wall-clock budget (${_c}x the rule's timeout) exhausted`;break}}a++,t("info",`Turn limit hit mid-work \u2014 auto-resuming the same session (resume ${a}, cap ${l})`);let d=await r.run({...e,prompt:em,resume:!0});d.costUsd+=o.costUsd,d.inputTokens+=o.inputTokens,d.outputTokens+=o.outputTokens,o=d}return!o.ok&&o.turnLimitHit&&r.capabilities.sessionResume&&(o.error=`${o.error??"hit the turn limit"} \u2014 even after ${a} automatic same-session resume(s)${c?` (stopped: ${c})`:""}. The ticket is probably too large for one run: raise the rule's max turns, or split the ticket.`),o}function vr(r,e,t=0){let n=t;return{emit:(o,a)=>{e.send({type:"run.log",runId:r,seq:n++,ts:new Date().toISOString(),level:o,message:a}),o!=="agent"&&m.info(`[run ${r}] ${a}`)},setStatus:(o,a={})=>{e.send({type:"run.status",runId:r,status:o,...a})},nextSeq:()=>n}}async function _o(r){return r.rule.action.type==="implement"?nm(r):r.rule.action.type==="respond"?rm(r):tm(r)}async function tm(r){let{emit:e,setStatus:t,nextSeq:n}=vr(r.runId,r.transport),{trigger:s}=r.rule,i=r.rule.action;if(i.type!=="plan_only")return;let o=Rs(i.agent,i.type);if(o){e("error",o),await on(r,o),t("failed",{error:o});return}let a=(0,Ns.randomUUID)();try{t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", plan-only)`),e("info",`Fetching ${r.issueKey} from Jira`);let c=await r.jira.getIssue(r.issueKey),l=Rt(i.promptTemplate,{issueKey:c.key,summary:c.summary,description:c.description||"(no description)",comments:Un(c.comments)})+await Ur(r.jira,c.attachments,r.repoPath,e);e("info",`Starting Claude Code in ${r.repoPath} \u2014 read-only tools, path-jailed to the repo, timeout ${i.timeoutSeconds}s`);let d=await Ln(yr(i.agent),{repoPath:r.repoPath,prompt:l,timeoutSeconds:i.timeoutSeconds,bin:en(r.cfg,i.agent),configDir:r.claudeConfigDir,mode:"read_only",model:i.model||void 0,sessionId:a,onLog:(S,x)=>e(S,x)},e),p={costUsd:d.costUsd,inputTokens:d.inputTokens,outputTokens:d.outputTokens,billingMode:d.billingMode,model:d.model};if(!d.ok||!d.resultText.trim()){let S=d.error??"Claude Code produced no output";e("error",`Run failed: ${S}`),await on(r,S),t(d.timedOut?"timed_out":"failed",{error:S,...p});return}let v=Ms(d.resultText);if(v){await Ds({kind:"plan",runId:r.runId,issueKey:r.issueKey,repoPath:r.repoPath,sessionId:a,doneLabel:s.doneLabel,failedLabel:s.failedLabel,timeoutSeconds:i.timeoutSeconds,jira:r.jira,nextLogSeq:n(),rounds:1,claudeConfigDir:r.claudeConfigDir,agent:i.agent,model:i.model},v,e,t,p);return}await kc({runId:r.runId,issueKey:r.issueKey,doneLabel:s.doneLabel,jira:r.jira,resultText:d.resultText,costFields:p,emit:e,setStatus:t})}catch(c){let l=c instanceof Error?c.message:String(c);e("error",`Run failed: ${l}`),await on(r,l),t("failed",{error:l})}finally{St(r.repoPath)}}async function wc(r,e,t,n){let{emit:s,setStatus:i,nextSeq:o}=vr(r.runId,n.transport,r.nextLogSeq);try{i("running"),s("info",`Reply received on ${r.issueKey} \u2014 continuing run \`${r.runId}\``);let a=jc(e)+await Ur(n.jiraFor(r.repoName??""),t,r.repoPath,s),c=await Ln(yr(r.agent),{repoPath:r.repoPath,prompt:a,timeoutSeconds:r.timeoutSeconds,bin:en(n.cfg,r.agent??""),configDir:r.claudeConfigDir,mode:"read_only",model:r.model||void 0,sessionId:r.sessionId,resume:!0,onLog:(p,v)=>s(p,v)},s),l={costUsd:c.costUsd,inputTokens:c.inputTokens,outputTokens:c.outputTokens,billingMode:c.billingMode,model:c.model};if(!c.ok||!c.resultText.trim()){let p=c.error??"Claude Code produced no output";s("error",`Run failed: ${p}`),await dt(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,p),Je(r.runId),i(c.timedOut?"timed_out":"failed",{error:p,...l});return}let d=Ms(c.resultText);if(d){if(r.rounds>=bc){await Oc(n.jiraFor(r.repoName??""),r,s,i,l);return}await Ds({kind:"plan",runId:r.runId,issueKey:r.issueKey,repoPath:r.repoPath,sessionId:r.sessionId,doneLabel:r.doneLabel,failedLabel:r.failedLabel,timeoutSeconds:r.timeoutSeconds,jira:n.jiraFor(r.repoName??""),nextLogSeq:o(),rounds:r.rounds+1,createdAt:r.createdAt,claudeConfigDir:r.claudeConfigDir,actorEmail:r.actorEmail,agent:r.agent,model:r.model},d,s,i,l);return}await kc({runId:r.runId,issueKey:r.issueKey,doneLabel:r.doneLabel,jira:n.jiraFor(r.repoName??""),resultText:c.resultText,costFields:l,emit:s,setStatus:i}),Je(r.runId)}catch(a){let c=a instanceof Error?a.message:String(a);s("error",`Run failed: ${c}`),await dt(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,c),Je(r.runId),i("failed",{error:c})}finally{St(r.repoPath)}}async function kc(r){let{runId:e,issueKey:t,doneLabel:n,jira:s,resultText:i,costFields:o,emit:a,setStatus:c}=r;c("posting",o),a("info",`Posting plan to ${t} (${i.length} chars)`);let l=`
|
|
513
514
|
|
|
514
515
|
---
|
|
515
|
-
_Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(t,i+l),await s.editLabels(t,{add:[n],remove:[Te.NEEDS_INPUT_LABEL]}),a("info",`Labeled ${t} with "${n}"`),
|
|
516
|
+
_Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(t,i+l),await s.editLabels(t,{add:[n],remove:[Te.NEEDS_INPUT_LABEL]}),a("info",`Labeled ${t} with "${n}"`),c("succeeded",{...o,resultSummary:Dn(i)}),a("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function rm(r){let{emit:e,setStatus:t}=vr(r.runId,r.transport),n=r.rule.action;if(n.type!=="respond")return;let s=Rs(n.agent,n.type);if(s){e("error",s),await r.jira.addComment(r.issueKey,`**Allwright could not answer this question.**
|
|
516
517
|
|
|
517
|
-
${s}`).catch(()=>{}),t("failed",{error:s});return}try{t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", respond`+(r.question?`, question from ${r.question.author}`:"")+")"),e("info",`Fetching ${r.issueKey} from Jira`);let i=await r.jira.getIssue(r.issueKey),o=Rt(n.promptTemplate,{issueKey:i.key,summary:i.summary,description:i.description||"(no description)",comments:
|
|
518
|
+
${s}`).catch(()=>{}),t("failed",{error:s});return}try{t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", respond`+(r.question?`, question from ${r.question.author}`:"")+")"),e("info",`Fetching ${r.issueKey} from Jira`);let i=await r.jira.getIssue(r.issueKey),o=Rt(n.promptTemplate,{issueKey:i.key,summary:i.summary,description:i.description||"(no description)",comments:Un(i.comments),question:r.question?.body??"(see the latest comment on the ticket)",questionAuthor:r.question?.author??"the commenter"})+await Ur(r.jira,i.attachments,r.repoPath,e);e("info",`Starting Claude Code in ${r.repoPath} \u2014 read-only tools, path-jailed, timeout ${n.timeoutSeconds}s`);let a=await Ln(yr(n.agent),{repoPath:r.repoPath,prompt:o,timeoutSeconds:n.timeoutSeconds,bin:en(r.cfg,n.agent),configDir:r.claudeConfigDir,mode:"read_only",model:n.model||void 0,sessionId:(0,Ns.randomUUID)(),onLog:(l,d)=>e(l,d)},e),c={costUsd:a.costUsd,inputTokens:a.inputTokens,outputTokens:a.outputTokens,billingMode:a.billingMode,model:a.model};if(!a.ok||!a.resultText.trim()){let l=a.error??"Claude Code produced no answer";e("error",`Run failed: ${l}`),await r.jira.addComment(r.issueKey,`**Allwright could not answer this question.**
|
|
518
519
|
|
|
519
520
|
Error: ${l.slice(0,800)}
|
|
520
521
|
|
|
521
|
-
Ask again in a new comment to retry. (run \`${r.runId}\`)`).catch(d=>m.error(`could not post answer failure to ${r.issueKey}: ${d}`)),t(a.timedOut?"timed_out":"failed",{error:l,...
|
|
522
|
+
Ask again in a new comment to retry. (run \`${r.runId}\`)`).catch(d=>m.error(`could not post answer failure to ${r.issueKey}: ${d}`)),t(a.timedOut?"timed_out":"failed",{error:l,...c});return}t("posting",c),e("info",`Posting answer to ${r.issueKey} (${a.resultText.length} chars)`),await r.jira.addComment(r.issueKey,a.resultText),t("succeeded",{...c,resultSummary:Dn(a.resultText)}),e("info",`Run succeeded \xB7 $${a.costUsd.toFixed(4)}`)}catch(i){let o=i instanceof Error?i.message:String(i);e("error",`Run failed: ${o}`),t("failed",{error:o})}finally{St(r.repoPath)}}async function Sc(r,e,t,n){let s=`${e}-wip`;try{return St(r),await Ss(r,`WIP: turn limit exhausted (Allwright run ${t})`),await Mi(r,s),n("info",`Partial work preserved on branch "${s}"`),s}catch(i){return n("warn",`could not preserve partial work: ${i instanceof Error?i.message:i}`),null}}function Tc(r){return`
|
|
522
523
|
|
|
523
|
-
Partial work from this run is saved on branch \`${r}\` \u2014 it was NOT safety-checked or reviewed and never merges on its own; a future run or a developer can pick it up.`}async function
|
|
524
|
+
Partial work from this run is saved on branch \`${r}\` \u2014 it was NOT safety-checked or reviewed and never merges on its own; a future run or a developer can pick it up.`}async function nm(r){let{emit:e,setStatus:t,nextSeq:n}=vr(r.runId,r.transport),{trigger:s}=r.rule,i=r.rule.action;if(i.type!=="implement")return;let o=Rs(i.agent,i.type);if(o){e("error",o),await on(r,o),t("failed",{error:o});return}let a=vc.default.join(An(),r.runId),c=Rt(i.branchTemplate,{issueKey:r.issueKey}),l=(0,Ns.randomUUID)(),d=!1,p=!1;try{if(!Cs(ce()??r.cfg,r.project.repoName,r.actorEmail))throw new Error("no GitHub token applies to this repo \u2014 run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");if(c===i.baseBranch)throw new Error(`rendered branch "${c}" equals the base branch \u2014 refusing (check the rule's branch template)`);if(t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", implement)`),i.jiraTransitionOnStart)try{await r.jira.transitionByName(r.issueKey,i.jiraTransitionOnStart)?e("info",`Jira transition "${i.jiraTransitionOnStart}" applied at run start`):e("warn",`no transition named "${i.jiraTransitionOnStart}" is available from this ticket's current status \u2014 continuing anyway`)}catch(f){e("warn",`Jira start transition failed: ${f instanceof Error?f.message:f} \u2014 continuing anyway`)}let v=await pr(r.repoPath);if(e("info",`Repo origin: ${v}`),!mr(v))throw new Error(`origin "${v}" is not a GitHub remote \u2014 implement mode supports GitHub only`);e("info",`Fetching ${r.issueKey} from Jira`);let S=await r.jira.getIssue(r.issueKey);e("info",`Preparing worktree on branch "${c}" from origin/${i.baseBranch}`),await Jr(r.repoPath,i.baseBranch),await Li(r.repoPath,c),await zi(r.repoPath,a,c,i.baseBranch),d=!0;let x=Rt(i.promptTemplate,{issueKey:S.key,summary:S.summary,description:S.description||"(no description)",comments:Un(S.comments)})+await Ur(r.jira,S.attachments,a,e)+(i.updateMemory?Te.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree \u2014 edit tools enabled, path-jailed, no shell, timeout ${i.timeoutSeconds}s`);let w=await Ln(yr(i.agent),{repoPath:a,prompt:x,timeoutSeconds:i.timeoutSeconds,bin:en(r.cfg,i.agent),configDir:r.claudeConfigDir,mode:"edit_no_shell",model:i.model||void 0,maxTurns:i.maxTurns,sessionId:l,onLog:(f,g)=>e(f,g)},e,()=>ks(a)),j={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens,billingMode:w.billingMode,model:w.model};if(!w.ok){let f=w.error??"Claude Code failed";e("error",`Run failed: ${f}`);let g=f;if(w.turnLimitHit){let b=await Sc(a,c,r.runId,e);b&&(g+=Tc(b))}await on(r,g),t(w.timedOut?"timed_out":"failed",{error:f,...j});return}let U=Ms(w.resultText);if(U){p=!0,await Ds({kind:"implement",runId:r.runId,issueKey:r.issueKey,repoPath:a,sessionId:l,doneLabel:s.doneLabel,failedLabel:s.failedLabel,timeoutSeconds:i.timeoutSeconds,jira:r.jira,nextLogSeq:n(),rounds:1,claudeConfigDir:r.claudeConfigDir,agent:i.agent,model:i.model,actorEmail:r.actorEmail,baseRepoPath:r.repoPath,repoName:r.project.repoName,branch:c,baseBranch:i.baseBranch,jiraTransition:i.jiraTransition,jiraTransitionOnMerge:i.jiraTransitionOnMerge,requireApproval:i.requireApproval,maxTurns:i.maxTurns,issueSummary:S.summary},U,e,t,j);return}St(a),await Cc({runId:r.runId,issueKey:r.issueKey,issueSummary:S.summary,worktreePath:a,baseRepoPath:r.repoPath,branch:c,baseBranch:i.baseBranch,jiraTransition:i.jiraTransition,jiraTransitionOnMerge:i.jiraTransitionOnMerge,requireApproval:i.requireApproval,doneLabel:s.doneLabel,failedLabel:s.failedLabel,repoName:r.project.repoName,jira:r.jira,cfg:r.cfg,actorEmail:r.actorEmail,resultText:w.resultText,costFields:j,emit:e,setStatus:t})}catch(v){let S=v instanceof Error?v.message:String(v);e("error",`Run failed: ${S}`),await on(r,S),t("failed",{error:S})}finally{d&&!p&&await Yr(r.repoPath,a).catch(()=>{})}}async function xc(r,e,t,n){let{emit:s,setStatus:i,nextSeq:o}=vr(r.runId,n.transport,r.nextLogSeq),a=r.repoPath,c=!1;try{if(!Cs(ce()??n.cfg,r.repoName??"",r.actorEmail))throw new Error("no GitHub token applies to this repo \u2014 run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");i("running"),s("info",`Reply received on ${r.issueKey} \u2014 continuing run \`${r.runId}\``);let l=jc(e)+await Ur(n.jiraFor(r.repoName??""),t,a,s),d=await Ln(yr(r.agent),{repoPath:a,prompt:l,timeoutSeconds:r.timeoutSeconds,bin:en(n.cfg,r.agent??""),configDir:r.claudeConfigDir,mode:"edit_no_shell",model:r.model||void 0,maxTurns:r.maxTurns??120,sessionId:r.sessionId,resume:!0,onLog:(S,x)=>s(S,x)},s,()=>ks(a)),p={costUsd:d.costUsd,inputTokens:d.inputTokens,outputTokens:d.outputTokens,billingMode:d.billingMode,model:d.model};if(!d.ok){let S=d.error??"Claude Code failed";s("error",`Run failed: ${S}`);let x=S;if(d.turnLimitHit&&r.branch){let w=await Sc(a,r.branch,r.runId,s);w&&(x+=Tc(w))}await dt(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,x),Je(r.runId),i(d.timedOut?"timed_out":"failed",{error:S,...p});return}let v=Ms(d.resultText);if(v){if(r.rounds>=bc){await Oc(n.jiraFor(r.repoName??""),r,s,i,p);return}c=!0,await Ds({kind:"implement",runId:r.runId,issueKey:r.issueKey,repoPath:a,sessionId:r.sessionId,doneLabel:r.doneLabel,failedLabel:r.failedLabel,timeoutSeconds:r.timeoutSeconds,jira:n.jiraFor(r.repoName??""),nextLogSeq:o(),rounds:r.rounds+1,createdAt:r.createdAt,claudeConfigDir:r.claudeConfigDir,actorEmail:r.actorEmail,agent:r.agent,model:r.model,baseRepoPath:r.baseRepoPath,repoName:r.repoName,branch:r.branch,baseBranch:r.baseBranch,jiraTransition:r.jiraTransition,jiraTransitionOnMerge:r.jiraTransitionOnMerge,requireApproval:r.requireApproval,maxTurns:r.maxTurns,issueSummary:r.issueSummary},v,s,i,p);return}St(a),await Cc({runId:r.runId,issueKey:r.issueKey,issueSummary:r.issueSummary,worktreePath:a,baseRepoPath:r.baseRepoPath??a,branch:r.branch,baseBranch:r.baseBranch,jiraTransition:r.jiraTransition,requireApproval:r.requireApproval??!0,doneLabel:r.doneLabel,failedLabel:r.failedLabel,repoName:r.repoName,jira:n.jiraFor(r.repoName??""),cfg:n.cfg,actorEmail:r.actorEmail,resultText:d.resultText,costFields:p,emit:s,setStatus:i}),Je(r.runId)}catch(l){let d=l instanceof Error?l.message:String(l);s("error",`Run failed: ${d}`),await dt(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,d),Je(r.runId),i("failed",{error:d})}finally{c||await Yr(r.baseRepoPath??a,a).catch(()=>{})}}async function Cc(r){let{runId:e,issueKey:t,issueSummary:n,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:a,jiraTransition:c,jiraTransitionOnMerge:l,requireApproval:d,doneLabel:p,failedLabel:v,repoName:S,jira:x,cfg:w,actorEmail:j,resultText:U,costFields:f,emit:g,setStatus:b}=r,I=await Ni(s);I.deleted.length&&g("info",`Deleted ${I.deleted.length} file(s) listed in ${Wr}: `+I.deleted.slice(0,10).join(", ")+(I.deleted.length>10?", \u2026":""));for(let H of I.refused)g("warn",`${Wr} entry refused: ${H}`);g("info","Committing changes"),await Ss(s,`${t}: ${n}
|
|
524
525
|
|
|
525
|
-
Allwright run ${e}`);let N=await
|
|
526
|
+
Allwright run ${e}`);let N=await Ui(s,a);if(!N.ok){let H=N.forbidden.length?`refusing to push: changes touch protected paths (${N.forbidden.slice(0,5).join(", ")}) \u2014 CI/workflow files can exfiltrate repo secrets and are never pushed by the agent`:`refusing to push: change is too large (${N.files} files, ${N.insertions+N.deletions} lines; limits ${bs}/${ws})`;g("error",H),await dt(x,t,e,v,H),b("failed",{error:H,...f});return}g("info",`Diff: ${N.files} file(s), +${N.insertions}/-${N.deletions}`);let V=await pr(s),W=mr(V);if(!W){let H=`origin "${V}" is not a GitHub remote \u2014 implement mode supports GitHub only`;g("error",H),await dt(x,t,e,v,H),b("failed",{error:H,...f});return}let J=await Rn(s),z=sm(U);try{await Ec({gitDir:s,ownerRepo:W,runId:e,issueKey:t,issueSummary:n,branch:o,baseBranch:a,jiraTransition:c,jiraTransitionOnMerge:l,requireApproval:d,doneLabel:p,failedLabel:v,repoName:S,jira:x,cfg:w,actorEmail:j,summary:z,cost:f,emit:g,setStatus:b})}catch(H){let be=H instanceof Error?H.message:String(H);po({runId:e,issueKey:t,issueSummary:n,repoName:S,baseRepoPath:i,branch:o,baseBranch:a,headSha:J,requireApproval:d,doneLabel:p,failedLabel:v,jiraTransition:c,jiraTransitionOnMerge:l,actorEmail:j,resultSummary:z,costUsd:f.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),g("error",`Run failed: ${be}`),g("info",`The commit itself survived on the runner (branch ${o}) \u2014 fix the cause, then use "Retry push" on this run's dashboard page.`),await dt(x,t,e,v,`${be}
|
|
526
527
|
|
|
527
|
-
The agent's commit survived on the runner \u2014 "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),b("failed",{error:be,retryAvailable:!0,...f})}}async function
|
|
528
|
+
The agent's commit survived on the runner \u2014 "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),b("failed",{error:be,retryAvailable:!0,...f})}}async function Ec(r){let{gitDir:e,ownerRepo:t,runId:n,issueKey:s,issueSummary:i,branch:o,baseBranch:a,jiraTransition:c,jiraTransitionOnMerge:l,requireApproval:d,doneLabel:p,failedLabel:v,repoName:S,jira:x,cfg:w,actorEmail:j,summary:U,cost:f,emit:g,setStatus:b}=r;g("info",`Pushing ${o} to origin`),await qi(e,o);let I=await Ts(e,o),N=`${U}
|
|
528
529
|
|
|
529
530
|
---
|
|
530
531
|
Jira: ${new URL(`/browse/${s}`,w.jira?.baseUrl??"").toString()}
|
|
531
|
-
_Allwright implement run \`${n}\` \xB7 cost $${f.costUsd.toFixed(4)}. The agent could not run tests \u2014 review accordingly._`;g("info","Opening pull request");let V=
|
|
532
|
+
_Allwright implement run \`${n}\` \xB7 cost $${f.costUsd.toFixed(4)}. The agent could not run tests \u2014 review accordingly._`;g("info","Opening pull request");let V=Cs(ce()??w,S,j);V.source==="user"&&g("info",`PR will be authored with ${j}'s own GitHub token`);let J=await new Oe(V.token).createPullRequest(t.owner,t.repo,{title:`${s}: ${i}`.slice(0,250),head:o,base:a,body:N});g("info",`PR ready: ${J.url}`),fc({runId:n,issueKey:s,repoName:S,owner:t.owner,repo:t.repo,prNumber:J.number,prUrl:J.url,jiraTransitionOnMerge:l??"",createdAt:new Date().toISOString()}),b("posting",f);let z={runId:n,issueKey:s,repoName:S,owner:t.owner,repo:t.repo,prNumber:J.number,prUrl:J.url,branch:o,headSha:I,doneLabel:p,failedLabel:v,jiraTransition:c};d?(nn(z),await x.addComment(s,`**Allwright opened a pull request for review.**
|
|
532
533
|
|
|
533
534
|
PR: ${J.url}
|
|
534
535
|
|
|
535
|
-
Approve the PR on GitHub OR on the Allwright dashboard \u2014 either completes the run. Rejecting on the dashboard closes the PR and deletes the branch. (run \`${n}\`)`),b("awaiting_approval",{...f,prUrl:J.url,headSha:I,resultSummary:
|
|
536
|
+
Approve the PR on GitHub OR on the Allwright dashboard \u2014 either completes the run. Rejecting on the dashboard closes the PR and deletes the branch. (run \`${n}\`)`),b("awaiting_approval",{...f,prUrl:J.url,headSha:I,resultSummary:Dn(U),retryAvailable:!1}),g("info",`Awaiting approval on the dashboard \xB7 $${f.costUsd.toFixed(4)}`)):(await Ic({jira:x,issueKey:s},z,g),b("succeeded",{...f,prUrl:J.url,headSha:I,resultSummary:Dn(U),retryAvailable:!1}),g("info",`Run succeeded \xB7 ${J.url} \xB7 $${f.costUsd.toFixed(4)}`))}async function Ic(r,e,t){let n=null;if(e.jiraTransition)try{await r.jira.transitionByName(e.issueKey,e.jiraTransition)?t("info",`Jira transition "${e.jiraTransition}" applied`):(n=`no transition named "${e.jiraTransition}" is available from this ticket's current status \u2014 the PR is fine, but move the ticket manually`,t("warn",n))}catch(s){n=`Jira transition failed: ${s instanceof Error?s.message:s}`,t("warn",n)}return await r.jira.addComment(e.issueKey,`**Allwright: implementation complete.**
|
|
536
537
|
|
|
537
538
|
PR: ${e.prUrl}`+(n?`
|
|
538
539
|
|
|
539
540
|
Note: ${n}`:"")+`
|
|
540
541
|
|
|
541
|
-
(run \`${e.runId}\`)`),await r.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Te.NEEDS_INPUT_LABEL]}),n}async function
|
|
542
|
+
(run \`${e.runId}\`)`),await r.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Te.NEEDS_INPUT_LABEL]}),n}async function zn(r,e,t){let n=go(e);if(!n){m.warn(`run.approved for ${e}: no pending entry (already processed?) \u2014 ignoring`);return}let{emit:s,setStatus:i}=$c(r,e);try{let o=At(ce()??r.cfg,n.repoName);if(!o)throw new Error("GitHub token missing on this runner");let a=new Oe(o);s("info",`Approval received for ${n.issueKey} \u2014 verifying PR state`);let c=await a.getPullRequest(n.owner,n.repo,n.prNumber);if(!c)throw new Error(`PR #${n.prNumber} no longer exists on GitHub`);if(c.state==="closed"&&!c.merged)throw new Error(`PR #${n.prNumber} was closed on GitHub without merging`);let l=t??n.headSha;if(c.state==="open"&&c.headSha!==l){let d=`PR #${n.prNumber} changed since review started (${l.slice(0,7)} \u2192 ${c.headSha.slice(0,7)}) \u2014 approval not applied. Re-review the PR and approve again.`;s("warn",d),await r.jiraFor(n.repoName??"").addComment(n.issueKey,`**Allwright:** ${d}`),i("awaiting_approval",{prUrl:n.prUrl,headSha:c.headSha,resultSummary:d});return}await Ic({jira:r.jiraFor(n.repoName??""),issueKey:n.issueKey},n,s),i("succeeded",{prUrl:n.prUrl}),s("info","Run completed after approval"),_r(e)}catch(o){let a=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${a}`),await Pc(r,n,a),i("failed",{error:a}),_r(e)}}async function Ac(r,e){let t=go(e);if(!t){m.warn(`run.rejected for ${e}: no pending entry (already processed?) \u2014 ignoring`);return}let{emit:n,setStatus:s}=$c(r,e);try{let i=At(ce()??r.cfg,t.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new Oe(i);n("info",`Rejection received for ${t.issueKey} \u2014 closing PR #${t.prNumber}`);let a=await o.getPullRequest(t.owner,t.repo,t.prNumber);a&&a.state==="open"&&await o.closePullRequest(t.owner,t.repo,t.prNumber),a?.merged||await o.deleteBranch(t.owner,t.repo,t.branch),await r.jiraFor(t.repoName??"").addComment(t.issueKey,`**Allwright: changes rejected.**
|
|
542
543
|
|
|
543
|
-
The pull request was closed and the branch deleted. This ticket is labeled \`${t.failedLabel}\`; remove the label to try again. (run \`${t.runId}\`)`),await r.jiraFor(t.repoName??"").editLabels(t.issueKey,{add:[t.failedLabel]}),s("failed",{error:"rejected by user"}),n("info","PR closed, branch deleted, ticket labeled"),
|
|
544
|
+
The pull request was closed and the branch deleted. This ticket is labeled \`${t.failedLabel}\`; remove the label to try again. (run \`${t.runId}\`)`),await r.jiraFor(t.repoName??"").editLabels(t.issueKey,{add:[t.failedLabel]}),s("failed",{error:"rejected by user"}),n("info","PR closed, branch deleted, ticket labeled"),_r(e)}catch(i){let o=i instanceof Error?i.message:String(i);n("error",`Rejection handling failed: ${o}`),await Pc(r,t,o),s("failed",{error:o}),_r(e)}}async function Rc(r,e){let t=$s(e);if(!t){m.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:o,setStatus:a}=vr(e,r.transport,1e5);o("error","Retry push requested, but this runner holds no retry record for the run \u2014 it was already used or never saved. Re-run the ticket instead."),a("failed",{retryAvailable:!1});return}let{emit:n,setStatus:s,nextSeq:i}=vr(e,r.transport,t.nextLogSeq);try{let o=await Ts(t.baseRepoPath,t.branch);if(o!==t.headSha){n("error",`Retry push aborted: branch ${t.branch} no longer holds the commit this run produced (expected ${t.headSha.slice(0,7)}, ${o?`found ${o.slice(0,7)}`:"the branch is gone"}) \u2014 a newer run has likely reused the branch. Re-run the ticket instead.`),mo(e),s("failed",{retryAvailable:!1});return}let a=await pr(t.baseRepoPath),c=mr(a);if(!c)throw new Error(`origin "${a}" is not a GitHub remote`);n("info",`Retry push for ${t.issueKey}: branch ${t.branch} at ${t.headSha.slice(0,7)}`);let l=r.jiraFor(t.repoName);await Ec({gitDir:t.baseRepoPath,ownerRepo:c,runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:l,cfg:ce()??r.cfg,actorEmail:t.actorEmail,summary:t.resultSummary,cost:{costUsd:t.costUsd},emit:n,setStatus:s}),mo(e),await l.editLabels(t.issueKey,{remove:[t.failedLabel]}).catch(()=>{})}catch(o){let a=o instanceof Error?o.message:String(o);n("error",`Retry push failed: ${a}`),po({...t,nextLogSeq:i()}),s("failed",{error:a,retryAvailable:!0})}}function $c(r,e){let t=1e5;return{emit:(i,o)=>{r.transport.send({type:"run.log",runId:e,seq:t++,ts:new Date().toISOString(),level:i,message:o}),i!=="agent"&&m.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{r.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function Pc(r,e,t){try{await r.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
|
|
544
545
|
|
|
545
546
|
Error: ${t.slice(0,800)}
|
|
546
547
|
|
|
547
548
|
PR: ${e.prUrl}
|
|
548
|
-
(run \`${e.runId}\`)`),await r.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(n){m.error(`could not post decision failure to ${e.issueKey}: ${n}`)}}function
|
|
549
|
+
(run \`${e.runId}\`)`),await r.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(n){m.error(`could not post decision failure to ${e.issueKey}: ${n}`)}}function Un(r){if(!r.length)return"(no comments)";let e=6e4,t=r.map(i=>`${i.author} (${i.created}):
|
|
549
550
|
${i.body}`),n=[],s=0;for(let i=t.length-1;i>=0;i--){if(s+=t[i].length+6,s>e){n.unshift(`(\u2026 ${i+1} earlier comment(s) omitted for length \u2026)`);break}n.unshift(t[i])}return n.join(`
|
|
550
551
|
---
|
|
551
|
-
`)}function
|
|
552
|
+
`)}function jc(r){return`The ticket author replied:
|
|
552
553
|
|
|
553
554
|
${r}
|
|
554
555
|
|
|
555
|
-
Continue from where you left off now that you have this information. If you are still missing what you need, ask again the same way as before (the ${Te.NEEDS_INPUT_MARKER} marker).`}function
|
|
556
|
+
Continue from where you left off now that you have this information. If you are still missing what you need, ask again the same way as before (the ${Te.NEEDS_INPUT_MARKER} marker).`}function Ms(r){let e=r.trim(),t=e.split(`
|
|
556
557
|
`,1)[0].trim(),n=o=>o.replace(/[^a-z]/gi,"").toUpperCase();if(n(t)!==n(Te.NEEDS_INPUT_MARKER))return null;let s=e.indexOf(`
|
|
557
|
-
`);return s<0?null:e.slice(s+1).trim()||null}async function
|
|
558
|
+
`);return s<0?null:e.slice(s+1).trim()||null}async function Ds(r,e,t,n,s){t("info",`Claude needs more information \u2014 posting questions to ${r.issueKey}`),await r.jira.addComment(r.issueKey,`**${Te.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
|
|
558
559
|
|
|
559
560
|
${e}
|
|
560
561
|
|
|
561
|
-
Reply with your answers in a comment on this ticket \u2014 this run will pick up right where it left off, automatically, once you do. (run \`${r.runId}\`)`);let i=new Date().toISOString();await r.jira.editLabels(r.issueKey,{add:[Te.NEEDS_INPUT_LABEL]}),
|
|
562
|
+
Reply with your answers in a comment on this ticket \u2014 this run will pick up right where it left off, automatically, once you do. (run \`${r.runId}\`)`);let i=new Date().toISOString();await r.jira.editLabels(r.issueKey,{add:[Te.NEEDS_INPUT_LABEL]}),gc({runId:r.runId,issueKey:r.issueKey,kind:r.kind,repoPath:r.repoPath,sessionId:r.sessionId,doneLabel:r.doneLabel,failedLabel:r.failedLabel,timeoutSeconds:r.timeoutSeconds,createdAt:r.createdAt??i,questionsPostedAt:i,rounds:r.rounds,nextLogSeq:r.nextLogSeq,baseRepoPath:r.baseRepoPath,repoName:r.repoName,branch:r.branch,baseBranch:r.baseBranch,jiraTransition:r.jiraTransition,jiraTransitionOnMerge:r.jiraTransitionOnMerge,requireApproval:r.requireApproval,maxTurns:r.maxTurns,issueSummary:r.issueSummary??"",claudeConfigDir:r.claudeConfigDir,agent:r.agent,model:r.model,actorEmail:r.actorEmail}),n("needs_input",{...s,resultSummary:Dn(e)}),t("info",`Waiting for a reply on ${r.issueKey} (label "${Te.NEEDS_INPUT_LABEL}")`)}async function Oc(r,e,t,n,s){let i=`Claude asked for clarification ${e.rounds} times without reaching a result \u2014 giving up. Answer more completely and re-trigger manually if you want another attempt.`;t("error",i),await dt(r,e.issueKey,e.runId,e.failedLabel,i),Je(e.runId),n("failed",{error:i,...s})}async function on(r,e){await dt(r.jira,r.issueKey,r.runId,r.rule.trigger.failedLabel,e)}async function dt(r,e,t,n,s){try{await r.addComment(e,`**Allwright run failed.**
|
|
562
563
|
|
|
563
564
|
Error: ${s.slice(0,800)}
|
|
564
565
|
|
|
565
|
-
This ticket has been labeled \`${n}\` and will not be retried automatically. To retry, fix the cause and remove the \`${n}\` label. (run \`${t}\`)`),await r.editLabels(e,{add:[n],remove:[Te.NEEDS_INPUT_LABEL]})}catch(i){m.error(`could not post failure comment to ${e}: ${i}`)}}function
|
|
566
|
-
`)){let t=e.replace(/^#+\s*/,"").trim();if(t.length>10)return t.slice(0,200)}return r.slice(0,200)}var
|
|
566
|
+
This ticket has been labeled \`${n}\` and will not be retried automatically. To retry, fix the cause and remove the \`${n}\` label. (run \`${t}\`)`),await r.editLabels(e,{add:[n],remove:[Te.NEEDS_INPUT_LABEL]})}catch(i){m.error(`could not post failure comment to ${e}: ${i}`)}}function sm(r){let e=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(r);return(e?e[1]:r).trim().slice(0,8e3)||"(no summary provided)"}function Dn(r){for(let e of r.split(`
|
|
567
|
+
`)){let t=e.replace(/^#+\s*/,"").trim();if(t.length>10)return t.slice(0,200)}return r.slice(0,200)}var an=$(require("node:fs"),1),br=$(require("node:path"),1),Ls=require("node:child_process"),bo=$(require("node:readline"),1),Uc=require("node:crypto"),wr=$(Se(),1);gr();ct();var Nc=4e3,im=4e3;function wo(r){let e=0;return{emit:(s,i)=>{r.transport.send({type:"run.log",runId:r.runId,seq:e++,ts:new Date().toISOString(),level:s,message:i.slice(0,im)}),s!=="agent"&&m.info(`[deploy ${r.runId}] ${i}`)},setStatus:(s,i={})=>{r.transport.send({type:"run.status",runId:r.runId,status:s,...i})}}}async function zs(r){let{emit:e,setStatus:t}=wo(r),n=r.environment;try{let s=om(r);if(s){e("error",s),await qe(r,`**Allwright could not deploy to \`${n.name}\`.**
|
|
567
568
|
|
|
568
|
-
${s}`),t("failed",{error:s});return}if(n.requireApproval){
|
|
569
|
+
${s}`),t("failed",{error:s});return}if(n.requireApproval){mc({runId:r.runId,issueKey:r.issueKey,issueSummary:r.issueSummary,projectId:r.project.id,repoName:r.project.repoName,environmentName:n.name,requestedBy:r.requestedBy,createdAt:new Date().toISOString()}),e("info",`Deploy to "${n.name}" is waiting for approval on the dashboard \u2014 no step has run yet`),await qe(r,`**Allwright: deploy to \`${n.name}\` needs approval.**
|
|
569
570
|
|
|
570
|
-
${r.requestedBy?`Requested by ${r.requestedBy}. `:""}Nothing has been executed yet. Approve it on the Allwright dashboard to run the ${n.steps.length} deploy step(s), or reject to cancel. (run \`${r.runId}\`)`),t("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${r.issueKey} to ${n.name}`});return}await
|
|
571
|
+
${r.requestedBy?`Requested by ${r.requestedBy}. `:""}Nothing has been executed yet. Approve it on the Allwright dashboard to run the ${n.steps.length} deploy step(s), or reject to cancel. (run \`${r.runId}\`)`),t("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${r.issueKey} to ${n.name}`});return}await qc(r,e,t)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await qe(r,`**Allwright deploy to \`${n.name}\` failed.**
|
|
571
572
|
|
|
572
573
|
${i.slice(0,800)}
|
|
573
574
|
|
|
574
|
-
(run \`${r.runId}\`)`),t("failed",{error:i})}}function
|
|
575
|
+
(run \`${r.runId}\`)`),t("failed",{error:i})}}function om(r){let e=r.environment;if(!r.cfg.deploy.enabled)return"deployments are turned off on this runner. Deploy steps are shell commands, so they stay disabled until someone with access to this machine runs `allwright deploy enable`.";if(!e.steps.length)return`environment "${e.name}" has no deploy steps configured \u2014 add them in the dashboard first`;if(e.promotionMode==="merge_and_deploy"&&!e.branch)return`environment "${e.name}" is set to merge-and-deploy but has no branch configured`;if(e.useDedicatedCheckout&&!e.branch)return`environment "${e.name}" wants a dedicated checkout but has no branch configured`;let t=Jt(r.cfg,r.project.repoName,e.name),n=e.requiredSecrets.filter(s=>!t[s]&&!process.env[s]);return n.length?`missing deploy secret(s) on this runner: ${n.join(", ")}. Set them with: allwright env set "${r.project.repoName}" "${e.name}" ${n[0]}=...`:null}async function qc(r,e,t){let n=r.environment,s=Jt(r.cfg,r.project.repoName,n.name),i=dm(Object.values(s)),o=Date.now();if(t("running"),e("info",`Deploying ${r.issueKey} to "${n.name}"`+(r.requestedBy?` (requested by ${r.requestedBy})`:"")+` \u2014 ${n.steps.length} step(s), ${n.timeoutSeconds}s budget`),n.auditBeforeDeploy){e("info",`Pre-deploy ${n.auditBeforeDeploy} audit starting (advisory \u2014 will not block)`);try{let j=await Qr({projectId:r.project.id,repoPath:r.repoPath,role:n.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",claudeBin:r.cfg.claudeBin,jira:r.jira});if(!j.ok)e("warn",`Pre-deploy audit could not run: ${j.error} \u2014 deploying anyway (advisory)`);else if(!j.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let U={};for(let f of j.audit.findings)U[f.severity]=(U[f.severity]??0)+1;e("warn",`Pre-deploy audit: ${j.audit.findings.length} finding(s) (`+Object.entries(U).map(([f,g])=>`${g} ${f}`).join(", ")+") \u2014 full report on the Audits page. Deploying anyway (advisory).");for(let f of j.audit.findings.slice(0,5))e("warn",` [${f.severity}] ${f.title} \u2014 ${f.evidence[0]?.file??""}`)}}catch(j){e("warn",`Pre-deploy audit crashed: ${j instanceof Error?j.message:String(j)} \u2014 deploying anyway`)}}if(n.requireSyncCheck){if(!n.previousEnvBranch||!n.branch){let U=n.branch?`"${n.name}" requires a branch sync check, but no earlier stage in the pipeline has a branch to compare against. Check the pipeline order on the Environments page (was "${n.name}" moved to the top?), or turn the check off.`:`"${n.name}" requires a branch sync check but has no branch set \u2014 set it, or turn the check off`;e("error",U),await qe(r,`**Allwright refused to deploy to \`${n.name}\`.**
|
|
575
576
|
|
|
576
577
|
${U}
|
|
577
578
|
|
|
578
|
-
(run \`${r.runId}\`)`),t("failed",{error:U,errorKind:"guard"});return}let j=await
|
|
579
|
+
(run \`${r.runId}\`)`),t("failed",{error:U,errorKind:"guard"});return}let j=await um(r,e);if(j){await qe(r,j.comment),t("failed",{error:j.error,...j.guard?{errorKind:"guard"}:{}});return}}let a=r.repoPath;if(n.useDedicatedCheckout||n.promotionMode==="merge_and_deploy"?(e("info",`Preparing ${n.name} checkout at origin/${n.branch}`),a=await Zi({repoPath:r.repoPath,repoName:r.project.repoName,envName:n.name,branch:n.branch,attached:n.promotionMode==="merge_and_deploy"})):e("info",`No dedicated checkout for "${n.name}" \u2014 running the steps in the mapped checkout as it is`),n.promotionMode==="merge_and_deploy"){let j=Rt(n.ticketBranchTemplate,{issueKey:r.issueKey});e("info",`Merging "${j}" into "${n.branch}"`);let U=await Ki(a,j,`Deploy ${r.issueKey} to ${n.name}
|
|
579
580
|
|
|
580
581
|
Allwright run ${r.runId}`);if(!U.ok){e("error",U.reason??"merge failed"),await qe(r,`**Allwright deploy to \`${n.name}\` failed before running anything.**
|
|
581
582
|
|
|
582
|
-
${U.reason}`),t("failed",{error:U.reason});return}U.alreadyMerged?e("info",`"${j}" is already in "${n.branch}" \u2014 nothing to merge`):(e("info",`Pushing "${n.branch}" to origin`),await
|
|
583
|
+
${U.reason}`),t("failed",{error:U.reason});return}U.alreadyMerged?e("info",`"${j}" is already in "${n.branch}" \u2014 nothing to merge`):(e("info",`Pushing "${n.branch}" to origin`),await Vi(a,n.branch))}let l=await Rn(a).catch(()=>"");l&&e("info",`Deploying commit ${l.slice(0,10)}`);let d=cm(a,n.workdir),p={...process.env,...s,ALLWRIGHT_ENVIRONMENT:n.name,ALLWRIGHT_ISSUE_KEY:r.issueKey,ALLWRIGHT_RUN_ID:r.runId,ALLWRIGHT_DEPLOY_REF:l,ALLWRIGHT_BRANCH:n.branch,TICKETPILOT_ENVIRONMENT:n.name,TICKETPILOT_ISSUE_KEY:r.issueKey,TICKETPILOT_RUN_ID:r.runId,TICKETPILOT_DEPLOY_REF:l,TICKETPILOT_BRANCH:n.branch},v=0,S=n.timeoutSeconds*1e3;for(let[j,U]of n.steps.entries()){let f=S-(Date.now()-o);if(f<=0){let b=`deploy exceeded its ${n.timeoutSeconds}s budget before step ${j+1}`;e("error",b),await qe(r,`**Allwright deploy to \`${n.name}\` timed out.**
|
|
583
584
|
|
|
584
|
-
${b}`),t("timed_out",{error:b,deployedRef:l});return}e("info",`\u25B6 step ${j+1}/${n.steps.length}: ${U.name}`);let g=await
|
|
585
|
+
${b}`),t("timed_out",{error:b,deployedRef:l});return}e("info",`\u25B6 step ${j+1}/${n.steps.length}: ${U.name}`);let g=await lm({command:U.run,cwd:d,env:p,timeoutMs:f,onLine:(b,I)=>{v++,v===Nc&&e("warn","(output truncated \u2014 deploy log limit reached)"),!(v>=Nc)&&e(b,i(I))}});if(g.timedOut){let b=`step "${U.name}" hit the ${n.timeoutSeconds}s deploy budget and was killed`;e("error",b),await qe(r,`**Allwright deploy to \`${n.name}\` timed out.**
|
|
585
586
|
|
|
586
|
-
${b}`),t("timed_out",{error:b,deployedRef:l});return}if(g.code!==0){if(U.continueOnError){e("warn",`step "${U.name}" exited ${g.code} \u2014 continuing (marked continue-on-error)`);continue}let b="";try{b=i(await
|
|
587
|
+
${b}`),t("timed_out",{error:b,deployedRef:l});return}if(g.code!==0){if(U.continueOnError){e("warn",`step "${U.name}" exited ${g.code} \u2014 continuing (marked continue-on-error)`);continue}let b="";try{b=i(await Di(a))}catch{}let I=`step ${j+1} "${U.name}" failed with exit code ${g.code}`+(g.tail?`: ${i(g.tail)}`:"")+(b?`
|
|
587
588
|
|
|
588
589
|
Checkout at failure:
|
|
589
590
|
${b}`:"");e("error",I),await qe(r,`**Allwright deploy to \`${n.name}\` failed.**
|
|
@@ -599,45 +600,48 @@ ${i(g.tail).slice(0,1200)}
|
|
|
599
600
|
${b.slice(0,800)}
|
|
600
601
|
\`\`\`
|
|
601
602
|
|
|
602
|
-
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${r.runId}\`)`),t("failed",{error:I.slice(0,1600),deployedRef:l});return}e("info",`\u2713 step ${j+1}/${n.steps.length}: ${U.name}`)}t("posting");let x=Math.round((Date.now()-o)/1e3);r.issueKey!==
|
|
603
|
+
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${r.runId}\`)`),t("failed",{error:I.slice(0,1600),deployedRef:l});return}e("info",`\u2713 step ${j+1}/${n.steps.length}: ${U.name}`)}t("posting");let x=Math.round((Date.now()-o)/1e3);r.issueKey!==wr.BRANCH_DEPLOY_ISSUE_KEY&&await qe(r,`**Allwright deployed \`${r.issueKey}\` to \`${n.name}\`.**
|
|
603
604
|
|
|
604
605
|
`+(l?`Commit: \`${l.slice(0,10)}\`${n.branch?` on \`${n.branch}\``:""}
|
|
605
606
|
`:"")+`${n.steps.length} step(s) in ${x}s.`+(r.requestedBy?` Requested by ${r.requestedBy}.`:"")+`
|
|
606
607
|
|
|
607
|
-
(run \`${r.runId}\`)`);let w=await
|
|
608
|
+
(run \`${r.runId}\`)`);let w=await am(r,e,l);t("succeeded",{resultSummary:`Deployed to ${n.name}${l?` at ${l.slice(0,10)}`:""} in ${x}s`+(w!==null?` \xB7 ${w} ticket(s) moved to "${n.deployToColumn}"`:""),deployedRef:l}),e("info",`Deploy to "${n.name}" succeeded in ${x}s`)}async function am(r,e,t){let n=r.environment;if(!n.deployFromColumn||!n.deployToColumn)return null;let s=new Date().toISOString().slice(0,10),i;try{i=await r.jira.search(`project = "${r.project.jiraProjectKey}" AND status = "${n.deployFromColumn}" ORDER BY updated ASC`,50)}catch(a){return e("warn",`deploy succeeded, but listing tickets in "${n.deployFromColumn}" failed: ${a instanceof Error?a.message:a} \u2014 move them by hand`),null}if(!i.length)return e("info",`No tickets in "${n.deployFromColumn}" to move`),0;e("info",`Moving ${i.length} ticket(s) from "${n.deployFromColumn}" to "${n.deployToColumn}"`);let o=0;for(let a of i)try{if(await r.jira.addComment(a.key,`**Allwright: deployed to \`${n.name}\` on ${s}.**
|
|
608
609
|
|
|
609
610
|
`+(t?`Commit: \`${t.slice(0,10)}\`${n.branch?` on \`${n.branch}\``:""}
|
|
610
|
-
`:"")+(r.requestedBy?`Requested by ${r.requestedBy}. `:"")+`(run \`${r.runId}\`)`),!await r.jira.transitionByName(a.key,n.deployToColumn)){e("warn",`${a.key}: no workflow transition to "${n.deployToColumn}" from its current status \u2014 left in place`),await r.jira.addComment(a.key,`**Allwright could not move this ticket to \`${n.deployToColumn}\`** \u2014 no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${r.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${a.key} \u2192 "${n.deployToColumn}"`)}catch(
|
|
611
|
+
`:"")+(r.requestedBy?`Requested by ${r.requestedBy}. `:"")+`(run \`${r.runId}\`)`),!await r.jira.transitionByName(a.key,n.deployToColumn)){e("warn",`${a.key}: no workflow transition to "${n.deployToColumn}" from its current status \u2014 left in place`),await r.jira.addComment(a.key,`**Allwright could not move this ticket to \`${n.deployToColumn}\`** \u2014 no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${r.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${a.key} \u2192 "${n.deployToColumn}"`)}catch(c){e("warn",`${a.key}: sweep failed (${c instanceof Error?c.message:c}) \u2014 left in "${n.deployFromColumn}"`)}return e("info",`Moved ${o}/${i.length} ticket(s) to "${n.deployToColumn}"`),o}async function um(r,e){let t=r.environment,n=t.previousEnvBranch,s=(a,c=!1)=>({error:a,guard:c,comment:`**Allwright could not deploy \`${r.issueKey}\` to \`${t.name}\`.**
|
|
611
612
|
|
|
612
613
|
${a}
|
|
613
614
|
|
|
614
|
-
(run \`${r.runId}\`)`});e("info",`Checking "${t.branch}" is in sync with "${n}" before deploying`);try{await
|
|
615
|
+
(run \`${r.runId}\`)`});e("info",`Checking "${t.branch}" is in sync with "${n}" before deploying`);try{await Jr(r.repoPath,n),await Jr(r.repoPath,t.branch)}catch(a){return s(`sync check could not fetch branches: ${a instanceof Error?a.message:String(a)}`)}let i;try{i=await Hi(r.repoPath,`origin/${n}`,`origin/${t.branch}`)}catch(a){return s(`sync check failed: ${a instanceof Error?a.message:String(a)}`)}if(!i)return e("info",`"${t.branch}" already matches "${n}" \u2014 continuing`),null;e("warn",`"${t.branch}" and "${n}" have diverged \u2014 opening a PR instead of deploying`);let o=At(ce()??r.cfg,r.project.repoName);if(!o)return s(`"${t.branch}" and "${n}" have diverged, and no GitHub token applies to this repo to open a PR. Run \`allwright github set-token\`, or merge them manually, then retry the deploy.`,!0);try{let a=await pr(r.repoPath),c=mr(a);if(!c)throw new Error(`could not parse a GitHub owner/repo from origin "${a}"`);let d=await new Oe(o).createPullRequest(c.owner,c.repo,{title:`Sync ${t.name} (${t.branch}) with ${n}`,head:n,base:t.branch,body:`Allwright opened this automatically while trying to deploy \`${r.issueKey}\` to \`${t.name}\`: \`${t.branch}\` doesn't have everything that's on \`${n}\` yet, so deploying now would ship different code than what was validated there. Merge this PR, then retry the deploy.
|
|
615
616
|
|
|
616
|
-
(run \`${r.runId}\`)`});return s(`"${t.branch}" is not in sync with "${n}" \u2014 opened ${d.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(a){return s(`could not open a sync PR: ${a instanceof Error?a.message:String(a)}`)}}function
|
|
617
|
-
`)}))},
|
|
617
|
+
(run \`${r.runId}\`)`});return s(`"${t.branch}" is not in sync with "${n}" \u2014 opened ${d.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(a){return s(`could not open a sync PR: ${a instanceof Error?a.message:String(a)}`)}}function cm(r,e){if(!e.trim())return r;let t=br.default.resolve(r,e),n=br.default.relative(r,t);if(n.startsWith("..")||br.default.isAbsolute(n))throw new Error(`working directory "${e}" is outside the repository checkout`);return t}function lm(r){return new Promise(e=>{let t=(0,Ls.spawn)("bash",["-lc",r.command],{cwd:r.cwd,env:r.env,detached:!0,stdio:["ignore","pipe","pipe"]}),n=[],s=l=>{n.push(l),n.length>20&&n.shift()},i=!1,o=!1,a=l=>{i||(i=!0,clearTimeout(c),e({code:l,timedOut:o,tail:n.join(`
|
|
618
|
+
`)}))},c=setTimeout(()=>{o=!0,Mc(t.pid,"SIGTERM"),setTimeout(()=>Mc(t.pid,"SIGKILL"),1e4).unref()},r.timeoutMs);bo.default.createInterface({input:t.stdout}).on("line",l=>{s(l),r.onLine("info",l)}),bo.default.createInterface({input:t.stderr}).on("line",l=>{s(l),r.onLine("warn",l)}),t.on("error",l=>{s(`failed to start: ${l.message}`),a(127)}),t.on("close",l=>a(l??1))})}function Mc(r,e){if(r)try{process.kill(-r,e)}catch{try{process.kill(r,e)}catch{}}}function dm(r){let e=r.filter(t=>t&&t.length>=6).sort((t,n)=>n.length-t.length);return e.length?t=>{let n=t;for(let s of e)n=n.split(s).join("***");return n}:t=>t}async function qe(r,e){if(r.issueKey!==wr.BRANCH_DEPLOY_ISSUE_KEY)try{await r.jira.addComment(r.issueKey,e)}catch(t){m.error(`could not post deploy comment to ${r.issueKey}: ${t}`)}}function ko(r){return js(r)!==null}async function Bc(r,e){let t=js(e);if(!t)return;let{emit:n,setStatus:s}=wo({runId:e,transport:r.transport}),i=r.lookup(t.projectId,t.environmentName);if(!i){let a=`approved, but environment "${t.environmentName}" is no longer in this runner's config (deleted or renamed?) \u2014 nothing was deployed`;n("error",a),s("failed",{error:a}),Os(e);return}Os(e);let o={runId:e,project:i.project,environment:i.environment,issueKey:t.issueKey,issueSummary:t.issueSummary,repoPath:i.repoPath,cfg:r.cfg,jira:r.jiraFor(i.project.repoName),transport:r.transport,requestedBy:t.requestedBy};n("info",`Approved \u2014 running the ${i.environment.steps.length} deploy step(s) now`);try{await qc(o,n,s)}catch(a){let c=a instanceof Error?a.message:String(a);n("error",`Deploy failed: ${c}`),await qe(o,`**Allwright deploy failed.**
|
|
618
619
|
|
|
619
|
-
${
|
|
620
|
+
${c.slice(0,800)}`),s("failed",{error:c})}}async function Fc(r,e){let t=js(e);if(!t)return;let{emit:n,setStatus:s}=wo({runId:e,transport:r.transport});Os(e),n("info",`Deploy to "${t.environmentName}" was rejected \u2014 nothing ran`);let i=r.lookup(t.projectId,t.environmentName);try{await r.jiraFor(i?.project.repoName??"").addComment(t.issueKey,`**Allwright: deploy to \`${t.environmentName}\` was rejected.**
|
|
620
621
|
|
|
621
|
-
No deploy step was executed. (run \`${e}\`)`)}catch(o){m.error(`could not post rejection comment to ${t.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var
|
|
622
|
+
No deploy step was executed. (run \`${e}\`)`)}catch(o){m.error(`could not post rejection comment to ${t.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var hm=k.object({steps:k.array(wr.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),fm=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"],Dc=24e3;function So(r){for(let e of fm){let t=br.default.join(r,e);try{if(!an.default.existsSync(t))continue;let n=an.default.readFileSync(t,"utf8");if(!n.trim())continue;return{path:e,content:n.length>Dc?n.slice(0,Dc)+`
|
|
622
623
|
|
|
623
|
-
[\u2026document truncated\u2026]`:n}}catch{continue}}return null}var
|
|
624
|
-
-
|
|
625
|
-
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
624
|
+
[\u2026document truncated\u2026]`:n}}catch{continue}}return null}var Lc=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function Zc(r){return Kc("bash",["-lc",`command -v ${JSON.stringify(r)}`]).trim().length>0}function Kc(r,e){try{let t=(0,Ls.spawnSync)(r,e,{encoding:"utf8",timeout:5e3});return t.status===0?t.stdout??"":""}catch{return""}}function pm(r){let e=r.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],t=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return t.length?`
|
|
625
|
+
- absolute paths the document mentions, checked on THIS machine:
|
|
626
|
+
${t.map(s=>` - ${s}: ${an.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
|
|
627
|
+
`)}`:""}function mm(r,e,t,n=""){let s=Lc.filter(a=>Zc(a)),i=Lc.filter(a=>!s.includes(a)),o=Object.keys(Jt(r,e,t));return`About the machine these steps will run on (gathered by the runner, trust it):
|
|
628
|
+
- available tools: ${s.join(", ")||"(none of the common ones)"}
|
|
629
|
+
- NOT installed: ${i.join(", ")||"(none missing)"}
|
|
630
|
+
- secrets already stored for this environment (names only): ${o.join(", ")||"(none yet)"}`+pm(n)}async function Vc(r){let e=[];if(e.push(an.default.existsSync(r.repoPath)?{name:"repo-path",ok:!0,detail:r.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${r.repoPath}`}),e.push({name:"deploys-enabled",ok:r.cfg.deploy.enabled,detail:r.cfg.deploy.enabled?"enabled on this runner":"disabled \u2014 run: allwright deploy enable (then restart the runner)"}),r.workdir){let a=br.default.isAbsolute(r.workdir)?r.workdir:br.default.join(r.repoPath,r.workdir);e.push(an.default.existsSync(a)?{name:"workdir",ok:!0,detail:a}:{name:"workdir",ok:!1,detail:`does not exist: ${a}`})}if(r.branch){let a=Kc("git",["-C",r.repoPath,"ls-remote","--heads","origin",r.branch]);e.push(a.trim()?{name:"branch",ok:!0,detail:`origin/${r.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${r.branch}" (or the remote is unreachable)`})}let t=Jt(r.cfg,r.repoName,r.environmentName),n=new Set(r.requiredSecrets);for(let a of r.steps)for(let c of a.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))n.add(c[1]);let s=[...n].filter(a=>!t[a]&&!process.env[a]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} \u2014 set with: allwright env set "${r.repoName}" "${r.environmentName}" ${s[0]}=...`:`${n.size} present`});let i=new Set;for(let a of r.steps)for(let c of a.run.split(/&&|\|\||;|\|/)){let l=c.trim().split(/\s+/),d=l.shift();for(;d&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(d)||d==="sudo"||d==="env"||d==="nohup");)d=l.shift();!d||d.startsWith("$")||d.startsWith("#")||d.startsWith("(")||i.add(d)}let o=[...i].filter(a=>!Zc(a));return e.push({name:"binaries",ok:o.length===0,detail:o.length?`not found on this machine: ${o.join(", ")}`:`${i.size} found: ${[...i].slice(0,12).join(", ")}`}),{ok:e.every(a=>a.ok),checks:e}}async function Hc(r){let e=So(r.repoPath);if(!e)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:'this repo has no deploy document. Create DEPLOY.md at the repo root (or .ticketpilot/deploy.md) describing how this project actually deploys \u2014 the same commands you run by hand. "Ask Claude for steps" translates that document; it does not guess.'};let t=mm(r.cfg,r.repoName,r.environmentName,e.content),n=Rt(wr.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:r.environmentName,docPath:e.path,docContent:e.content,notes:r.notes.trim()||"(nothing specified)",machineContext:t}),s=await Ue.run({repoPath:r.repoPath,prompt:n,timeoutSeconds:r.timeoutSeconds,bin:r.cfg.claudeBin,mode:"read_only",maxTurns:30,sessionId:(0,Uc.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=gm(s.resultText);return i?{ok:!0,...i}:(m.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
|
|
631
|
+
`+s.resultText.slice(0,4e3)),{ok:!1,steps:[],requiredSecrets:[],notes:"",error:`Claude answered, but not in the JSON shape we expected, so there is nothing safe to fill in. Try again, or write the steps by hand. Its answer started: "${s.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`})}function gm(r){for(let e of ym(r)){let t;try{t=JSON.parse(e)}catch{continue}let n=hm.safeParse(_m(t));if(n.success&&n.data.steps.length||n.success&&n.data.notes.trim())return n.data}return null}function ym(r){let e=[];for(let s of r.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let t=r.indexOf("{"),n=r.lastIndexOf("}");return t>=0&&n>t&&e.push(r.slice(t,n+1)),e}function _m(r){if(!r||typeof r!="object")return r;let e=r,n=(Array.isArray(r)?r:Array.isArray(e.steps)?e.steps:Array.isArray(e.deploy_steps)?e.deploy_steps:Array.isArray(e.deploySteps)?e.deploySteps:[]).map((o,a)=>{if(typeof o=="string")return o.trim()?{name:zc(o,a),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,l=vo(c.run,c.command,c.cmd,c.script,c.shell);return l?{name:(vo(c.name,c.title,c.description)??zc(l,a)).slice(0,120),run:l,continueOnError:c.continueOnError===!0||c.continue_on_error===!0}:null}).filter(Boolean),s=e.requiredSecrets??e.required_secrets??e.secrets,i=Array.isArray(s)?s.filter(o=>typeof o=="string"):s&&typeof s=="object"?Object.keys(s):[];return{steps:n.slice(0,50),requiredSecrets:i.slice(0,50),notes:vo(e.notes,e.note,e.explanation)??""}}function vo(...r){for(let e of r)if(typeof e=="string"&&e.trim())return e.trim()}function zc(r,e){return(r.split(`
|
|
632
|
+
`)[0].trim()||`Step ${e+1}`).slice(0,120)}gr();ct();function To(r,e){if(!r.componentRoutes.length)return{project:r};let t=e.filter(Boolean);if(!t.length)return{error:`no Jira component set \u2014 project "${r.name}" routes by component (${r.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let n=r.componentRoutes.filter(i=>t.includes(i.component));if(!n.length)return{error:`component(s) [${t.join(", ")}] not mapped \u2014 known: `+r.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(n.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) \u2014 ambiguous, refusing`}:{project:{...r,repoName:n[0].repoName}}}var Gc=24*3600*1e3,Us=14,vm=Us*24*3600*1e3,bm=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),qs=class{constructor(e,t,n){this.cfg=e;this.jiraFor=t;this.transport=n}cfg;jiraFor;transport;projects=[];rules=[];environments=[];inFlight=new Set;repoQueues=new Map;envQueues=new Map;timer=null;ticking=!1;paused=!1;jiraOf(e){return this.jiraFor(e.repoName)}routingWarned=new Set;warnRoutingOnce(e,t){this.routingWarned.has(e)||(this.routingWarned.add(e),m.warn(`Component routing refused \u2014 ${t}`))}resolveClaudeProfile(e,t){if(!t)return;let n=this.cfg.claudeProfiles[t]?.configDir;return!n&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${t}" is not set up on this runner (allwright claude login "${t}") \u2014 using the runner's own login instead.`}),m.warn(`run ${e}: claude profile "${t}" missing locally \u2014 using default login`)),n}setConfig(e,t,n=!1,s=[]){this.projects=e,this.rules=t,this.environments=s;let i=t.filter(o=>o.enabled).length;m.info(`config synced: ${e.length} project(s), ${t.length} rule(s) (${i} enabled), ${s.length} environment(s)`),n!==this.paused&&(m.info(n?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=n)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),m.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let t=this.projects.find(s=>s.repoName===e.repoName);if(!t)continue;let n=Ku(t.id,e.role);if(!(n&&Date.now()-new Date(n).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{m.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=await Qr({projectId:t.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",claudeBin:this.cfg.claudeBin,jira:this.jiraFor(e.repoName)});if(s.ok){let i=s.audit.findings.length;m.info(`Scheduled audit done: ${i} finding(s) \u2014 drift visible on the Audits page`)}else m.warn(`Scheduled audit failed: ${s.error}`)}catch(s){m.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let t of this.rules){if(!t.enabled)continue;let n=this.projects.find(i=>i.id===t.projectId);if(!n)continue;let s=this.cfg.repos[n.repoName];if(!s){m.warn(`rule "${t.name}": no local path for repo "${n.repoName}" \u2014 run: allwright repo add "${n.repoName}" /path/to/checkout`);continue}t.action.type==="deploy"?await this.pollDeployRule(t,n,s.path):t.action.type==="respond"?await this.pollRespondRule(t,n,s.path):(e.has(n.id)||(e.add(n.id),await this.sweepNeedsInput(n)),t.trigger.type==="comment_keyword"&&await this.sweepRevisions(t,n),await this.pollRule(t,n,s.path))}}catch(e){m.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async sweepGitHubApprovals(){let e=Object.values(Mn());if(!e.length)return;let t=ce()??this.cfg,n=new Map,s=i=>{let o=At(t,i);if(!o)return null;let a=n.get(o);return a||n.set(o,a=new Oe(o)),a};for(let i of e.slice(0,10)){let o=s(i.repoName);if(!o)continue;let a=`gh-approve:${i.runId}`;if(this.inFlight.has(a))continue;let c,l;try{[c,l]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(S){m.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${S instanceof Error?S.message:S}`);continue}if(!l)continue;let d={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(l.merged){m.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub \u2014 completing the run`),this.inFlight.add(a);try{await zn(d,i.runId,l.headSha)}finally{this.inFlight.delete(a)}continue}if(l.state==="closed"){m.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub \u2014 failing the run`);let S=this.jiraFor(i.repoName),x=`PR #${i.prNumber} was closed on GitHub without merging`;await S.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
|
|
629
633
|
|
|
630
634
|
PR: ${i.prUrl}
|
|
631
635
|
|
|
632
|
-
The run is marked failed. Remove the \`${i.failedLabel}\` label (or hit Retry on the Allwright board) to implement again. (run \`${i.runId}\`)`).catch(()=>{}),await S.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:x}),
|
|
636
|
+
The run is marked failed. Remove the \`${i.failedLabel}\` label (or hit Retry on the Allwright board) to implement again. (run \`${i.runId}\`)`).catch(()=>{}),await S.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:x}),_r(i.runId);continue}l.mergeableState==="dirty"?i.conflictNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: the pull request for this ticket has merge conflicts.** The base branch moved after this change was built, so GitHub cannot merge it as-is.
|
|
633
637
|
|
|
634
638
|
PR: ${i.prUrl}
|
|
635
639
|
|
|
636
|
-
To fix: Reject this run on the Allwright dashboard (that closes the conflicted PR), then post the implement trigger comment again \u2014 a fresh run rebuilds the change on the current base. Or resolve the conflicts manually on branch \`${i.branch}\`; approval works normally once the PR is conflict-free. (run \`${i.runId}\`)`).catch(()=>{}),i.conflictNotified=!0,
|
|
640
|
+
To fix: Reject this run on the Allwright dashboard (that closes the conflicted PR), then post the implement trigger comment again \u2014 a fresh run rebuilds the change on the current base. Or resolve the conflicts manually on branch \`${i.branch}\`; approval works normally once the PR is conflict-free. (run \`${i.runId}\`)`).catch(()=>{}),i.conflictNotified=!0,nn(i),m.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} \u2014 ticket notified`)):i.conflictNotified&&l.mergeableState!==null&&l.mergeableState!=="unknown"&&(i.conflictNotified=!1,nn(i));let p=c.filter(S=>S.state==="APPROVED"||S.state==="CHANGES_REQUESTED").sort((S,x)=>S.submittedAt.localeCompare(x.submittedAt)),v=p[p.length-1];if(v){if(v.state==="CHANGES_REQUESTED"){i.changesRequestedNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: changes were requested on the pull request** (by ${v.user}).
|
|
637
641
|
|
|
638
642
|
PR: ${i.prUrl}
|
|
639
643
|
|
|
640
|
-
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),
|
|
644
|
+
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),nn({...i,changesRequestedNotified:!0}),m.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} \u2014 ticket notified`));continue}if(v.commitId===l.headSha){m.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${v.user} \u2014 completing the run`),this.inFlight.add(a);try{await zn(d,i.runId,v.commitId)}catch(S){m.warn(`github-approval completion failed for ${i.runId}: ${S instanceof Error?S.message:S}`)}finally{this.inFlight.delete(a)}}}}}async sweepMergedPRs(){let e=Object.values(Ps());if(!e.length)return;let t=ce()??this.cfg,n=new Map,s=a=>{let c=At(t,a);if(!c)return null;let l=n.get(c);return l||n.set(c,l=new Oe(c)),l},i=20,o=720*3600*1e3;for(let a of e.slice(0,i)){let c=s(a.repoName);if(!c)continue;if(Date.now()-new Date(a.createdAt).getTime()>o){m.warn(`merge watch for ${a.issueKey} PR #${a.prNumber} is over 30 days old \u2014 dropping`),Nn(a.runId);continue}let l;try{l=await c.getPullRequest(a.owner,a.repo,a.prNumber)}catch(v){m.warn(`merge check failed for ${a.owner}/${a.repo}#${a.prNumber}: ${v instanceof Error?v.message:v}`);continue}if(!l){Nn(a.runId);continue}if(l.state==="open")continue;if(!l.merged){Nn(a.runId);continue}let d=this.jiraFor(a.repoName),p="";if(a.jiraTransitionOnMerge)try{p=await d.transitionByName(a.issueKey,a.jiraTransitionOnMerge)?`
|
|
641
645
|
|
|
642
646
|
Ticket moved to **${a.jiraTransitionOnMerge}**.`:`
|
|
643
647
|
|
|
@@ -647,17 +651,17 @@ Note: the "${a.jiraTransitionOnMerge}" transition failed: ${v instanceof Error?v
|
|
|
647
651
|
|
|
648
652
|
PR: ${a.prUrl} (merged at \`${l.headSha.slice(0,10)}\`)${p}
|
|
649
653
|
|
|
650
|
-
(run \`${a.runId}\`)`)}catch(v){m.warn(`could not post merge comment to ${a.issueKey}: ${v instanceof Error?v.message:v}`);continue}m.info(`PR #${a.prNumber} for ${a.issueKey} merged \u2014 ticket updated`),
|
|
654
|
+
(run \`${a.runId}\`)`)}catch(v){m.warn(`could not post merge comment to ${a.issueKey}: ${v instanceof Error?v.message:v}`);continue}m.info(`PR #${a.prNumber} for ${a.issueKey} merged \u2014 ticket updated`),Nn(a.runId)}}async sweepNeedsInput(e){let t;try{t=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${kr.NEEDS_INPUT_LABEL}"`,10)}catch(s){m.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!t.length)return;let n=sn();for(let s of t){let i=Object.values(n).filter(a=>a.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[kr.NEEDS_INPUT_LABEL]}).catch(()=>{}),m.warn(`${s.key}: needs-input label with no local pending record \u2014 removed`);continue}let o=null;for(let a of i){let c=`resume:${a.runId}`;if(this.inFlight.has(c))continue;if(Date.now()-new Date(a.createdAt).getTime()>vm){this.inFlight.add(c),this.abandonStaleInput(a,e).finally(()=>this.inFlight.delete(c));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(x){m.warn(`needs-input check failed for ${s.key}: ${x instanceof Error?x.message:x}`);continue}let l=new Date(a.questionsPostedAt).getTime(),d=o.comments.filter(x=>!Ge(x.body)&&new Date(x.created).getTime()>l);if(!d.length)continue;let p=Un(d),v=o.attachments;this.inFlight.add(c),m.info(`reply received on ${s.key} \u2014 resuming run ${a.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[kr.NEEDS_INPUT_LABEL]}).catch(x=>{m.warn(`could not remove needs-input label on ${s.key}: ${x}`)});let S={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};a.kind==="implement"?this.enqueueForRepo(a.baseRepoPath??a.repoPath,async()=>{try{await xc(a,p,v,S)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(a.repoPath,async()=>{try{await wc(a,p,v,S)}finally{this.inFlight.delete(c)}})}}}async abandonStaleInput(e,t){m.warn(`${e.issueKey}: needs-input unanswered for over ${Us}d \u2014 abandoning run ${e.runId}`);try{await this.jiraOf(t).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
|
|
651
655
|
|
|
652
|
-
No reply arrived within ${
|
|
656
|
+
No reply arrived within ${Us} days of the question above. This ticket has been labeled \`${e.failedLabel}\`; remove it and re-trigger to try again. (run \`${e.runId}\`)`),await this.jiraOf(t).editLabels(e.issueKey,{add:[e.failedLabel],remove:[kr.NEEDS_INPUT_LABEL]})}catch(n){m.warn(`could not post staleness notice for ${e.issueKey}: ${n}`)}e.kind==="implement"&&await Yr(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),Je(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Us} days`})}async pollRule(e,t,n){let s=e.trigger.type==="label_added"?await this.matchLabelTrigger(e,t):await this.matchCommentTrigger(e,t);for(let i of s){let o=`${e.id}:${i.issueKey}`;if(this.inFlight.has(o))continue;let a=To(t,i.components??[]);if("error"in a){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${a.error}`);continue}let c=a.project,l=c.repoName===t.repoName?n:this.cfg.repos[c.repoName]?.path;if(!l){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${c.repoName}" but it has no local checkout \u2014 run: allwright repo add "${c.repoName}" /path/to/checkout`);continue}let d=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!d.accepted||!d.runId){d.reason!=="duplicate"&&m.warn(`claim rejected for ${i.issueKey}: ${d.reason??"unknown"}`);continue}this.inFlight.add(o),m.info(`claimed run ${d.runId} for ${i.issueKey}`+(c.repoName!==t.repoName?` (routed \u2192 ${c.repoName})`:"")+(d.claudeProfile?` (claude profile "${d.claudeProfile}")`:""));let p=this.resolveClaudeProfile(d.runId,d.claudeProfile);this.enqueueForRepo(l,async()=>{try{await _o({runId:d.runId,rule:e,project:c,issueKey:i.issueKey,repoPath:l,cfg:this.cfg,jira:this.jiraOf(c),transport:this.transport,claudeConfigDir:p,actorEmail:d.actorEmail})}finally{this.inFlight.delete(o)}})}}async pollRespondRule(e,t,n){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),a=Date.now()-Gc;for(let c of i){let l=await this.jiraOf(t).getIssue(c.key);for(let d of l.comments){if(!d.body.toLowerCase().includes(o)||Ge(d.body)||new Date(d.created).getTime()<a||!d.id)continue;let p=`respond:${d.id}`;if(this.inFlight.has(p))continue;let v=To(t,c.components??[]);if("error"in v){this.warnRoutingOnce(`${e.id}:${c.key}`,`${c.key}: ${v.error}`);continue}let S=v.project,x=S.repoName===t.repoName?n:this.cfg.repos[S.repoName]?.path;if(!x){this.warnRoutingOnce(`${e.id}:${c.key}:path`,`${c.key}: routed to repo "${S.repoName}" but it has no local checkout \u2014 run: allwright repo add "${S.repoName}" /path/to/checkout`);continue}let w=await this.transport.claimRun({ruleId:e.id,issueKey:c.key,issueSummary:c.summary,triggerFingerprint:`question by ${d.author} at ${d.created}`,dedupKey:`respond:comment:${d.id}`,triggeredByAccountId:d.authorAccountId??void 0});if(!w.accepted||!w.runId){w.reason!=="duplicate"&&m.warn(`respond claim rejected for ${c.key}: ${w.reason??"unknown"}`);continue}this.inFlight.add(p),m.info(`claimed respond run ${w.runId}: ${c.key} (comment ${d.id})`+(S.repoName!==t.repoName?` (routed \u2192 ${S.repoName})`:"")+(w.claudeProfile?` (claude profile "${w.claudeProfile}")`:""));let j={author:d.author,body:d.body},U=this.resolveClaudeProfile(w.runId,w.claudeProfile);this.enqueueForRepo(x,async()=>{try{await _o({runId:w.runId,rule:e,project:S,issueKey:c.key,repoPath:x,cfg:this.cfg,jira:this.jiraOf(S),transport:this.transport,question:j,claudeConfigDir:U,actorEmail:w.actorEmail})}finally{this.inFlight.delete(p)}})}}}async sweepRevisions(e,t){let n=e.trigger;if(n.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.doneLabel}" AND updated >= "-2d"`,10)}catch(o){m.warn(`revision sweep failed for ${t.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=n.keyword.toLowerCase();for(let o of s)try{let a=await this.jiraOf(t).getIssue(o.key),c=null;for(let d of a.comments)Ge(d.body)&&(c=Math.max(c??0,new Date(d.created).getTime()));if(c===null||!a.comments.some(d=>!Ge(d.body)&&d.body.toLowerCase().includes(i)&&new Date(d.created).getTime()>c))continue;await this.jiraOf(t).editLabels(o.key,{remove:[n.doneLabel]}),m.info(`revision requested on ${o.key} (new "${n.keyword}" after completion) \u2014 done label removed, rule will re-fire`)}catch(a){m.warn(`revision check failed for ${o.key}: ${a instanceof Error?a.message:a}`)}}async pollDeployRule(e,t,n){if(e.action.type!=="deploy")return;let s=e.trigger.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t);for(let i of s){let o=`deploy:${i.dedupKey}`;if(this.inFlight.has(o))continue;let a=await this.transport.claimDeploy({projectId:t.id,ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,environmentName:i.environmentName,requestedByAccountId:i.requestedByAccountId,requestedByDisplayName:i.requestedByDisplayName,dedupKey:i.dedupKey,triggerFingerprint:i.fingerprint});if(!a.accepted||!a.runId||!a.environment){if(a.code==="duplicate")continue;a.reason&&a.runId?(await this.jiraOf(t).addComment(i.issueKey,`**Allwright did not deploy this ticket.**
|
|
653
657
|
|
|
654
658
|
${a.reason}`+(i.requestedByAccountId?`
|
|
655
659
|
|
|
656
660
|
Jira account id: \`${i.requestedByAccountId}\``:"")+`
|
|
657
661
|
|
|
658
|
-
(run \`${a.runId}\`)`).catch(l=>m.warn(`could not post refusal to ${i.issueKey}: ${l}`)),m.warn(`deploy refused for ${i.issueKey}: ${a.reason}`)):a.reason&&m.warn(`deploy claim rejected for ${i.issueKey}: ${a.reason}`);continue}let
|
|
659
|
-
`,{mode:384}),kr.default.renameSync(t,e),kr.default.chmodSync(e,384)}function Ju(r,e,t,n){let s=ko(),o=s[e]??{sessionId:e,projectId:r,title:t.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};o.messages.push({role:"user",text:t.slice(0,Hu)},{role:"agent",text:n.slice(0,Hu)}),o.messages=o.messages.slice(-ym),o.updatedAt=new Date().toISOString(),s[e]=o;let a=Object.values(s).filter(u=>u.projectId===o.projectId).sort((u,l)=>l.updatedAt.localeCompare(u.updatedAt));for(let u of a.slice(gm))delete s[u.sessionId];_m(s)}function Yu(r){return Object.values(ko()).filter(e=>e.projectId===r).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function So(r){return ko()[r]??null}var zg=$(Vl(),1),Ug=$(Hs(),1),qg=$(an(),1),Bg=$(Oo(),1),Fg=$(Do(),1),Zg=$(Fo(),1),td=$(Ys(),1),Kg=$(ed(),1);var Ko=td.default;var Ho=$(require("node:crypto"),1),Xe=$(Se(),1);function Vg(r){let e=r&&typeof r=="object"&&"name"in r?String(r.name):null;return e?`"${e}"`:"(unnamed)"}function Vo(r,e,t,n){r.push(`dropped ${e} ${t} \u2014 this runner is out of date and does not understand it yet (${n}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function Hg(r){if(!r||typeof r!="object"||r.type!=="config")return null;let e=r,t=[],n=[];for(let a of Array.isArray(e.projects)?e.projects:[]){let u=Xe.ProjectConfig.safeParse(a);u.success?n.push(u.data):Vo(t,"project","",u.error.issues[0]?.message??"invalid shape")}let s=[];for(let a of Array.isArray(e.rules)?e.rules:[]){let u=Xe.RuleConfig.safeParse(a);u.success?s.push(u.data):Vo(t,"rule",Vg(a),u.error.issues[0]?.message??"invalid shape")}let i=[];for(let a of Array.isArray(e.environments)?e.environments:[]){let u=Xe.EnvironmentConfig.safeParse(a);u.success?i.push(u.data):Vo(t,"environment","",u.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:n,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var Gg=2e4,Wg=6e4,Jg=5e3,Qs=class{constructor(e,t,n,s){this.wsUrl=e;this.runnerToken=t;this.meta=n;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===Ko.OPEN}connect(){if(this.closed)return;m.info(`connecting to control plane at ${this.wsUrl}`);let e=new Ko(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Xe.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let t=this.queue.splice(0,this.queue.length);for(let n of t)this.sendNow(n);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},Gg)}),e.on("message",t=>{let n;try{n=JSON.parse(t.toString())}catch(i){m.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Xe.parseServerMsg)(n)}catch(i){let o=Hg(n);if(!o){m.warn(`ignoring malformed server message: ${i}`);return}for(let a of o.warnings)m.warn(a);m.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand \u2014 applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)m.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===4003){m.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let n=Math.random()*.3+.85,s=Math.round(this.backoffMs*n);m.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,Wg)}),e.on("error",t=>{m.warn(`websocket error: ${t.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,m.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"){let t=this.pending.get(e.requestId);t&&(clearTimeout(t.timer),this.pending.delete(e.requestId),t.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=Jg){let t=this.queue.findIndex(n=>n.type==="run.log");t>=0?this.queue.splice(t,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Ho.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:t,...e})});return!n||n.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:n.accepted,runId:n.runId,reason:n.reason,claudeProfile:n.claudeProfile,actorEmail:n.actorEmail}}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Ho.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:t,...e})});return!n||n.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:n.accepted,runId:n.runId,environment:n.environment,reason:n.reason,code:n.code}}sendDeploySuggestResult(e,t){this.send({type:"deploy.suggest.result",requestId:e,...t})}sendChatTurnResult(e,t){this.send({type:"chat.turn.result",requestId:e,...t})}sendChatCreateTicketResult(e,t){this.send({type:"chat.create.ticket.result",requestId:e,...t,childKeys:t.childKeys??[]})}sendChatListResult(e,t){this.send({type:"chat.list.result",requestId:e,sessions:t})}sendChatLoadResult(e,t){this.send({type:"chat.load.result",requestId:e,...t})}sendBoardFetchResult(e,t){this.send({type:"board.fetch.result",requestId:e,...t,browseBaseUrl:t.browseBaseUrl??""})}sendAuditStartResult(e,t){this.send({type:"audit.start.result",requestId:e,...t})}sendAuditListResult(e,t){this.send({type:"audit.list.result",requestId:e,ok:t.ok,error:t.error,audits:t.audits??[]})}sendAuditGetResult(e,t){this.send({type:"audit.get.result",requestId:e,...t})}sendAuditReviewResult(e,t){this.send({type:"audit.review.result",requestId:e,...t})}sendKnowledgeListResult(e,t){this.send({type:"knowledge.list.result",requestId:e,ok:t.ok,error:t.error,files:t.files??[]})}sendKnowledgeSaveResult(e,t){this.send({type:"knowledge.save.result",requestId:e,...t})}sendEpicListResult(e,t){this.send({type:"epic.list.result",requestId:e,ok:t.ok,error:t.error,epics:t.epics??[],children:t.children??[]})}sendEpicSuggestResult(e,t){this.send({type:"epic.suggest.result",requestId:e,ok:t.ok,error:t.error,issueKey:t.issueKey??"",reason:t.reason??"",considered:t.considered??0})}sendTeamCredsResult(e,t){this.send({type:"team.creds.result",requestId:e,ok:t.ok,error:t.error,githubShared:t.githubShared??!1,sharedGithubLogin:t.sharedGithubLogin??"",entries:t.entries??[]})}sendBoardTriggerResult(e,t){this.send({type:"board.trigger.result",requestId:e,...t})}sendEnvPreflightResult(e,t){this.send({type:"env.preflight.result",requestId:e,...t})}sendJiraUsersResult(e,t){this.send({type:"jira.users.result",requestId:e,...t})}sendProjectTestResult(e,t,n){this.send({type:"project.test.result",requestId:e,ok:t,checks:n})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t})}};var fn=$(require("node:fs"),1),Go=$(require("node:path"),1),nd=require("node:child_process"),sd=require("node:util");var rd=(0,sd.promisify)(nd.execFile);async function ei(r,e,t=[]){let n=[],s=r.repos[e.repoName]?.jira??r.jira;if(!s)n.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else{let o=new ze(s);try{let a=await o.myself();n.push({name:"jira-auth",ok:!0,detail:`authenticated as ${a.displayName}`});try{await o.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),n.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable`})}catch(u){n.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey}: ${Vn(u)}`})}}catch(a){n.push({name:"jira-auth",ok:!1,detail:`Jira auth failed: ${Vn(a)}`})}}let i=r.repos[e.repoName];if(i&&fn.default.existsSync(i.path)){let o=Go.default.join(i.path,"CLAUDE.md"),a=fn.default.existsSync(o)&&fn.default.readFileSync(o,"utf8").trim().length>0;n.push({name:"memory-file",ok:a,detail:a?"CLAUDE.md present \u2014 the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file \u2014 it is what makes every run smarter than the last."});let u=bo(i.path);n.push({name:"deploy-doc",ok:u!==null,detail:u?`${u.path} present \u2014 deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys."})}if(!i)n.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" \u2014 run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!fn.default.existsSync(i.path))n.push({name:"repo-path",ok:!1,detail:`path does not exist: ${i.path}`});else{let o=fn.default.existsSync(Go.default.join(i.path,".git"));n.push({name:"repo-path",ok:!0,detail:`${i.path}${o?" (git checkout)":" (warning: not a git checkout)"}`})}try{let{stdout:o}=await rd(r.claudeBin,["--version"],{timeout:15e3});n.push({name:"claude-code",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"claude-code",ok:!1,detail:`cannot run "${r.claudeBin}": ${Vn(o)}`})}try{let{stdout:o}=await rd("git",["--version"],{timeout:15e3});n.push({name:"git",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"git",ok:!1,detail:`cannot run git: ${Vn(o)}`})}if(r.github?.token)try{let{GitHubClient:o}=await Promise.resolve().then(()=>(ut(),Qr)),a=await new o(r.github.token).whoami();n.push({name:"github-token",ok:!0,detail:`authenticated as ${a}`})}catch(o){n.push({name:"github-token",ok:!1,detail:Vn(o)})}else n.push({name:"github-token",ok:!0,detail:"not set \u2014 needed only for implement rules (allwright github set-token)"});if(t.length){r.deploy.enabled?n.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):n.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner \u2014 run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let o of t){let a=Wt(r,e.repoName,o.name),u=o.requiredSecrets.filter(l=>!a[l]&&!process.env[l]);n.push({name:`env:${o.name}`,ok:u.length===0,detail:u.length?`missing secret(s): ${u.join(", ")} \u2014 allwright env set "${e.repoName}" "${o.name}" ${u[0]}=...`:`${o.steps.length} step(s), ${o.requiredSecrets.length} secret(s) present`+(o.branch?`, deploys origin/${o.branch}`:"")})}}return n}function Vn(r){return(r instanceof Error?r.message:String(r)).slice(0,300)}var ae=new ga;ae.name("allwright").description("Allwright runner \u2014 runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(gs);ae.command("init").description("Interactive setup: enroll this runner and store credentials locally").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",id.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async r=>{let e=Ir.default.createInterface({input:process.stdin,output:process.stdout}),t=async(n,s,i=!1)=>{if(s)return s;let o=await e.question(`${n}: `);if(!o.trim())throw new Error(`${n} is required`);return o.trim()};try{let n=await t("Control plane URL",r.cpUrl),s=await t("Enrolment token (from the web UI)",r.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",r.jiraUrl),o=await t("Jira account email",r.jiraEmail),a=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",r.jiraToken,!0),u=wi.parse({controlPlaneUrl:n,runnerName:r.name,jira:{baseUrl:i,email:o,apiToken:a}}),l=await new ze(u.jira).myself();m.info(`Jira credential OK \u2014 authenticated as ${l.displayName}`),u=await cc(u,s),m.info(`Enrolled as runner "${u.runnerName}" (${u.runnerId})`),m.info(`Credentials saved to ${wt()} (mode 600, this machine only)`),m.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Jo=ae.command("repo").description("Map control-plane repo names to local checkouts");Jo.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(r,e)=>{let t=Q();t.repos[r]={path:e},ie(t),m.info(`mapped repo "${r}" -> ${e}`);try{let{originUrl:n}=await Promise.resolve().then(()=>(mr(),_c));m.info(` origin remote: ${await n(e)} \u2014 make sure this is the repo you meant`)}catch{m.warn(` could not read an origin remote at ${e} \u2014 is it a git checkout?`)}});Jo.command("list").description("Show configured repo mappings").action(()=>{let r=Q(),e=Object.entries(r.repos);if(!e.length)return m.info("no repos mapped yet");for(let[t,n]of e)m.info(`${t} -> ${n.path}`)});var ad=ae.command("claude").description("Per-user Claude login profiles \u2014 each teammate's runs bill their OWN Claude account");ad.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory \u2014 have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async r=>{if(!/^[a-zA-Z0-9._-]+$/.test(r))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=Q(),t=e.claudeProfiles[r]?.configDir??`${wt().replace(/runner\.json$/,"")}claude-profiles/${r}`;pn.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[r]={configDir:t},ie(e),m.info(`profile "${r}" -> ${t}`),m.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),m.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let n=(0,Hn.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>n.on("exit",()=>s())),m.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${r}".`),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});ad.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let r=Q(),e=Object.entries(r.claudeProfiles);if(m.info("default: this OS user's own Claude login (no profile)"),!e.length)return m.info("no named profiles yet \u2014 allwright claude login <name>");for(let[t,n]of e){let s=pn.default.existsSync(n.configDir)&&pn.default.readdirSync(n.configDir).length>0;m.info(`${t} -> ${n.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Jo.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane \u2014 delete the project on the dashboard separately.").action(r=>{let e=Q();if(!e.repos[r]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${i}`)}let t=e.repos[r].path;delete e.repos[r];let n=Object.keys(e.environments).filter(i=>i.startsWith(`${r}:`));for(let i of n)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==r),ie(e),m.info(`Removed "${r}" (was ${t})`),n.length&&m.info(`Also removed ${n.length} environment secret set(s): ${n.join(", ")}`),e.auditSchedules.length!==s&&m.info("Also removed its audit schedule(s)"),m.info("The checkout on disk was NOT touched \u2014 remove it yourself if you want it gone."),m.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var Yo=ae.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");Yo.command("install").description("Install + start the systemd service \u2014 detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(r=>{if(r.print){m.info(`
|
|
660
|
-
`+Wi(Gi()));return}xc(m)});Yo.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>Cc(m));Yo.command("status").description("systemctl status for the runner service").action(()=>{(0,Hn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});ae.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards \u2014 and only when no runs are active.").action(async()=>{m.info("Updating: npm install -g allwright@latest");let r=(0,Hn.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{r.on("exit",n=>n===0?e():t(new Error(`npm exited with code ${n}`))),r.on("error",t)}),m.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Gn=ae.command("jira").description("Per-repo Jira site overrides \u2014 for projects living on a different Atlassian site");Gn.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async r=>{let e=Q();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Ir.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question("Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim(),s=(await t.question("Jira account email: ")).trim(),i=(await t.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!n||!s||!i)throw new Error("all three values are required");let o={baseUrl:n,email:s,apiToken:i},a=await new ze(o).myself();m.info(`Jira credential OK \u2014 authenticated as ${a.displayName} on ${n}`),e.repos[r].jira=o,ie(e),m.info(`Saved: repo "${r}" now polls ${n} (other repos keep the runner-wide credential)`),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")}finally{t.close()}});Gn.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let r=Q();m.info(`runner-wide: ${r.jira?`${r.jira.baseUrl} (${r.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(r.repos))m.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(runner-wide credential)"}`)});Gn.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click \u2014 no restart needed.").action(async r=>{let e=Q(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Ir.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await n.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(l=>l.jira)].filter(l=>!!l),a=new Set,u=!1;for(let l of o)if(!a.has(l.baseUrl)){a.add(l.baseUrl);try{let d=await new ze({baseUrl:l.baseUrl,email:s,apiToken:i}).myself();m.info(`${l.baseUrl}: OK \u2014 authenticated as ${d.displayName}`),u=!0}catch{m.warn(`${l.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!u)throw new Error("credential failed on every configured Jira site \u2014 nothing saved");e.jiraUsers[t]={email:s,apiToken:i},ie(e),m.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{n.close()}});Gn.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let r=Q(),e=Object.entries(r.jiraUsers);if(!e.length)return m.info("none yet \u2014 everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,n]of e)m.info(`${t} -> posts to Jira as ${n.email}`)});Gn.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(r=>{let e=Q(),t=r.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],ie(e),m.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var mn=ae.command("github").description("GitHub credential for implement-mode rules");mn.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async r=>{let e=Ir.default.createInterface({input:process.stdin,output:process.stdout});try{let t=r.token??(await e.question("GitHub token (fine-grained PAT recommended): ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:n}=await Promise.resolve().then(()=>(ut(),Qr)),s=await new n(t).whoami(),i=Q();i.github={token:t,login:s},ie(i),m.info(`GitHub token OK \u2014 authenticated as ${s}`),m.info(`Saved to ${wt()} (mode 600, this machine only)`)}finally{e.close()}});mn.command("set <repoName>").description("Store a GitHub token for ONE repo only \u2014 overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async r=>{let e=Q();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Ir.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question(`GitHub token for "${r}" (fine-grained PAT scoped to just this repo): `)).trim();if(!n)throw new Error("token is required");let{GitHubClient:s}=await Promise.resolve().then(()=>(ut(),Qr)),i=await new s(n).whoami();e.repos[r].github={token:n,login:i},ie(e),m.info(`GitHub token OK \u2014 authenticated as ${i}`),m.info(`Saved: repo "${r}" now uses its own token (other repos keep the runner-wide one)`)}finally{t.close()}});mn.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional \u2014 without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async r=>{let e=Q(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Ir.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(ut(),Qr)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},ie(e),m.info(`GitHub token OK \u2014 authenticated as ${o}`),m.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{n.close()}});mn.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let r=Q(),e=Object.entries(r.githubUsers);if(!e.length)return m.info("no per-user GitHub tokens \u2014 everyone's PRs use the repo/runner-wide token");for(let[t]of e)m.info(`${t} -> own GitHub token stored`)});mn.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(r=>{let e=Q(),t=r.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],ie(e),m.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});mn.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let r=Q();m.info(`runner-wide: ${r.github?.token?"token set":"(not configured)"}`);for(let[t,n]of Object.entries(r.repos))m.info(`${t} -> ${n.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(r.githubUsers);m.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var Xo=ae.command("audit").description("Recurring specialist audits on this runner");Xo.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only \u2014 nothing blocks.").action((r,e,t)=>{let n=Q();if(!n.repos[r]){let i=Object.keys(n.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(t,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");n.auditSchedules=[...n.auditSchedules.filter(i=>!(i.repoName===r&&i.role===e)),{repoName:r,role:e,intervalHours:s}],ie(n),m.info(`Scheduled: ${e} audit of "${r}" every ${s}h. Restart the runner to apply.`)});Xo.command("schedules").description("List scheduled audits").action(()=>{let r=Q();if(!r.auditSchedules.length)return m.info("no scheduled audits \u2014 allwright audit schedule <repo> <role> <hours>");for(let e of r.auditSchedules)m.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});Xo.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((r,e)=>{let t=Q(),n=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===r&&s.role===e)),t.auditSchedules.length===n)throw new Error("no such schedule");ie(t),m.info("Removed. Restart the runner to apply.")});var Qo=ae.command("deploy").description("Deployment settings for this machine");Qo.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user \u2014 so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let r=Q();r.deploy={enabled:!0},ie(r),m.info("deployments ENABLED on this runner"),m.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});Qo.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let r=Q();r.deploy={enabled:!1},ie(r),m.info("deployments DISABLED on this runner"),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});Qo.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let r=Q();m.info(`deployments: ${r.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(r.environments);if(!e.length)return m.info("no environment secrets stored");for(let[t,n]of e){let s=Object.keys(n.secrets);m.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var ea=ae.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");ea.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((r,e,t)=>{let n=Q(),s=ss(r,e),i=n.environments[s]??{secrets:{}},o=[];for(let a of t){let u=a.indexOf("=");if(u<=0)throw new Error(`expected KEY=VALUE, got "${a}"`);let l=a.slice(0,u).trim();i.secrets[l]=a.slice(u+1),o.push(l)}n.environments[s]=i,ie(n),m.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),m.info(`Saved to ${wt()} (mode 600, this machine only)`),m.info("Restart the background runner to pick these up: allwright stop && allwright start")});ea.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((r,e,t)=>{let n=Q(),s=ss(r,e),i=n.environments[s];if(!i)return m.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];n.environments[s]=i,ie(n),m.info(`removed ${t.join(", ")} from ${s}`)});ea.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let r=Q(),e=Object.entries(r.environments);if(!e.length)return m.info("no environment secrets stored");for(let[t,n]of e)m.info(`${t}: ${Object.keys(n.secrets).join(", ")||"(none)"}`)});ae.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(r=>{try{let e=Aa(r);m.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),m.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private \u2014 anyone holding it can act as this runner."),m.info(`Restore on any machine with: allwright import ${od.default.basename(e.file)}`)}catch(e){m.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});ae.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(r=>{let e=zr();if(e&&wn(e)){m.error("the runner is running \u2014 stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let t=Ra(r);m.info(`Restored ${t.restored.length} entries into ${ee()}`),t.previousDir&&m.info(`Previous config kept at ${t.previousDir}`),m.info("Start the runner and it will reconnect with the restored identity.")}catch(t){m.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});ae.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let r=Q(),e=Object.keys(r.repos);if(!r.jira){m.error("no Jira credentials configured \u2014 run `allwright init`"),process.exitCode=1;return}let t=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],n=!0;for(let s of t){let i=await ei(r,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let a=o.ok?"PASS":"FAIL";(o.ok?m.info:m.error)(`[${a}] ${o.name}: ${o.detail}`),n&&=o.ok}}n||(process.exitCode=1)});function Yg(r){if(!r.runnerToken)throw new Error("runner not enrolled \u2014 run `allwright init`");if(!r.jira)throw new Error("no Jira credentials \u2014 run `allwright init`");let e=new ze(r.jira),t=new Map,n=f=>{let g=r.repos[f]?.jira;if(!g)return e;let b=t.get(f);return b||(b=new ze(g),t.set(f,b)),b},s=new Map,i=(f,g)=>{let b=wc(he()??r,f,g);switch(b.kind){case"legacy":return{jira:n(f),authored:!1};case"self":return{jira:n(f),authored:!0};case"missing":return{error:b.error};case"user":{let I=`${b.creds.baseUrl}:${b.creds.email}:${b.creds.apiToken.slice(-6)}`,N=s.get(I);return N||(N=new ze(b.creds),s.set(I,N)),{jira:N,authored:!0}}}},o=new URL("/api/runner/ws",r.controlPlaneUrl);o.protocol=o.protocol==="https:"?"wss:":"ws:";let a=[],u=[],l=[],d,p={cfg:r,jiraFor:n,transport:null},v=new Set,S=f=>{let g=a.find(I=>I.id===f),b=g&&r.repos[g.repoName];return g&&b?{project:g,repoPath:b.path}:null},x={cfg:r,jiraFor:n,get transport(){return p.transport},lookup:(f,g)=>{let b=S(f),I=l.find(N=>N.projectId===f&&N.name===g);return b&&I?{...b,environment:I}:null}},w=new Qs(o.toString(),r.runnerToken,{runnerVersion:gs},{onConfig:f=>{a=f.projects,u=f.rules,l=f.environments,d.setConfig(f.projects,f.rules,f.pollingPaused,f.environments)},onProjectTest:async f=>{let g=a.find(I=>I.id===f.projectId);if(!g){w.sendProjectTestResult(f.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}m.info(`running connection test for project "${g.name}"`);let b=await ei(r,g,l.filter(I=>I.projectId===g.id));w.sendProjectTestResult(f.requestId,b.every(I=>I.ok),b)},onRuleDiagnose:async f=>{let g=u.find(z=>z.id===f.ruleId),b=g&&a.find(z=>z.id===g.projectId);if(!g||!b){w.sendRuleDiagnoseResult(f.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}m.info(`diagnosing rule "${g.name}"`);let I=await ei(r,b,g.action.type==="deploy"?l.filter(z=>z.projectId===b.id):[]),N=g.action.type==="implement"?I:I.filter(z=>z.name!=="github-token"),{matchedCount:V,excludedCount:W,excludedSample:J}=await d.diagnoseRule(g,b);w.sendRuleDiagnoseResult(f.requestId,{checks:N,matchedCount:V,excludedCount:W,excludedSample:J})},onCancel:f=>{m.warn(`cancel requested for run ${f} \u2014 not supported in this version, run will finish or time out`)},onApproved:(f,g)=>{if(vo(f)){Uu(x,f).catch(b=>m.error(`deploy approval crashed for ${f}: ${b instanceof Error?b.stack:b}`));return}Mn(p,f,g).catch(b=>m.error(`approval handling crashed for ${f}: ${b instanceof Error?b.stack:b}`))},onRetryPush:f=>{let g=Is(f),b=()=>Iu(p,f).catch(I=>m.error(`retry push crashed for ${f}: ${I instanceof Error?I.stack:I}`));g?d.runOnRepoQueue(g.baseRepoPath,b):b()},onRejected:f=>{if(vo(f)){qu(x,f).catch(g=>m.error(`deploy rejection crashed for ${f}: ${g instanceof Error?g.stack:g}`));return}Eu(p,f).catch(g=>m.error(`rejection handling crashed for ${f}: ${g instanceof Error?g.stack:g}`))},onDeployStart:f=>{let g=`${f.runId}#${f.attempt}`;if(v.has(g))return;v.add(g);let b=S(f.projectId);if(!b){let I="this runner has no local checkout mapped for that project \u2014 run: allwright repo add <repoName> /path/to/checkout";m.error(`deploy ${f.runId}: ${I}`),w.send({type:"run.status",runId:f.runId,status:"failed",error:I});return}m.info(`deploy ${f.runId} requested from the dashboard: ${f.issueKey} \u2192 ${f.environment.name}`),d.runOnEnvironmentQueue(f.environment.id,()=>Ms({runId:f.runId,project:b.project,environment:f.environment,issueKey:f.issueKey,issueSummary:f.issueSummary,repoPath:b.repoPath,cfg:r,jira:n(b.project.repoName),transport:w,requestedBy:f.requestedBy}).catch(I=>m.error(`deploy crashed for ${f.runId}: ${I instanceof Error?I.stack:I}`)))},onDeploySuggest:async f=>{let g=S(f.projectId);if(!g){w.sendDeploySuggestResult(f.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}m.info(`asking Claude Code for "${f.environmentName}" deploy steps in ${g.repoPath}`);let b=await Ku({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:f.environmentName,notes:f.notes,timeoutSeconds:f.timeoutSeconds,cfg:r});w.sendDeploySuggestResult(f.requestId,b)},onEnvPreflight:async f=>{let g=S(f.projectId);if(!g){w.sendEnvPreflightResult(f.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let b=await Zu({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:f.environmentName,steps:f.steps,requiredSecrets:f.requiredSecrets,workdir:f.workdir,branch:f.branch,cfg:r});w.sendEnvPreflightResult(f.requestId,b)},onChatTurn:async f=>{let g=S(f.projectId);if(!g){w.sendChatTurnResult(f.requestId,{ok:!1,sessionId:f.sessionId??"",reply:"",error:"this runner has no local checkout mapped for that project"});return}let b=f.sessionId||(0,Wo.randomUUID)(),I=!f.sessionId;if((I?0:So(b)?.messages.length??0)>=44){w.sendChatTurnResult(f.requestId,{ok:!1,sessionId:b,reply:"",error:"this chat has hit its length limit \u2014 every turn re-reads the whole conversation, so long chats get slow and expensive. Start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}let V=f.files.length?ja(g.repoPath,f.requestId,f.files):null,W="```",J=I?`You are the project assistant for "${g.project.name}" \u2014 this working directory is its repository, and you have read-only access.
|
|
662
|
+
(run \`${a.runId}\`)`).catch(l=>m.warn(`could not post refusal to ${i.issueKey}: ${l}`)),m.warn(`deploy refused for ${i.issueKey}: ${a.reason}`)):a.reason&&m.warn(`deploy claim rejected for ${i.issueKey}: ${a.reason}`);continue}let c=a.environment;this.inFlight.add(o),m.info(`claimed deploy ${a.runId}: ${i.issueKey} \u2192 ${c.name}`),this.enqueue(this.envQueues,c.id,async()=>{try{await zs({runId:a.runId,project:t,environment:c,issueKey:i.issueKey,issueSummary:i.summary,repoPath:n,cfg:this.cfg,jira:this.jiraOf(t),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,t){let n=e.trigger,s=e.action;if(n.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=n.keyword.toLowerCase(),a=Date.now()-Gc,c=this.environments.filter(p=>p.projectId===t.id).map(p=>p.name),l=this.fixedEnvironmentName(s.environmentId),d=[];for(let p of i){let v=await this.jiraOf(t).getIssue(p.key);if(!(s.requireStatus&&v.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let S of v.comments){if(!S.body.toLowerCase().includes(o)||Ge(S.body)||new Date(S.created).getTime()<a||!S.id)continue;let x=s.envSelection==="fixed"?l:wm(S.body,n.keyword,c);d.push({issueKey:p.key,summary:p.summary,environmentName:x,requestedByAccountId:S.authorAccountId??void 0,requestedByDisplayName:S.author,dedupKey:`deploy:comment:${S.id}`,fingerprint:`comment "${n.keyword}" by ${S.author} at ${S.created}`+(x?` \u2192 ${x}`:"")})}}return d}async matchStatusDeploys(e,t){let n=e.trigger,s=e.action;if(n.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${n.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),a=[];for(let c of i){let l=await this.jiraOf(t).lastEnteredStatus(c.key,n.status);l&&a.push({issueKey:c.key,summary:c.summary,environmentName:o,requestedByAccountId:l.authorAccountId??void 0,requestedByDisplayName:l.author,dedupKey:`deploy:status:${e.id}:${c.key}:${l.at}`,fingerprint:`moved to "${n.status}" by ${l.author} at ${l.at}`})}return a}fixedEnvironmentName(e){return e?this.environments.find(t=>t.id===e)?.name??"":""}async matchLabelTrigger(e,t){let n=e.trigger;if(n.type!=="label_added")return[];let s=`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels not in ("${n.doneLabel}", "${n.failedLabel}", "${kr.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(t).search(s,10)).map(o=>({issueKey:o.key,summary:o.summary,components:o.components,fingerprint:`label "${n.label}" matched at ${new Date().toISOString()}`}))}async matchCommentTrigger(e,t){let n=e.trigger;if(n.type!=="comment_keyword")return[];let s=`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${n.doneLabel}", "${n.failedLabel}", "${kr.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(t).search(s,10),o=n.keyword.toLowerCase(),a=[];for(let c of i){let d=(await this.jiraOf(t).getIssue(c.key)).comments.find(p=>p.body.toLowerCase().includes(o)&&!Ge(p.body));d&&a.push({issueKey:c.key,components:c.components,summary:c.summary,fingerprint:`comment keyword "${n.keyword}" by ${d.author} at ${d.created}`,triggeredByAccountId:d.authorAccountId??void 0})}return a}async diagnoseRule(e,t){let n=e.trigger;if(e.action.type==="deploy"){let c=n.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t),l=c.filter(d=>d.environmentName);return{matchedCount:l.length,excludedCount:c.length-l.length,excludedSample:c.filter(d=>!d.environmentName).slice(0,5).map(d=>d.issueKey)}}if(n.type==="status_changed")return{matchedCount:(await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${n.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(n.type==="label_added"){let[c,l]=await Promise.all([this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels not in ("${n.doneLabel}", "${n.failedLabel}")`,50),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels in ("${n.doneLabel}", "${n.failedLabel}")`,50)]);return{matchedCount:c.length,excludedCount:l.length,excludedSample:l.slice(0,5).map(d=>d.key)}}let s=n.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,t),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${n.doneLabel}", "${n.failedLabel}")`,50)]),a=[];for(let c of o)(await this.jiraOf(t).getIssue(c.key)).comments.some(d=>d.body.toLowerCase().includes(s))&&a.push(c.key);return{matchedCount:i.length,excludedCount:a.length,excludedSample:a.slice(0,5)}}enqueueForRepo(e,t){this.enqueue(this.repoQueues,e,t)}runOnRepoQueue(e,t){this.enqueue(this.repoQueues,e,t)}runOnEnvironmentQueue(e,t){this.enqueue(this.envQueues,e,t)}enqueue(e,t,n){let i=(e.get(t)??Promise.resolve()).then(n).catch(o=>{m.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(t,i)}};function wm(r,e,t){let n=r.toLowerCase().indexOf(e.toLowerCase());if(n<0)return"";let i=r.slice(n+e.length).split(/[^\w.-]+/).filter(Boolean);for(let o of i){let a=t.find(c=>c.toLowerCase()===o.toLowerCase());if(a)return a}for(let o of i)if(!bm.has(o.toLowerCase()))return o;return""}var Sr=$(require("node:fs"),1),Jc=$(require("node:path"),1);var km=k.object({role:k.enum(["user","agent"]),text:k.string()}),Sm=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),messages:k.array(km).default([])}),Tm=k.record(Sm),xm=10,Cm=200,Wc=2e4;function Yc(){return Jc.default.join(ee(),"chat-sessions.json")}function xo(){let r=Yc();if(!Sr.default.existsSync(r))return{};try{return Tm.parse(JSON.parse(Sr.default.readFileSync(r,"utf8")))}catch{return{}}}function Em(r){Sr.default.mkdirSync(ee(),{recursive:!0,mode:448});let e=Yc(),t=e+".tmp";Sr.default.writeFileSync(t,JSON.stringify(r,null,2)+`
|
|
663
|
+
`,{mode:384}),Sr.default.renameSync(t,e),Sr.default.chmodSync(e,384)}function Xc(r,e,t,n){let s=xo(),o=s[e]??{sessionId:e,projectId:r,title:t.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};o.messages.push({role:"user",text:t.slice(0,Wc)},{role:"agent",text:n.slice(0,Wc)}),o.messages=o.messages.slice(-Cm),o.updatedAt=new Date().toISOString(),s[e]=o;let a=Object.values(s).filter(c=>c.projectId===o.projectId).sort((c,l)=>l.updatedAt.localeCompare(c.updatedAt));for(let c of a.slice(xm))delete s[c.sessionId];Em(s)}function Qc(r){return Object.values(xo()).filter(e=>e.projectId===r).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function Co(r){return xo()[r]??null}var Gg=$(Gl(),1),Wg=$(Js(),1),Jg=$(ln(),1),Yg=$(Do(),1),Xg=$(Uo(),1),Qg=$(Vo(),1),nd=$(ei(),1),ey=$(rd(),1);var Go=nd.default;var Jo=$(require("node:crypto"),1),Xe=$(Se(),1);function ty(r){let e=r&&typeof r=="object"&&"name"in r?String(r.name):null;return e?`"${e}"`:"(unnamed)"}function Wo(r,e,t,n){r.push(`dropped ${e} ${t} \u2014 this runner is out of date and does not understand it yet (${n}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function ry(r){if(!r||typeof r!="object"||r.type!=="config")return null;let e=r,t=[],n=[];for(let a of Array.isArray(e.projects)?e.projects:[]){let c=Xe.ProjectConfig.safeParse(a);c.success?n.push(c.data):Wo(t,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let a of Array.isArray(e.rules)?e.rules:[]){let c=Xe.RuleConfig.safeParse(a);c.success?s.push(c.data):Wo(t,"rule",ty(a),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let a of Array.isArray(e.environments)?e.environments:[]){let c=Xe.EnvironmentConfig.safeParse(a);c.success?i.push(c.data):Wo(t,"environment","",c.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:n,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var ny=2e4,sy=6e4,iy=5e3,ri=class{constructor(e,t,n,s){this.wsUrl=e;this.runnerToken=t;this.meta=n;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===Go.OPEN}connect(){if(this.closed)return;m.info(`connecting to control plane at ${this.wsUrl}`);let e=new Go(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Xe.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let t=this.queue.splice(0,this.queue.length);for(let n of t)this.sendNow(n);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},ny)}),e.on("message",t=>{let n;try{n=JSON.parse(t.toString())}catch(i){m.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Xe.parseServerMsg)(n)}catch(i){let o=ry(n);if(!o){m.warn(`ignoring malformed server message: ${i}`);return}for(let a of o.warnings)m.warn(a);m.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand \u2014 applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)m.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===4003){m.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let n=Math.random()*.3+.85,s=Math.round(this.backoffMs*n);m.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,sy)}),e.on("error",t=>{m.warn(`websocket error: ${t.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,m.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"){let t=this.pending.get(e.requestId);t&&(clearTimeout(t.timer),this.pending.delete(e.requestId),t.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e);if(e.type==="setup.status")return this.events.onSetupStatus(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=iy){let t=this.queue.findIndex(n=>n.type==="run.log");t>=0?this.queue.splice(t,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Jo.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:t,...e})});return!n||n.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:n.accepted,runId:n.runId,reason:n.reason,claudeProfile:n.claudeProfile,actorEmail:n.actorEmail}}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Jo.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:t,...e})});return!n||n.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:n.accepted,runId:n.runId,environment:n.environment,reason:n.reason,code:n.code}}sendDeploySuggestResult(e,t){this.send({type:"deploy.suggest.result",requestId:e,...t})}sendChatTurnResult(e,t){this.send({type:"chat.turn.result",requestId:e,...t})}sendChatCreateTicketResult(e,t){this.send({type:"chat.create.ticket.result",requestId:e,...t,childKeys:t.childKeys??[]})}sendChatListResult(e,t){this.send({type:"chat.list.result",requestId:e,sessions:t})}sendChatLoadResult(e,t){this.send({type:"chat.load.result",requestId:e,...t})}sendBoardFetchResult(e,t){this.send({type:"board.fetch.result",requestId:e,...t,browseBaseUrl:t.browseBaseUrl??""})}sendAuditStartResult(e,t){this.send({type:"audit.start.result",requestId:e,...t})}sendAuditListResult(e,t){this.send({type:"audit.list.result",requestId:e,ok:t.ok,error:t.error,audits:t.audits??[]})}sendAuditGetResult(e,t){this.send({type:"audit.get.result",requestId:e,...t})}sendAuditReviewResult(e,t){this.send({type:"audit.review.result",requestId:e,...t})}sendKnowledgeListResult(e,t){this.send({type:"knowledge.list.result",requestId:e,ok:t.ok,error:t.error,files:t.files??[]})}sendKnowledgeSaveResult(e,t){this.send({type:"knowledge.save.result",requestId:e,...t})}sendEpicListResult(e,t){this.send({type:"epic.list.result",requestId:e,ok:t.ok,error:t.error,epics:t.epics??[],children:t.children??[]})}sendEpicSuggestResult(e,t){this.send({type:"epic.suggest.result",requestId:e,ok:t.ok,error:t.error,issueKey:t.issueKey??"",reason:t.reason??"",considered:t.considered??0})}sendTeamCredsResult(e,t){this.send({type:"team.creds.result",requestId:e,ok:t.ok,error:t.error,githubShared:t.githubShared??!1,sharedGithubLogin:t.sharedGithubLogin??"",entries:t.entries??[]})}sendBoardTriggerResult(e,t){this.send({type:"board.trigger.result",requestId:e,...t})}sendSetupStatusResult(e,t){this.send({type:"setup.status.result",requestId:e,ok:t.ok,error:t.error,jiraConfigured:t.jiraConfigured??!1,jiraEmail:t.jiraEmail??"",claude:t.claude,githubTokenSet:t.githubTokenSet??!1,githubLogin:t.githubLogin??"",deploysEnabled:t.deploysEnabled??!1,jiraUserCount:t.jiraUserCount??0,repos:t.repos??[]})}sendEnvPreflightResult(e,t){this.send({type:"env.preflight.result",requestId:e,...t})}sendJiraUsersResult(e,t){this.send({type:"jira.users.result",requestId:e,...t})}sendProjectTestResult(e,t,n){this.send({type:"project.test.result",requestId:e,ok:t,checks:n})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t})}};var gn=$(require("node:fs"),1),Yo=$(require("node:path"),1),id=require("node:child_process"),od=require("node:util");var sd=(0,od.promisify)(id.execFile);async function ni(r,e,t=[]){let n=[],s=r.repos[e.repoName]?.jira??r.jira;if(!s)n.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else{let o=new ze(s);try{let a=await o.myself();n.push({name:"jira-auth",ok:!0,detail:`authenticated as ${a.displayName}`});try{await o.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),n.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable`})}catch(c){n.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey}: ${Gn(c)}`})}}catch(a){n.push({name:"jira-auth",ok:!1,detail:`Jira auth failed: ${Gn(a)}`})}}let i=r.repos[e.repoName];if(i&&gn.default.existsSync(i.path)){let o=Yo.default.join(i.path,"CLAUDE.md"),a=gn.default.existsSync(o)&&gn.default.readFileSync(o,"utf8").trim().length>0;n.push({name:"memory-file",ok:a,detail:a?"CLAUDE.md present \u2014 the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file \u2014 it is what makes every run smarter than the last."});let c=So(i.path);n.push({name:"deploy-doc",ok:c!==null,detail:c?`${c.path} present \u2014 deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys."})}if(!i)n.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" \u2014 run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!gn.default.existsSync(i.path))n.push({name:"repo-path",ok:!1,detail:`path does not exist: ${i.path}`});else{let o=gn.default.existsSync(Yo.default.join(i.path,".git"));n.push({name:"repo-path",ok:!0,detail:`${i.path}${o?" (git checkout)":" (warning: not a git checkout)"}`})}try{let{stdout:o}=await sd(r.claudeBin,["--version"],{timeout:15e3});n.push({name:"claude-code",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"claude-code",ok:!1,detail:`cannot run "${r.claudeBin}": ${Gn(o)}`})}try{let{stdout:o}=await sd("git",["--version"],{timeout:15e3});n.push({name:"git",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"git",ok:!1,detail:`cannot run git: ${Gn(o)}`})}if(r.github?.token)try{let{GitHubClient:o}=await Promise.resolve().then(()=>(ct(),tn)),a=await new o(r.github.token).whoami();n.push({name:"github-token",ok:!0,detail:`authenticated as ${a}`})}catch(o){n.push({name:"github-token",ok:!1,detail:Gn(o)})}else n.push({name:"github-token",ok:!0,detail:"not set \u2014 needed only for implement rules (allwright github set-token)"});if(t.length){r.deploy.enabled?n.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):n.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner \u2014 run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let o of t){let a=Jt(r,e.repoName,o.name),c=o.requiredSecrets.filter(l=>!a[l]&&!process.env[l]);n.push({name:`env:${o.name}`,ok:c.length===0,detail:c.length?`missing secret(s): ${c.join(", ")} \u2014 allwright env set "${e.repoName}" "${o.name}" ${c[0]}=...`:`${o.steps.length} step(s), ${o.requiredSecrets.length} secret(s) present`+(o.branch?`, deploys origin/${o.branch}`:"")})}}return n}function Gn(r){return(r instanceof Error?r.message:String(r)).slice(0,300)}var ae=new _a;ae.name("allwright").description("Allwright runner \u2014 runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(vs);ae.command("init").description("Interactive setup: enroll this runner and store credentials locally").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",fd.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async r=>{let e=Rr.default.createInterface({input:process.stdin,output:process.stdout}),t=async(n,s,i=!1)=>{if(s)return s;let o=await e.question(`${n}: `);if(!o.trim())throw new Error(`${n} is required`);return o.trim()};try{let n=await t("Control plane URL",r.cpUrl),s=await t("Enrolment token (from the web UI)",r.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",r.jiraUrl),o=await t("Jira account email",r.jiraEmail),a=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",r.jiraToken,!0),c=Ti.parse({controlPlaneUrl:n,runnerName:r.name,jira:{baseUrl:i,email:o,apiToken:a}}),l=await new ze(c.jira).myself();m.info(`Jira credential OK \u2014 authenticated as ${l.displayName}`),c=await lu(c,s),m.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),m.info(`Credentials saved to ${wt()} (mode 600, this machine only)`),m.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Qo=ae.command("repo").description("Map control-plane repo names to local checkouts");Qo.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(r,e)=>{let t=Q();t.repos[r]={path:e},ie(t),m.info(`mapped repo "${r}" -> ${e}`);try{let{originUrl:n}=await Promise.resolve().then(()=>(gr(),bu));m.info(` origin remote: ${await n(e)} \u2014 make sure this is the repo you meant`)}catch{m.warn(` could not read an origin remote at ${e} \u2014 is it a git checkout?`)}});Qo.command("list").description("Show configured repo mappings").action(()=>{let r=Q(),e=Object.entries(r.repos);if(!e.length)return m.info("no repos mapped yet");for(let[t,n]of e)m.info(`${t} -> ${n.path}`)});var md=ae.command("claude").description("Per-user Claude login profiles \u2014 each teammate's runs bill their OWN Claude account");md.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory \u2014 have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async r=>{if(!/^[a-zA-Z0-9._-]+$/.test(r))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=Q(),t=e.claudeProfiles[r]?.configDir??`${wt().replace(/runner\.json$/,"")}claude-profiles/${r}`;yn.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[r]={configDir:t},ie(e),m.info(`profile "${r}" -> ${t}`),m.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),m.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let n=(0,Wn.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>n.on("exit",()=>s())),m.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${r}".`),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});md.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let r=Q(),e=Object.entries(r.claudeProfiles);if(m.info("default: this OS user's own Claude login (no profile)"),!e.length)return m.info("no named profiles yet \u2014 allwright claude login <name>");for(let[t,n]of e){let s=yn.default.existsSync(n.configDir)&&yn.default.readdirSync(n.configDir).length>0;m.info(`${t} -> ${n.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Qo.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane \u2014 delete the project on the dashboard separately.").action(r=>{let e=Q();if(!e.repos[r]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${i}`)}let t=e.repos[r].path;delete e.repos[r];let n=Object.keys(e.environments).filter(i=>i.startsWith(`${r}:`));for(let i of n)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==r),ie(e),m.info(`Removed "${r}" (was ${t})`),n.length&&m.info(`Also removed ${n.length} environment secret set(s): ${n.join(", ")}`),e.auditSchedules.length!==s&&m.info("Also removed its audit schedule(s)"),m.info("The checkout on disk was NOT touched \u2014 remove it yourself if you want it gone."),m.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var ea=ae.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");ea.command("install").description("Install + start the systemd service \u2014 detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(r=>{if(r.print){m.info(`
|
|
664
|
+
`+Xi(Yi()));return}Eu(m)});ea.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>Iu(m));ea.command("status").description("systemctl status for the runner service").action(()=>{(0,Wn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});ae.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards \u2014 and only when no runs are active.").action(async()=>{m.info("Updating: npm install -g allwright@latest");let r=(0,Wn.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{r.on("exit",n=>n===0?e():t(new Error(`npm exited with code ${n}`))),r.on("error",t)}),m.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Jn=ae.command("jira").description("Per-repo Jira site overrides \u2014 for projects living on a different Atlassian site");Jn.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async r=>{let e=Q();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question("Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim(),s=(await t.question("Jira account email: ")).trim(),i=(await t.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!n||!s||!i)throw new Error("all three values are required");let o={baseUrl:n,email:s,apiToken:i},a=await new ze(o).myself();m.info(`Jira credential OK \u2014 authenticated as ${a.displayName} on ${n}`),e.repos[r].jira=o,ie(e),m.info(`Saved: repo "${r}" now polls ${n} (other repos keep the runner-wide credential)`),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")}finally{t.close()}});Jn.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let r=Q();m.info(`runner-wide: ${r.jira?`${r.jira.baseUrl} (${r.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(r.repos))m.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(runner-wide credential)"}`)});Jn.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click \u2014 no restart needed.").action(async r=>{let e=Q(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await n.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(l=>l.jira)].filter(l=>!!l),a=new Set,c=!1;for(let l of o)if(!a.has(l.baseUrl)){a.add(l.baseUrl);try{let d=await new ze({baseUrl:l.baseUrl,email:s,apiToken:i}).myself();m.info(`${l.baseUrl}: OK \u2014 authenticated as ${d.displayName}`),c=!0}catch{m.warn(`${l.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!c)throw new Error("credential failed on every configured Jira site \u2014 nothing saved");e.jiraUsers[t]={email:s,apiToken:i},ie(e),m.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{n.close()}});Jn.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let r=Q(),e=Object.entries(r.jiraUsers);if(!e.length)return m.info("none yet \u2014 everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,n]of e)m.info(`${t} -> posts to Jira as ${n.email}`)});Jn.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(r=>{let e=Q(),t=r.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],ie(e),m.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var _n=ae.command("github").description("GitHub credential for implement-mode rules");_n.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async r=>{let e=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let t=r.token??(await e.question("GitHub token (fine-grained PAT recommended): ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:n}=await Promise.resolve().then(()=>(ct(),tn)),s=await new n(t).whoami(),i=Q();i.github={token:t,login:s},ie(i),m.info(`GitHub token OK \u2014 authenticated as ${s}`),m.info(`Saved to ${wt()} (mode 600, this machine only)`)}finally{e.close()}});_n.command("set <repoName>").description("Store a GitHub token for ONE repo only \u2014 overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async r=>{let e=Q();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question(`GitHub token for "${r}" (fine-grained PAT scoped to just this repo): `)).trim();if(!n)throw new Error("token is required");let{GitHubClient:s}=await Promise.resolve().then(()=>(ct(),tn)),i=await new s(n).whoami();e.repos[r].github={token:n,login:i},ie(e),m.info(`GitHub token OK \u2014 authenticated as ${i}`),m.info(`Saved: repo "${r}" now uses its own token (other repos keep the runner-wide one)`)}finally{t.close()}});_n.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional \u2014 without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async r=>{let e=Q(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(ct(),tn)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},ie(e),m.info(`GitHub token OK \u2014 authenticated as ${o}`),m.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{n.close()}});_n.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let r=Q(),e=Object.entries(r.githubUsers);if(!e.length)return m.info("no per-user GitHub tokens \u2014 everyone's PRs use the repo/runner-wide token");for(let[t]of e)m.info(`${t} -> own GitHub token stored`)});_n.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(r=>{let e=Q(),t=r.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],ie(e),m.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});_n.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let r=Q();m.info(`runner-wide: ${r.github?.token?"token set":"(not configured)"}`);for(let[t,n]of Object.entries(r.repos))m.info(`${t} -> ${n.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(r.githubUsers);m.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var ta=ae.command("audit").description("Recurring specialist audits on this runner");ta.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only \u2014 nothing blocks.").action((r,e,t)=>{let n=Q();if(!n.repos[r]){let i=Object.keys(n.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(t,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");n.auditSchedules=[...n.auditSchedules.filter(i=>!(i.repoName===r&&i.role===e)),{repoName:r,role:e,intervalHours:s}],ie(n),m.info(`Scheduled: ${e} audit of "${r}" every ${s}h. Restart the runner to apply.`)});ta.command("schedules").description("List scheduled audits").action(()=>{let r=Q();if(!r.auditSchedules.length)return m.info("no scheduled audits \u2014 allwright audit schedule <repo> <role> <hours>");for(let e of r.auditSchedules)m.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});ta.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((r,e)=>{let t=Q(),n=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===r&&s.role===e)),t.auditSchedules.length===n)throw new Error("no such schedule");ie(t),m.info("Removed. Restart the runner to apply.")});var ra=ae.command("deploy").description("Deployment settings for this machine");ra.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user \u2014 so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let r=Q();r.deploy={enabled:!0},ie(r),m.info("deployments ENABLED on this runner"),m.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});ra.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let r=Q();r.deploy={enabled:!1},ie(r),m.info("deployments DISABLED on this runner"),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});ra.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let r=Q();m.info(`deployments: ${r.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(r.environments);if(!e.length)return m.info("no environment secrets stored");for(let[t,n]of e){let s=Object.keys(n.secrets);m.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var na=ae.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");na.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((r,e,t)=>{let n=Q(),s=as(r,e),i=n.environments[s]??{secrets:{}},o=[];for(let a of t){let c=a.indexOf("=");if(c<=0)throw new Error(`expected KEY=VALUE, got "${a}"`);let l=a.slice(0,c).trim();i.secrets[l]=a.slice(c+1),o.push(l)}n.environments[s]=i,ie(n),m.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),m.info(`Saved to ${wt()} (mode 600, this machine only)`),m.info("Restart the background runner to pick these up: allwright stop && allwright start")});na.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((r,e,t)=>{let n=Q(),s=as(r,e),i=n.environments[s];if(!i)return m.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];n.environments[s]=i,ie(n),m.info(`removed ${t.join(", ")} from ${s}`)});na.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let r=Q(),e=Object.entries(r.environments);if(!e.length)return m.info("no environment secrets stored");for(let[t,n]of e)m.info(`${t}: ${Object.keys(n.secrets).join(", ")||"(none)"}`)});ae.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(r=>{try{let e=$a(r);m.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),m.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private \u2014 anyone holding it can act as this runner."),m.info(`Restore on any machine with: allwright import ${pd.default.basename(e.file)}`)}catch(e){m.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});ae.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(r=>{let e=qr();if(e&&Tn(e)){m.error("the runner is running \u2014 stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let t=Pa(r);m.info(`Restored ${t.restored.length} entries into ${ee()}`),t.previousDir&&m.info(`Previous config kept at ${t.previousDir}`),m.info("Start the runner and it will reconnect with the restored identity.")}catch(t){m.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});ae.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let r=Q(),e=Object.keys(r.repos);if(!r.jira){m.error("no Jira credentials configured \u2014 run `allwright init`"),process.exitCode=1;return}let t=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],n=!0;for(let s of t){let i=await ni(r,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let a=o.ok?"PASS":"FAIL";(o.ok?m.info:m.error)(`[${a}] ${o.name}: ${o.detail}`),n&&=o.ok}}n||(process.exitCode=1)});function uy(r){if(!r.runnerToken)throw new Error("runner not enrolled \u2014 run `allwright init`");if(!r.jira)throw new Error("no Jira credentials \u2014 run `allwright init`");let e=new ze(r.jira),t=new Map,n=f=>{let g=r.repos[f]?.jira;if(!g)return e;let b=t.get(f);return b||(b=new ze(g),t.set(f,b)),b},s=new Map,i=(f,g)=>{let b=Su(ce()??r,f,g);switch(b.kind){case"legacy":return{jira:n(f),authored:!1};case"self":return{jira:n(f),authored:!0};case"missing":return{error:b.error};case"user":{let I=`${b.creds.baseUrl}:${b.creds.email}:${b.creds.apiToken.slice(-6)}`,N=s.get(I);return N||(N=new ze(b.creds),s.set(I,N)),{jira:N,authored:!0}}}},o=new URL("/api/runner/ws",r.controlPlaneUrl);o.protocol=o.protocol==="https:"?"wss:":"ws:";let a=[],c=[],l=[],d,p={cfg:r,jiraFor:n,transport:null},v=new Set,S=f=>{let g=a.find(I=>I.id===f),b=g&&r.repos[g.repoName];return g&&b?{project:g,repoPath:b.path}:null},x={cfg:r,jiraFor:n,get transport(){return p.transport},lookup:(f,g)=>{let b=S(f),I=l.find(N=>N.projectId===f&&N.name===g);return b&&I?{...b,environment:I}:null}},w=new ri(o.toString(),r.runnerToken,{runnerVersion:vs},{onConfig:f=>{a=f.projects,c=f.rules,l=f.environments,d.setConfig(f.projects,f.rules,f.pollingPaused,f.environments)},onProjectTest:async f=>{let g=a.find(I=>I.id===f.projectId);if(!g){w.sendProjectTestResult(f.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}m.info(`running connection test for project "${g.name}"`);let b=await ni(r,g,l.filter(I=>I.projectId===g.id));w.sendProjectTestResult(f.requestId,b.every(I=>I.ok),b)},onRuleDiagnose:async f=>{let g=c.find(z=>z.id===f.ruleId),b=g&&a.find(z=>z.id===g.projectId);if(!g||!b){w.sendRuleDiagnoseResult(f.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}m.info(`diagnosing rule "${g.name}"`);let I=await ni(r,b,g.action.type==="deploy"?l.filter(z=>z.projectId===b.id):[]),N=g.action.type==="implement"?I:I.filter(z=>z.name!=="github-token"),{matchedCount:V,excludedCount:W,excludedSample:J}=await d.diagnoseRule(g,b);w.sendRuleDiagnoseResult(f.requestId,{checks:N,matchedCount:V,excludedCount:W,excludedSample:J})},onCancel:f=>{m.warn(`cancel requested for run ${f} \u2014 not supported in this version, run will finish or time out`)},onApproved:(f,g)=>{if(ko(f)){Bc(x,f).catch(b=>m.error(`deploy approval crashed for ${f}: ${b instanceof Error?b.stack:b}`));return}zn(p,f,g).catch(b=>m.error(`approval handling crashed for ${f}: ${b instanceof Error?b.stack:b}`))},onRetryPush:f=>{let g=$s(f),b=()=>Rc(p,f).catch(I=>m.error(`retry push crashed for ${f}: ${I instanceof Error?I.stack:I}`));g?d.runOnRepoQueue(g.baseRepoPath,b):b()},onRejected:f=>{if(ko(f)){Fc(x,f).catch(g=>m.error(`deploy rejection crashed for ${f}: ${g instanceof Error?g.stack:g}`));return}Ac(p,f).catch(g=>m.error(`rejection handling crashed for ${f}: ${g instanceof Error?g.stack:g}`))},onDeployStart:f=>{let g=`${f.runId}#${f.attempt}`;if(v.has(g))return;v.add(g);let b=S(f.projectId);if(!b){let I="this runner has no local checkout mapped for that project \u2014 run: allwright repo add <repoName> /path/to/checkout";m.error(`deploy ${f.runId}: ${I}`),w.send({type:"run.status",runId:f.runId,status:"failed",error:I});return}m.info(`deploy ${f.runId} requested from the dashboard: ${f.issueKey} \u2192 ${f.environment.name}`),d.runOnEnvironmentQueue(f.environment.id,()=>zs({runId:f.runId,project:b.project,environment:f.environment,issueKey:f.issueKey,issueSummary:f.issueSummary,repoPath:b.repoPath,cfg:r,jira:n(b.project.repoName),transport:w,requestedBy:f.requestedBy}).catch(I=>m.error(`deploy crashed for ${f.runId}: ${I instanceof Error?I.stack:I}`)))},onDeploySuggest:async f=>{let g=S(f.projectId);if(!g){w.sendDeploySuggestResult(f.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}m.info(`asking Claude Code for "${f.environmentName}" deploy steps in ${g.repoPath}`);let b=await Hc({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:f.environmentName,notes:f.notes,timeoutSeconds:f.timeoutSeconds,cfg:r});w.sendDeploySuggestResult(f.requestId,b)},onEnvPreflight:async f=>{let g=S(f.projectId);if(!g){w.sendEnvPreflightResult(f.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let b=await Vc({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:f.environmentName,steps:f.steps,requiredSecrets:f.requiredSecrets,workdir:f.workdir,branch:f.branch,cfg:r});w.sendEnvPreflightResult(f.requestId,b)},onChatTurn:async f=>{let g=S(f.projectId);if(!g){w.sendChatTurnResult(f.requestId,{ok:!1,sessionId:f.sessionId??"",reply:"",error:"this runner has no local checkout mapped for that project"});return}let b=f.sessionId||(0,Xo.randomUUID)(),I=!f.sessionId;if((I?0:Co(b)?.messages.length??0)>=44){w.sendChatTurnResult(f.requestId,{ok:!1,sessionId:b,reply:"",error:"this chat has hit its length limit \u2014 every turn re-reads the whole conversation, so long chats get slow and expensive. Start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}let V=f.files.length?Na(g.repoPath,f.requestId,f.files):null,W="```",J=I?`You are the project assistant for "${g.project.name}" \u2014 this working directory is its repository, and you have read-only access.
|
|
661
665
|
|
|
662
666
|
DEFAULT MODE IS DISCUSSION. Answer questions, explain code, weigh approaches, review ideas \u2014 like a teammate who knows this repo. Most conversations never produce a ticket, and that is fine. Do NOT propose a Jira ticket unless the user explicitly asks for one in this conversation ("create a ticket", "make this a ticket", "draft the ticket" or similar). Never end a normal answer with a ticket proposal.
|
|
663
667
|
Be fast: answer from CLAUDE.md and what you already know first; open files only when the question genuinely needs code-level detail. Keep replies short.
|
|
@@ -667,17 +671,23 @@ ${W}ticket
|
|
|
667
671
|
{"summary": "\u2026", "description": "\u2026"}
|
|
668
672
|
${W}
|
|
669
673
|
Before drafting, re-read this ENTIRE conversation from its first message and fold in every decision, constraint, and correction agreed along the way \u2014 the ticket reflects the final state of the whole discussion, not just the last message.
|
|
670
|
-
|
|
674
|
+
Write the description in plain human language, structured with these Markdown section headings in this order:
|
|
675
|
+
Story: \u2014 one or two sentences: who needs this and why.
|
|
676
|
+
Description: \u2014 what to build and where in the codebase, as bullet points.
|
|
677
|
+
Expected Flow: \u2014 the flow once this ticket is done, as numbered steps.
|
|
678
|
+
Current Flow: \u2014 how it behaves today; include ONLY when current behavior exists.
|
|
679
|
+
Acceptance Criteria: \u2014 testable bullet points a reviewer can check off one by one.
|
|
680
|
+
Include a section only when it carries real content, and add extra sections (Out of Scope, Notes, \u2026) when the work genuinely needs them. Use as many bullets as the work needs \u2014 no artificial length cap, but no padding either. It must stay concrete enough that a developer (or an agent) can implement it without asking questions. NEVER paste the conversation into the description; distill it. Refine the draft over further turns if the user asks.
|
|
671
681
|
EXCEPTION \u2014 verbatim payloads: when the user supplies literal content that must land in the ticket exactly (file contents, error logs, specs, commands), include it in the description IN FULL inside a fenced code block \u2014 the word budget applies to your own prose around it, never to the user's payload. Never summarize such content and never replace it with a placeholder like "[insert content here]": a placeholder makes the ticket unimplementable, because the implementing agent only ever sees the ticket. Inside the ${W}ticket JSON, fence such payloads with ~~~ (tildes), NEVER with triple backticks \u2014 a nested ${W} would end the outer block early and corrupt the draft.
|
|
672
682
|
EXCEPTION \u2014 big requirements: when the user asks for an epic with sub-tickets, or asks to ticket something clearly too large for one ticket, break it down instead and emit this shape in the \`\`\`ticket block:
|
|
673
683
|
{"epic": {"summary": "\u2026", "description": "\u2026"}, "tickets": [{"summary": "\u2026", "description": "\u2026"}, \u2026]}
|
|
674
|
-
3-8 tickets, each independently implementable and
|
|
684
|
+
3-8 tickets, each independently implementable and structured with the same section headings as above, ordered so foundations come first; the epic description is the overall goal in under 100 words.
|
|
675
685
|
|
|
676
|
-
${f.userName||"The user"} says: ${f.message}`+(V?.section??""):`${f.userName||"The user"} says: ${f.message}`+(V?.section??""),z=0,H;try{H=await Ue.run({repoPath:g.repoPath,prompt:J,timeoutSeconds:180,bin:r.claudeBin,mode:"read_only",maxTurns:25,model:f.model||"claude-sonnet-5",sessionId:b,resume:!I,onLog:(be,Ce)=>{be==="agent"&&w.send({type:"chat.stream",requestId:f.requestId,seq:z++,text:Ce.slice(0,8e3)})}})}finally{V&&
|
|
686
|
+
${f.userName||"The user"} says: ${f.message}`+(V?.section??""):`${f.userName||"The user"} says: ${f.message}`+(V?.section??""),z=0,H;try{H=await Ue.run({repoPath:g.repoPath,prompt:J,timeoutSeconds:180,bin:r.claudeBin,mode:"read_only",maxTurns:25,model:f.model||"claude-sonnet-5",sessionId:b,resume:!I,onLog:(be,Ce)=>{be==="agent"&&w.send({type:"chat.stream",requestId:f.requestId,seq:z++,text:Ce.slice(0,8e3)})}})}finally{V&&yn.default.rmSync(V.dir,{recursive:!0,force:!0})}H.ok&&Xc(f.projectId,b,f.message,H.resultText),w.sendChatTurnResult(f.requestId,{ok:H.ok,sessionId:b,reply:H.resultText,error:H.ok?void 0:H.error??"the agent produced no reply"})},onChatList:f=>{w.sendChatListResult(f.requestId,Qc(f.projectId))},onChatLoad:f=>{let g=Co(f.sessionId);w.sendChatLoadResult(f.requestId,{ok:g!==null,projectId:g?.projectId??"",messages:g?.messages??[],error:g?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async f=>{let g=S(f.projectId);if(!g){w.sendBoardFetchResult(f.requestId,{ok:!1,columns:[],error:"this runner has no local checkout mapped for that project"});return}try{let b=n(g.project.repoName),I;try{I=await b.searchBoard(`project = "${g.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{I=await b.searchBoard(`project = "${g.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let N=await b.boardColumns(g.project.jiraProjectKey),V;if(N){V=N.map(z=>({name:z.name,issues:[]}));let J=new Map;for(let z of I){let H=N.findIndex(Ce=>Ce.statusIds.includes(z.statusId)),be={key:z.key,summary:z.summary,labels:z.labels};if(H>=0)V[H].issues.push(be);else{let Ce=J.get(z.status)??[];Ce.push(be),J.set(z.status,Ce)}}for(let[z,H]of J)V.push({name:z,issues:H})}else{let J=de=>de.trim().toLowerCase(),z=new Map,H=new Map;for(let de of I){let gt=J(de.status);z.has(gt)||z.set(gt,de.status.trim());let sa=H.get(gt)??[];sa.push({key:de.key,summary:de.summary,labels:de.labels}),H.set(gt,sa)}let be=[];try{be=await b.projectStatuses(g.project.jiraProjectKey)}catch{}let Ce=[];for(let de of be){let gt=J(de);!Ce.includes(gt)&&H.has(gt)&&Ce.push(gt)}for(let de of H.keys())Ce.includes(de)||Ce.push(de);V=Ce.map(de=>({name:z.get(de)??de,issues:H.get(de)??[]}))}let W=r.repos[g.project.repoName]?.jira??r.jira;w.sendBoardFetchResult(f.requestId,{ok:!0,browseBaseUrl:(W?.baseUrl??"").replace(/\/+$/,""),columns:V})}catch(b){w.sendBoardFetchResult(f.requestId,{ok:!1,columns:[],error:b instanceof Error?b.message:String(b)})}},onBoardTrigger:async f=>{let g=S(f.projectId);if(!g){w.sendBoardTriggerResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let b=n(g.project.repoName),I=f.comment.trim()?i(g.project.repoName,f.requestedByEmail):{jira:b,authored:!1};if(I.error!==void 0){w.sendBoardTriggerResult(f.requestId,{ok:!1,error:I.error});return}if(f.reimplement){let N=await b.getIssue(f.issueKey),V=N.comments.filter(z=>Ge(z.body)),W=V.length?Math.max(...V.map(z=>new Date(z.created).getTime())):0;if(!N.comments.some(z=>!Ge(z.body)&&new Date(z.created).getTime()>W)){w.sendBoardTriggerResult(f.requestId,{ok:!1,error:`${f.issueKey} has nothing new since the last implementation \u2014 add a comment describing what should change, then hit Implement again. Re-running with the same ticket would just rebuild the same thing.`});return}await b.editLabels(f.issueKey,{remove:["agent-implemented"]})}f.removeLabel.trim()&&await b.editLabels(f.issueKey,{remove:[f.removeLabel.trim()]}),f.comment.trim()&&await I.jira.addTriggerComment(f.issueKey,`${f.comment.trim()}`+(!I.authored&&f.requestedBy?`
|
|
677
687
|
|
|
678
688
|
_(requested by ${f.requestedBy} via Allwright)_`:"")),m.info(`Board action on ${f.issueKey}`+(f.comment?` comment "${f.comment.trim()}"`:"")+(f.removeLabel?` -label ${f.removeLabel}`:"")+(f.requestedBy?` by ${f.requestedBy}`:"")),w.sendBoardTriggerResult(f.requestId,{ok:!0})}catch(b){w.sendBoardTriggerResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onChatCreateTicket:async f=>{let g=S(f.projectId);if(!g){w.sendChatCreateTicketResult(f.requestId,{ok:!1,issueKey:"",error:"this runner has no local checkout mapped for that project"});return}try{let b=i(g.project.repoName,f.requestedByEmail);if(b.error!==void 0){w.sendChatCreateTicketResult(f.requestId,{ok:!1,issueKey:"",error:b.error});return}let I=`
|
|
679
689
|
|
|
680
690
|
---
|
|
681
691
|
_Created via Allwright Compose`+(!b.authored&&f.requestedBy?` by ${f.requestedBy}`:"")+", drafted with the project agent._",{key:N}=await b.jira.createIssue(g.project.jiraProjectKey,f.summary,(f.description||"(no description)")+I,f.asEpic?"Epic":"Task");f.files.length&&await b.jira.addAttachments(N,f.files.map(W=>({name:W.name,content:Buffer.from(W.contentBase64,"base64")}))).then(()=>m.info(`Compose attached ${f.files.length} file(s) to ${N}`)).catch(W=>m.warn(`Compose could not attach files to ${N}: ${W instanceof Error?W.message:W}`));let V=[];if(f.asEpic){for(let W of f.children){let J=await b.jira.createIssue(g.project.jiraProjectKey,W.summary,W.description||"(no description)","Task",N);V.push(J.key)}m.info(`Compose created epic ${N} with ${V.length} child ticket(s)`),w.sendChatCreateTicketResult(f.requestId,{ok:!0,issueKey:N,childKeys:V});return}f.triggerComment.trim()&&await b.jira.addTriggerComment(N,`${f.triggerComment.trim()}`+(!b.authored&&f.requestedBy?`
|
|
682
692
|
|
|
683
|
-
_(requested by ${f.requestedBy} via Allwright)_`:"")),m.info(`Compose created ${N}`+(f.requestedBy?` for ${f.requestedBy}`:"")+(f.triggerComment?` with trigger "${f.triggerComment.trim()}"`:"")),w.sendChatCreateTicketResult(f.requestId,{ok:!0,issueKey:N})}catch(b){w.sendChatCreateTicketResult(f.requestId,{ok:!1,issueKey:"",error:b instanceof Error?b.message:String(b)})}},onAuditStart:async f=>{let g=S(f.projectId);if(!g){w.sendAuditStartResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{m.info(`Audit (${f.role}) starting on ${g.project.repoName}`+(f.scope.kind!=="repo"?` scoped to ${f.scope.kind}:${f.scope.ref}`:""));let b=await
|
|
693
|
+
_(requested by ${f.requestedBy} via Allwright)_`:"")),m.info(`Compose created ${N}`+(f.requestedBy?` for ${f.requestedBy}`:"")+(f.triggerComment?` with trigger "${f.triggerComment.trim()}"`:"")),w.sendChatCreateTicketResult(f.requestId,{ok:!0,issueKey:N})}catch(b){w.sendChatCreateTicketResult(f.requestId,{ok:!1,issueKey:"",error:b instanceof Error?b.message:String(b)})}},onAuditStart:async f=>{let g=S(f.projectId);if(!g){w.sendAuditStartResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{m.info(`Audit (${f.role}) starting on ${g.project.repoName}`+(f.scope.kind!=="repo"?` scoped to ${f.scope.kind}:${f.scope.ref}`:""));let b=await Qr({projectId:f.projectId,repoPath:g.repoPath,role:f.role,scope:f.scope,model:f.model,claudeBin:r.claudeBin,jira:n(g.project.repoName)});if(!b.ok){w.sendAuditStartResult(f.requestId,{ok:!1,error:b.error});return}w.sendAuditStartResult(f.requestId,{ok:!0,audit:b.audit})}catch(b){w.sendAuditStartResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onAuditList:async f=>{try{w.sendAuditListResult(f.requestId,{ok:!0,audits:Zu(f.projectId)})}catch(g){w.sendAuditListResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditGet:async f=>{try{let g=Vu(f.projectId,f.auditId);if(!g){w.sendAuditGetResult(f.requestId,{ok:!1,error:"audit not found on this runner"});return}w.sendAuditGetResult(f.requestId,{ok:!0,audit:g})}catch(g){w.sendAuditGetResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditReview:async f=>{try{let g=to(f.projectId,f.auditId,{selected:f.selected,ticketed:f.ticketed,verdicts:f.verdicts,verdictBy:f.verdictBy});if(!g){w.sendAuditReviewResult(f.requestId,{ok:!1,error:"audit not found on this runner"});return}let b=S(f.projectId);if(b&&f.verdicts.length){let I=[];for(let N of f.verdicts){if(N.verdict==="valid"||g.lessonsWritten.includes(N.findingId))continue;let V=g.findings.find(W=>W.id===N.findingId);V&&(so(b.repoPath,g.role,Xu(V,N.verdict,N.note,f.verdictBy)),I.push(N.findingId),m.info(`Lesson written (${g.role}): ${N.verdict} \u2014 ${V.title.slice(0,60)}`))}I.length&&(g=to(f.projectId,f.auditId,{markLessonsWritten:I})??g)}w.sendAuditReviewResult(f.requestId,{ok:!0,audit:g})}catch(g){w.sendAuditReviewResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeList:async f=>{let g=S(f.projectId);if(!g){w.sendKnowledgeListResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{w.sendKnowledgeListResult(f.requestId,{ok:!0,files:ec(g.repoPath)})}catch(b){w.sendKnowledgeListResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onKnowledgeSave:async f=>{let g=S(f.projectId);if(!g){w.sendKnowledgeSaveResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{f.append?so(g.repoPath,f.role,Qu(f.content,f.by),f.level):tc(g.repoPath,f.role,f.level,f.source,f.name,f.content),m.info(`Knowledge ${f.append?"taught":"saved"}: ${f.role}/${f.level}/${f.name}`),w.sendKnowledgeSaveResult(f.requestId,{ok:!0})}catch(b){w.sendKnowledgeSaveResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onEpicList:async f=>{let g=S(f.projectId);if(!g){w.sendEpicListResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let b=n(g.project.repoName);if(f.epicKey){let I=await b.epicChildren(f.epicKey);w.sendEpicListResult(f.requestId,{ok:!0,children:I})}else{let I=await b.searchEpics(g.project.jiraProjectKey);w.sendEpicListResult(f.requestId,{ok:!0,epics:I})}}catch(b){w.sendEpicListResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onEpicSuggest:async f=>{let g=S(f.projectId);if(!g){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let b=n(g.project.repoName),I=await b.epicChildren(f.epicKey),N=Ru(I);if(!N.length){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:`every child of ${f.epicKey} is already done or in an agent's hands \u2014 nothing to sequence`});return}if(N.length===1){w.sendEpicSuggestResult(f.requestId,{ok:!0,issueKey:N[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let V=await Promise.all(N.slice(0,12).map(async H=>{try{let be=await b.getIssue(H.key);return{...H,description:be.description}}catch{return{...H,description:""}}})),W=(await b.getIssue(f.epicKey).catch(()=>null))?.summary??"";m.info(`Epic suggest: weighing ${V.length} pending children of ${f.epicKey}`);let J=await Ue.run({repoPath:g.repoPath,prompt:$u(f.epicKey,W,V),timeoutSeconds:150,bin:r.claudeBin,mode:"read_only",maxTurns:20,sessionId:(0,Xo.randomUUID)(),model:f.model||"claude-sonnet-5",onLog:()=>{}}),z=Pu(J.resultText,V.map(H=>H.key));if("error"in z){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:z.error});return}m.info(`Epic suggest: ${f.epicKey} -> do ${z.issueKey} first`),w.sendEpicSuggestResult(f.requestId,{ok:!0,issueKey:z.issueKey,reason:z.reason,considered:V.length})}catch(b){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onTeamCreds:async f=>{try{let g=ce()??r;if(g.github?.token&&!g.github.login)try{let{GitHubClient:I}=await Promise.resolve().then(()=>(ct(),tn));g.github.login=await new I(g.github.token).whoami(),ie(g)}catch{}let b=Tu(g,f.emails);w.sendTeamCredsResult(f.requestId,{ok:!0,...b})}catch(g){w.sendTeamCredsResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupStatus:async f=>{try{let g=ce()??r,{buildSetupReport:b}=await Promise.resolve().then(()=>(hd(),dd)),I=await b(g,f.repoNames);w.sendSetupStatusResult(f.requestId,{ok:!0,...I})}catch(g){w.sendSetupStatusResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onJiraUsers:async f=>{try{let g=await e.searchUsers(f.query);w.sendJiraUsersResult(f.requestId,{ok:!0,users:g})}catch(g){w.sendJiraUsersResult(f.requestId,{ok:!1,users:[],error:g instanceof Error?g.message:String(g)})}}});p.transport=w,d=new qs(r,n,w);let j=Object.values(sn()).filter(f=>f.kind==="implement").map(f=>f.repoPath);Bi(Object.values(r.repos).map(f=>f.path),j).catch(()=>{}),w.start(),d.start();let U=()=>{m.info("shutting down"),d.stop(),w.stop(),La(process.pid),process.exit(0)};process.on("SIGINT",U),process.on("SIGTERM",U)}ae.command("start").description("Start watching Jira. Runs in the background by default \u2014 close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async r=>{let e=Q();if(r.foreground){uy(e);return}let t=qr();if(t&&Tn(t)){m.info(`already running in the background (pid ${t}). Use \`allwright status\` or \`stop\`.`);return}let n=Ma(),s=(0,Wn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",n,n]});s.unref(),Da(s.pid),m.info(`Runner started in the background (pid ${s.pid}).`),m.info(`Logs: ${ds()}`),m.info("It will keep polling Jira until you run `allwright stop` \u2014 closing this terminal is fine.")});ae.command("stop").description("Stop the background runner started by `start`").action(()=>{let r=qr();if(!r||!Tn(r)){m.info("no background runner is running"),r&&yn.default.rmSync(Sn(),{force:!0});return}process.kill(r,"SIGTERM"),m.info(`stop signal sent (pid ${r})`)});ae.command("status").description("Check whether the background runner is running").action(()=>{let r=qr();r&&Tn(r)?m.info(`running in the background (pid ${r})`):m.info("not running")});ae.parseAsync().catch(r=>{m.error(r instanceof Error?r.message:String(r)),process.exit(1)});
|